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)
如果您想獲得單個硬幣像素區域,那么您可以遍歷每個輪廓??偯娣e應該相同
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)
添加回答
舉報