findContours在OpenCV中没有发现非常明显的轮廓?

时间:2016-05-20 20:44:58

标签: python opencv

我试图在Python 2.7中使用OpenCV来发现黑色矩形。我很困惑为什么我的轮廓查找代码没有发现PNG底部的黑色矩形(downloadable image, pre-grayscale):

enter image description here

显然,我想要发现大黑盒子。这是我的代码:

import cv2
import numpy as np 

img = cv2.imread(f)
# grayscale
imgrey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold and invert
ret, thresh = cv2.threshold(imgrey, 127, 255, cv2.THRESH_BINARY_INV)
# find contours, and draw red highlights around them
contours, h = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    x, y, w, h = cv2.boundingRect(cnt)
    mask = np.zeros(imgrey.shape, np.uint8)
    cv2.drawContours(mask, [cnt], 0, 255, -1)
    cv2.rectangle(img, (x-2, y), (x+w+2, y+h), (0, 0, 255), 3)
cv2.imwrite(f.replace('.png', '-output.png'), img)

我得到的输出看起来像这样 - 看起来很棒找到每个可能的轮廓除了我感兴趣的那个(注意周围没有红线)黑匣子):

enter image description here

我可以轻松找到排除较小轮廓的方法(例如,通过查看平均颜色值)。但是根本没有发现黑匣子的轮廓,我不知道该怎么做。

我做错了什么?

作为参考,如果我保存它,这就是thresh的样子 - 阈值似乎正常工作:

enter image description here

1 个答案:

答案 0 :(得分:0)

在下面的findContours之前尝试侵蚀和扩张(抱歉,我不熟悉python)

erode(thresh,thresh,Mat(),Point(-1,-1),20);
dilate(thresh,thresh,Mat(),Point(-1,-1),20);
通过这种方式,您将只获得一个轮廓

enter image description here

相关问题