【问题标题】:OpenCV findContours() just returning one external contourOpenCV findContours() 只返回一个外部轮廓
【发布时间】:2019-01-03 00:16:59
【问题描述】:

我正在尝试隔离验证码中的字母,我设法过滤了验证码,结果是这张黑白图像:

但是当我尝试使用 OpenCV 的 findContours 方法分离字母时,它只是找到了一个包裹我整个图像的外部轮廓,从而产生了这个图像(黑色轮廓外部图像)。

我将此代码与 Python 3 和 OpenCV 3.4.2.17 一起使用:

img = threshold_image(img)
cv2.imwrite("images/threshold.png", img)

image, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for i, contour in enumerate(contours):
    area = cv2.contourArea(contour)
    cv2.drawContours(img, contours, i, (0, 0, 0), 3)

cv2.imwrite('images/output3.png', img)

我只希望我的最终结果是每个字符外有 5 个轮廓。

【问题讨论】:

    标签: python opencv captcha cv2 opencv-contour


    【解决方案1】:

    要提取的轮廓应为白色,背景为黑色。我对您的代码进行了一些修改,删除了没有添加任何值的行。

    import cv2
    img = cv2.imread('image_to_be_read',0)
    backup = img.copy()   #taking backup of the input image
    backup = 255-backup    #colour inversion
    

    我使用 RETR_TREE 作为轮廓检索模式,它检索所有轮廓并创建完整的家庭层次结构列表。 Please find the documentation for the same here

    _, contours, _ = cv2.findContours(backup, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    

    在 opencv4 中,finContours 方法已更改。请使用:

    contours, _ = cv2.findContours(backup, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    

    然后遍历轮廓并在轮廓周围绘制矩形

    for i, contour in enumerate(contours):
         x, y, w, h = cv2.boundingRect(contour)
         cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 1)
    

    保存图片

    cv2.imwrite('output3.png', img)
    

    我得到的结果看起来像这样 -

    【讨论】:

    • 在 OpenCV 4 中,cv2.findContours 返回不同的值;对此代码使用contours, _ = ...。因为这是 StackOverflow,所以更新代码示例的编辑当然被拒绝了。
    【解决方案2】:

    您使用了 RETR_EXTERNAL 标志,这意味着它只寻找对象的最外层轮廓,而不是孔洞。在您的情况下,找到了覆盖整个图像的白色物体,带有几个孔(字母/数字)。你有两个选择:

    1. 使用“bitwise_not”在图像中反转颜色

    2. 使用 RETR_LIST 标志收集所有轮廓。请注意,它还会收集数字内的孔。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      相关资源
      最近更新 更多