查找图像中连续的黑色像素 [英] Find contiguous black pixels in image

查看:181
本文介绍了查找图像中连续的黑色像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用OpenCV的findContours()查找连续的黑色像素区域.有时,它会选择围绕黑色像素的白色像素区域,例如在此图中,"g","e"和"n"与黑色像素一样被选中,但是其他三个字母由白色像素的周围区域选择,如轮廓的绿色点所示:

I have been using OpenCV's findContours() to find areas of contiguous black pixels. Sometimes it selects the area of white pixels surrounding the black pixels, e.g. in this figure the "g", "e", and "n" are selected with black pixels as I expect, but the other three letters are selected by the surrounding area of white pixels, as shown by the green points of the contour:

有时,将碗内部带有白色区域的"g"选择为轮廓,而有时碗内部具有白色轮廓的是不同的轮廓.

Sometimes, the "g" with the white area inside the bowl is selected as a contour, and other times the white area inside the bowl is a different contour.

对于两个示例,我都可以处理层次结构并检查哪些轮廓是其他轮廓的子轮廓,但是我想我缺少了一些简单的东西.

For both examples, I could deal with the hierarchy and check which contours are children of which other contours, but I think I am missing something simpler.

如何让OpenCV选择并返回连续的黑色像素的每个单独区域?

How can I get OpenCV to select and return each separate area of contiguous black pixels?

推荐答案

这是由findContours引起的,该问题始于在黑色背景上寻找白色形状.只需反转图像即可改善结果.下面的代码将通过按键一一绘制轮廓,因此您可以看到被选中的是黑色像素.

This is caused by findContours, that starts by looking for white shapes on a black background. Simply inverting you image will improve results. The code below will draw contours one by one with a keypress, so you can see that it is the black pixels that are selected.

import cv2
import numpy as np
# Read image in color (so we can draw in red)
img = cv2.imread("vBQa7.jpg")
# convert to gray and threshold to get a binary image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, dst = cv2.threshold(gray, 20, 255, cv2.THRESH_BINARY)
# invert image
dst = cv2.bitwise_not(dst)
# find contours
countours,hierarchy=cv2.findContours(dst,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# draw contours
for cnt in countours:
        cv2.drawContours(img,[cnt],0,(0,0,255),2)
        cv2.imshow("Result",img)
        cv2.waitKey(0)
# show image
cv2.imshow("Result",img)
cv2.waitKey(0)
cv2.destroyAllWindows()

您会发现还选择了一些黑色的小块以及背景区域.您可以通过设置最小和最大尺寸来删除它们,并检查每个轮廓的contourArea. (文档)

You'll find that there are also some small black patches selected, as well as the background area. You can remove these by setting a minimum and maximum size and check the contourArea for each contour. (docs)

这篇关于查找图像中连续的黑色像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆