在Watershed opencv之后查找轮廓

时间:2018-06-15 21:06:40

标签: python opencv computer-vision watershed

我的部分代码遇到了一些麻烦。我想在Python中找到 cv.Watershed 算法后的轮廓。说实话,我不知道该怎么做。

这是我的代码

kernel = np.ones((3, 3), np.uint8)
# sure background area
sure_bg = cv2.dilate(image, kernel, iterations=5)
opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel, iterations=2)

# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 3)
ret, sure_fg = cv2.threshold(dist_transform, 0.4 * dist_transform.max(), 255, 0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
cv.imshow('mark ', sure_fg)
cv.waitKey(0)
# sure_fg = cv2.erode(sure_fg,kernel,iterations=3)
unknown = cv2.subtract(sure_bg, sure_fg)

# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)

# Add one to all labels so that sure background is not 0, but 1
markers = markers + 1

# Now, mark the region of unknown with zero

markers[unknown == 255] = 0

markers = cv2.watershed(img, markers)

m = cv2.convertScaleAbs(markers)
m = cv2.threshold(m, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

img[markers == -1] = [255, 255, 255]

_, contours, _ = cv2.findContours(img[markers == -1], cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img[markers == -1] = [255, 255, 255]标记完美,但如何将其转换为轮廓?

谢谢!

1 个答案:

答案 0 :(得分:1)

您无法在img上找到轮廓,但可以使用markers

现在,数组markers包含值-1,这是一个有符号整数。我将其转换为包含有符号整数markers1 = markers.astype(np.uint8)的数组,其中-1的值将替换为255的值。然后在结果上应用Otsu阈值,然后我找到了轮廓。

以下是您必须添加到现有代码的额外代码:

<强>代码:

img2 = img.copy()
markers1 = markers.astype(np.uint8)
ret, m2 = cv2.threshold(markers1, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)
cv2.imshow('m2', m2)
_, contours, hierarchy = cv2.findContours(m2, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)    
for c in contours:
#    img2 = img.copy()
#    cv2.waitKey(0)
    cv2.drawContours(img2, c, -1, (0, 255, 0), 2)

#cv2.imshow('markers1', markers1)
cv2.imshow('contours', img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

<强>结果:

enter image description here