外部二值化后不工作

2024-04-28 23:12:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我将大津的二值化应用于一幅图像,得到了这个结果

enter image description here

之后,我使用以下代码在四个主要形状周围生成方框:

img = cv.imread('test_bin.jpg', 0)
_, cnts, _ = cv.findContours(img.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_NONE)

for cnt in cnts:
    x,y,w,h = cv.boundingRect(cnt)
    cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

cv.imwrite('test_cnt.jpg', img)

但是,我什么也没得到。它只返回一个轮廓,我想它可能是完整的图像本身。我看到它适用于RETR\u TREE,但我需要它在下一个操作中与RETR\u EXTERNAL一起使用。什么是失败?你知道吗


Tags: 代码test图像imgbincvexternaljpg
1条回答
网友
1楼 · 发布于 2024-04-28 23:12:24

根据OpenCV等高线documentation

In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.

但在您的情况下,这显然与要求相反,因此您只需反转图像,就可以简单地执行以下操作:

img = cv2.bitwise_not(img)

另外,请注意:

For better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection.

我使用了你的图像,得到了以下结果,在反转图像后。如果您想移除小方框,那么只需使用cv2.threshold获得一个二进制图像。你知道吗

enter image description here

相关问题 更多 >