gpt4 book ai didi

python - OpenCV - Otsu 二值化后 RETR_EXTERNAL 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 22:41:56 26 4
gpt4 key购买 nike

我将 Otsu 的二值化应用于一张图像并得到了这个结果

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_TREE,但我需要它与 RETR_EXTERNAL 一起使用以进行下一个操作。这里有什么问题?

最佳答案

根据 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

关于python - OpenCV - Otsu 二值化后 RETR_EXTERNAL 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52512769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com