如何使用Python和Opencv计算白色区域?

如何使用Python和Opencv计算白色区域?,python,opencv,Python,Opencv,我是triyng计算此图像中白色像素的面积: 我的代码: 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("oran

我是triyng计算此图像中白色像素的面积:

我的代码:

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()
我怎样才能解决这个问题?实际上,我的目的是找到食物盘的空白区域


谢谢您的回答。

这是一种选择。由于BGR中的白色是
(255,255,255)
,因此我建议您将图像转换为布尔值true,其中每个(独立)通道等于
255

b, g, r = cv2.split(img)
wb = b == 255
wg = g == 255
wr = r == 255
对于同一像素,所有通道的值必须为
255
True
),因此,请使用:

最后,获取真实值的计数和图像的大小,并找到白色像素的百分比:

img_size = r.size
white_pixels_count = np.sum(white_pixels_if_true)
white_area_ratio = white_pixels_count / img_size
给定图像的面积,您可以将面积乘以
白面积比
得到白面积。

谢谢您的建议,我找到了解决上述图片问题的方法。但我会试试你的建议

注意:我的托盘是白色区域,目前保持不变

我的解决方案:

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)

使用
whitePixelCount=cv2.countNonZero(掩码)
获取掩码中白色像素的计数。该函数将统计每个白色像素,包括与其他斑点隔离的像素。如果您想要一个百分比,请将
whitePixelCount
除以遮罩尺寸。由于托盘的形状是固定的,您可以先划分位置(五个盘子位置和空白),然后应用阈值(cv2.inrange)。这可能会显示更好的结果。或者如果你必须只使用颜色空间来获得空白区域。我认为自适应阈值函数比固定阈值更好。
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)