简体   繁体   English

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

[英]OpenCV findContours() just returning one external contour

I'm trying to isolate letters in a captcha, I managed to filter a captcha and that result in this black and white image:我试图隔离验证码中的字母,我设法过滤了验证码,结果得到了这张黑白图像:

在此处输入图片说明

But when I tried to separate the letters with findContours method of OpenCV it just found a external contour that wraps my entire image, resulting in this image (black contour outside image).但是当我尝试使用 OpenCV 的 findContours 方法分离字母时,它只是发现了一个包裹我整个图像的外部轮廓,从而产生了这个图像(图像外的黑色轮廓)。

在此处输入图片说明

I'm using this code with Python 3 and OpenCV 3.4.2.17:我将此代码与 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)

I just want my final result is 5 contours outside each character.我只希望我的最终结果是每个字符外有 5 个轮廓。

The contour to be extracted should be in white, background being black.要提取的轮廓应为白色,背景为黑色。 I have modified your code a bit, eliminated the lines which were not adding any value.我稍微修改了您的代码,删除了没有添加任何值的行。

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

I am using RETR_TREE as the contour retrieval mode, which retrieves all the contours and creates full family hierarchy list.我使用 RETR_TREE 作为轮廓检索模式,它检索所有轮廓并创建完整的家庭层次结构列表。 Please find the documentation for the same here 请在此处找到相同的文档

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

In opencv4, the finContours method has been changed.在 opencv4 中,finContours 方法已更改。 Please use:请用:

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

Then iterate through contours and draw the rectangle around the contours然后遍历轮廓并围绕轮廓绘制矩形

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)

Save the image保存图像

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

I got result which looks like this -我得到的结果看起来像这样 -

在此处输入图片说明

You used flag RETR_EXTERNAL, which means it is looking only for outermost contours of objects, but not holes.您使用了标志 RETR_EXTERNAL,这意味着它只查找对象的最外层轮廓,而不是孔。 In your case the white object that covers a whole image with few holes (letters/digits) is found.在您的情况下,找到了覆盖整个图像且几乎没有孔(字母/数字)的白色物体。 You have two choices:你有两个选择:

  1. Inverse colors in your image with "bitwise_not"使用“bitwise_not”反转图像中的颜色

  2. Collect all contours with RETR_LIST flag.使用 RETR_LIST 标志收集所有轮廓。 Note that it will also collect holes inside digits.请注意,它还会收集数字内的孔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM