首页 > 解决方案 > 检测位于图像opencv侧面的对象

问题描述

我正在尝试检测图像中的多个对象;但是,某些对象位于边缘,因此图像中并未显示所有轮廓。我们如何检测以某种方式“裁剪”的对象?我们可以在图像边缘包围轮廓吗?

首先,我模糊了图像,应用了一个精巧的检测器,膨胀,然后侵蚀了边缘。
这是我的代码:

img = cv2.imread('porosity1.png')

img1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

blur = cv2.GaussianBlur(gray, (7,7),0)

med = np.median(blur)

lower = int(max(0,0.7*med))

upper = int(min(255,1.3*med))

edged = cv2.Canny(blur, lower, upper)

edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

这就是我得到的边缘检测,这对我来说很好。

在此处输入图像描述

但是,当我想填充轮廓以检查检测器是否能够检测到所有物体(甚至是图像侧面的物体)时,我得到了这个:

gray, cnts, hierarchy = cv2.findContours(edged, mode = cv2.RETR_CCOMP,method = cv2.CHAIN_APPROX_NONE )

cnts1 = []

external_contours = np.zeros(gray.shape)

for i,cnt in enumerate(cnts):
    
    
    #External contours
    if cv2.contourArea(cnt)>100.0: #To exclude small contour areas
        cv2.drawContours(external_contours, cnts, i, 1, -1)
        cnts1.append(cnt)
        
        
        #Last column in each row in the hierarchy

plt.imshow(external_contours, cmap='gray')

在此处输入图像描述

我想检测的原因是我想找到物体的封闭区域。

标签: pythonopencvcontouredge-detectioncanny-operator

解决方案


您可以cv2.convexHull对找到的轮廓使用功能,然后边缘上的轮廓将被关闭。


推荐阅读