【发布时间】:2016-05-22 06:12:36
【问题描述】:
我正在尝试在 Python 2.7 中使用 OpenCV 发现黑色矩形。我很困惑为什么我的轮廓查找代码没有发现 PNG 底部的黑色矩形 (downloadable image, pre-grayscale):
显然,我想找出那个大黑匣子。这是我的代码:
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)
我得到的输出看起来像这样 - 它似乎在发现所有可能的轮廓方面做得非常出色除了我感兴趣的那个(注意黑框周围没有红线):
我可以轻松找到排除较小轮廓的方法(例如,通过查看平均颜色值)。但只是没有发现黑匣子的轮廓,我不知道该怎么做。
我做错了什么?
作为参考,如果我保存 thresh,这就是它的样子 - 阈值似乎工作正常:
【问题讨论】:
-
可能是因为它是如何连接到将它与整个黑框连接起来的那条长黑线。
-
你可以试试 Canny 边缘检测器,我相信……OpenCV 支持它。
-
@DanMašek 非常有趣,谢谢!该代码对于大多数矩形都可以正常工作,这是一个例外,因此很可能是连接...我会尝试...