【问题标题】:openCV: cannot detect small shapes using findContoursopenCV:无法使用 findContours 检测小形状
【发布时间】:2018-03-19 14:40:36
【问题描述】:

我正在尝试使用 cv2.findContours 在二进制图像中检测特定类型的形状 - 三角形、正方形、圆形,并用不同的颜色为每种类型着色。 以下代码适用于大形状,但不适用于小形状 - 大约 10*10 像素。

将 numpy 导入为 np 导入简历2

img = cv2.imread('1.jpg') gray = cv2.imread('1.jpg',0)

ret,thresh = cv2.threshold(gray,127,255,1)

等高线,h = cv2.findContours(thresh,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)

对于轮廓中的cnt: 近似 = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True) 打印长度(大约) 如果 len(大约)==3: 打印“三角形” cv2.drawContours(img,[cnt],0,(122,212,78),-1) elif len(大约)==4: 打印“正方形” cv2.drawContours(img,[cnt],0,(94,234,255),-1) elif len(大约)> 15: 打印“圆圈” cv2.drawContours(img,[cnt],0,(220,152,91),-1)

cv2.imshow('img',img) cv2.waitKey(0)

cv2.destroyAllWindows()

我使用的图片:before

结果:after

如果您能帮我解决这个问题,我将不胜感激!

【问题讨论】:

    标签: python opencv


    【解决方案1】:

    “cv2.approxPolyDP 中的第二个参数称为 epsilon,它是从轮廓到近似轮廓的最大距离。它是一个精度参数。需要明智地选择 epsilon 以获得正确的输出。” em>

    具有以下更改的相同代码的输出-

    approx = cv2.approxPolyDP(cnt,.03*cv2.arcLength(cnt,True),True)
    

    【讨论】:

    • 感谢您的重播。我检查了您的解决方案,它确实检测到了小正方形和矩形,但根本没有检测到圆形。
    • 我将圆圈的“elif len(approx) > 15”更改为“elif len(approx) > 7”。然后它会检测圆形,但它也可以是圆形以外的各种形状。
    • 是的,我只是举了一个例子。尝试不同的系数值,找出最适合问题的值。
    猜你喜欢
    • 1970-01-01
    • 2021-03-31
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多