1 回答
TA贡献2016条经验 获得超9个赞
这是一种使用 OpenCV 的方法。我们使用 Otsu 的阈值来获得二值图像,这使我们得到所需的前景对象为白色,而背景为黑色。从这里我们使用cv2.countNonZero()
它返回蒙版上的白色像素数
查找白色像素的数量
pixels = cv2.countNonZero(thresh) # OR
# pixels = len(np.column_stack(np.where(thresh > 0)))
像素 198580
我们还可以计算像素与总图像面积的百分比
image_area = image.shape[0] * image.shape[1]
area_ratio = (pixels / image_area) * 100
面积比 24.43351838727459
import cv2
import numpy as np
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]
pixels = cv2.countNonZero(thresh)
# pixels = len(np.column_stack(np.where(thresh > 0)))
image_area = image.shape[0] * image.shape[1]
area_ratio = (pixels / image_area) * 100
print('pixels', pixels)
print('area ratio', area_ratio)
cv2.imshow('thresh', thresh)
cv2.waitKey(0)
如果您想获得单个硬币像素区域,那么您可以遍历每个轮廓。总面积应该相同
import cv2
import numpy as np
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
total = 0
for c in cnts:
x,y,w,h = cv2.boundingRect(c)
mask = np.zeros(image.shape, dtype=np.uint8)
cv2.fillPoly(mask, [c], [255,255,255])
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
pixels = cv2.countNonZero(mask)
total += pixels
cv2.putText(image, '{}'.format(pixels), (x,y - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255), 2)
print(total)
cv2.imshow('thresh', thresh)
cv2.imshow('image', image)
cv2.waitKey(0)
添加回答
举报