opencv(Python)中的connectedComponents不关心连接?

时间:2018-03-29 10:23:13

标签: python python-2.7 opencv image-processing opencv3.3

我遇到connectedComponents(或connectedComponentsWithStats)的问题,这是Python(2.7.12)中的opencv(3.3.0)函数。一个简单的代码如下:

import numpy as np
import cv2

img = np.zeros((4,4), dtype = np.uint8)
img[1,1] = 255
img[2,2] = 255
output = cv2.connectedComponents(img, 4)
print output[1]

返回

[[0 0 0 0]
 [0 1 0 0]
 [0 0 1 0]
 [0 0 0 0]]

这很奇怪,因为我要求连接组件具有连接4(而不是8)。因此,(1, 1)(2, 2)中的两个像素未连接,应该提供两个不同的连接组件,例如标记为1和2。

我犯了错误吗?

1 个答案:

答案 0 :(得分:0)

替换

output = cv2.connectedComponents(img, 4)

通过

output = cv2.connectedComponents(img, connectivity=4)

会给你

[[0 0 0 0]
 [0 1 0 0]
 [0 0 2 0]
 [0 0 0 0]]

或者提供所有3个参数

output =  cv2.connectedComponents(img, 4, cv2.CV_32S)

我不是100%为什么。我会把它留给那里的Python专家。从我的理解cv2.connectedComponents(img, 4)应该工作得很好。但它并没有