OpenCV findContours()仅返回一个外部轮廓

时间:2018-07-26 05:11:20

标签: python opencv captcha cv2 opencv-contour

我试图隔离验证码中的字母,我设法过滤了验证码,结果得到了黑白图像:

enter image description here

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

enter image description here

我正在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个轮廓。

2 个答案:

答案 0 :(得分:2)

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

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)

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

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)

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

enter image description here

答案 1 :(得分:0)

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

  1. 图像中带有“ bitwise_not”颜色的反色

  2. 使用RETR_LIST标志收集所有轮廓。请注意,它还会在手指内收集孔。

相关问题