python - cv2.findContours 无法检测轮廓

标签 python opencv image-processing contour

我有两个二值图像,我试图检测其中白色斑 block 的轮廓(拼贴右侧的粉红色轮廓是轮廓结果)。

cv2.contourFind() 对 Contour1 工作正常:

Contour1 Image & Result

但对于 Contour2,它表现得很奇怪:

Contour2 Image & Result

这是它的函数调用

#Convert Image to grayscale
img = cv2.imread(file_name)
img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
dilated = cv2.dilate(mask, kernel, iterations=2)
image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for contour in contours:
    [x, y, w, h] = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)

使用此 contours 变量,我在找到的点周围绘制矩形。 我不明白为什么它对 Contour1 有效,但对 Contour2 无效,因为它们看起来非常相似。

最佳答案

错误:二值图像在 Contour2 中有一个细的白色边框框,但在 Contour1 中没有(我的错!)。由于我要求外部轮廓,cv2.RETR_EXTERNAL in

image, contours, hierarchy = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

Contour2 只检测到最外层的框,因此它的子项都没有被绘制。但是在 Contour1 中,二值图像周围没有白色边框框,因此检测到内部白色 Blob 。

解决方案:使用cv2.RETR_LISTcv2.RETR_CCOMP

关于python - cv2.findContours 无法检测轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44601734/

相关文章:

python - scipy.interpolate.griddata 和 scipy.interpolate.Rbf 之间的区别

python - 如何从 .yaml 文件访问变量到机器人框架脚本?

python - wxPython 更改鼠标光标以通知长时间运行的操作

opencv - 使 : **all error 2 during opencv installation in ubuntu16. 10

java - OpenCV 2.4.9 在 eclipse Juno 上使用 java - Ubuntu 14.04

java - BackgroundSubtractor.apply() 不应该返回二进制掩码吗?

python - 如何在 Python 中访问类内的全局变量

python-2.7 - AWS Lambda 和 Numpy 库 - 导入多数组 numpy 扩展模块失败

c++ - OpenCV - 查找或访问未被 bg 包围的形状轮廓,仅由轮廓分隔

python - 向图像添加色度噪声