查找图像中连续的黑色像素

时间:2019-08-01 22:09:20

标签: opencv

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

example of selection of white area

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

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

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

2 个答案:

答案 0 :(得分:2)

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

enter image description here

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。 (docs

答案 1 :(得分:1)

我不知道这是否适合您的用例,但是您可以执行以下步骤:

  1. 使用过滤器/阈值识别黑色像素

  2. 使用聚类算法(我认为是DBscan)将像素分组在一起