问题描述
我的目标是检测放置在白色表面上的物体。从那里,计算有多少,并计算每个的面积。
似乎该算法正在检测其边缘,但将其视为多个对象。
原图
边缘检测后的图片
部分图片有问题
结果
简而言之,我正在使用“canny”和“连接组件”,并且我得到的是小数对象而不是整个对象。
解决方法
以下代码应该可以完成这项工作,您可能需要调整 minItemArea 和 maxItemArea 以过滤对象。
import numpy as np
import cv2
import matplotlib.pyplot as plt
rgb = cv2.imread('/path/to/your/image/items_0001.png')
gray = cv2.cvtColor(rgb,cv2.COLOR_BGR2GRAY)
imh,imw = gray.shape
th = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,21,5)
contours,hier = cv2.findContours(th.copy(),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
out_img = rgb.copy()
minItemArea = 50
maxItemArea = 4000
for i in range(len(contours)):
if hier[0][i][3] != -1:
continue
x,y,w,h = cv2.boundingRect(contours[i])
if minItemArea < w*h < maxItemArea:
cv2.drawContours(out_img,[contours[i]],-1,1)
plt.imshow(out_img)