Reputation: 61
I am triyng calculate the area of the white pixels in this image:
My code :
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread("tepsi.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv,(21, 10, 15), (30, 255, 255) )
cv2.imshow("orange", mask)
cv2.waitKey()
cv2.destroyAllWindows()
How can I solve this problem? Actually my purpose is to find empty areas of food tray.
Thank you for your answers.
Upvotes: 2
Views: 4406
Reputation: 61
Thanks for your advices, i found a solution for my problem for above picture. But i will try your advices...
Note: My tray is white area and it is constant for now.
My solution :
import numpy as np
import cv2
image = cv2.imread("petibor_biskuvi.png")
dimensions = image.shape
height= image.shape[0]
width = image.shape[1]
size = height*width
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV)
cnts, hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
size_elements = 0
for cnt in cnts:
cv2.drawContours(image,cnts, -1, (0, 0, 255), 3)
size_elements += cv2.contourArea(cnt)
print(cv2.contourArea(cnt))
cv2.imshow("Image", image)
print("size elements total : ", size_elements)
print("size of pic : ", size)
print("rate of fullness : % ", (size_elements/size)*100)
cv2.waitKey(0)
Upvotes: 4
Reputation: 11183
This is one option. Since white in BGR is (255, 255, 255)
, id suggest you convert the image to a boolean true where each (independent) channel equals to 255
:
b, g, r = cv2.split(img)
wb = b == 255
wg = g == 255
wr = r == 255
The value of all of the channels must be 255
(True
) for the same pixel, so, use np.bitwise_and:
white_pixels_if_true = np.bitwise_and(wb, np.bitwise_and(wg, wr))
Finally, get the count of the true value and the size of the image and find the percentage of white pixels:
img_size = r.size
white_pixels_count = np.sum(white_pixels_if_true)
white_area_ratio = white_pixels_count / img_size
Given the area of the image you can multiply the area by the white_area_ratio
to get the white area.
Upvotes: 1