【问题标题】:Calculate surface area of the non-white areas in a binary thresholded image (python)计算二进制阈值图像中非白色区域的表面积(python)
【发布时间】:2021-06-25 12:06:47
【问题描述】:
有哪些可能的方法来计算图像中非白色区域/灰色/黑色块的表面积?我尝试使用 cv2.contours 来获取形状、迭代轮廓并使用 cv2.contours 和cv2.arcLength(contour,True) 总结总面积和周长,但结果似乎与图像无关。
我也尝试在轮廓之前添加 Canny Edge Detection,但似乎仍然无法正常工作。
只是一个额外的上下文,我想将表面区域用作 ML 模型的特征)。
【问题讨论】:
标签:
python-3.x
opencv
image-processing
computer-vision
【解决方案1】:
您需要cv.countNonZero(img)。黑色像素的值为 0,白色/灰色像素的值更大。要查找非白色像素的数量,您必须在使用 countNonZero() 之前反转图像。
import cv2
img = cv2.imread('jwsFy.png', 0)
img = 255-img # invert image
n_black = cv2.countNonZero(img)
print("Number of dark pixels:")
print(n_black)
height, width = img.shape
n_total = height * width
print("Percentage of dark pixels:")
print(n_black / n_total * 100)