2017-06-17 188 views
0

我有两个二进制图像,我试图检测它们中的白色斑点的轮廓(拼贴右侧的粉色轮廓是轮廓结果)。cv2.findContours无法检测轮廓

cv2.contourFind()为Contour1工作的罚款:

Contour1 Image & Result

但轮廓2它的行事怪异:

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看起来非常相似时失败。

+1

请编辑您的问题提供了[最小的,完整的,和可核查的示例](https://stackoverflow.com/help/mcve)。 –

+0

完成,@AlexanderReynolds –

+0

每个图像的“轮廓”中有多少个轮廓? –

回答

1

错误:二进制图像在轮廓2中有一个薄的白色边框,但不在轮廓1(我的坏!)。因为我问外部轮廓,cv2.RETR_EXTERNAL

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

的轮廓2只有最外面的框检测的,所以它没有一个孩子得到了绘制。但是在Contour1中,二值图像周围没有白色边框,因此检测到内部白色斑点。

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