cv2.findContours无法检测轮廓

3
我有两个二进制图像,我试图检测它们中的白色斑块的轮廓(右侧拼贴画中粉色轮廓是轮廓结果)。
对于Contour1,cv2.contourFind()工作得很好: Contour1 Image & Result 但对于Contour2,它表现得很奇怪: Contour2 Image & Result 这是它的函数调用:
#Convert Image to grayscale
img = cv2.imread(file_name)
img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
dilated = cv2.dilate(mask, kernel, iterations=2)
image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for contour in contours:
    [x, y, w, h] = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)

使用变量contours,我在找到的点周围画出矩形。我不明白为什么对于Contour1它有效,但对于看起来非常相似的Contour2却失败了。


1
请编辑您的问题,提供一个最小、完整和可验证的示例 - alkasm
完成,@AlexanderReynolds - Anjali
每张图像中contours有多少轮廓? - alkasm
Contour1 的值为 102,Contour2 的值为 1。 - Anjali
1
在查找轮廓之前,查看每个步骤(转换颜色、阈值化、膨胀)的输出图像,并查看图像发生了什么。看看是否有任何问题的迹象。 - alkasm
1个回答

7

错误: 二进制图像在 Contour2 中有一个细白色边框,而在 Contour1 中没有(我的问题!)。由于我只请求了外部轮廓,因此在cv2.RETR_EXTERNAL中。

image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

对于Contour2,只有最外层的框被检测到,因此没有绘制其子级。但是在Contour1中,二进制图像周围没有白色边框框,因此检测到了内部的白色斑点。
解决方案:使用cv2.RETR_LIST或cv2.RETR_CCOMP。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接