问题描述
我的部分代码有些麻烦.我想在Python中的 cv.Watershed
算法之后找到轮廓.老实说,我不知道该怎么做.
I have some troubles with part of my code. I would like to find contours after cv.Watershed
algorithm in Python. To be honest, I don't know how to do it.
这是我的代码:
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]
的标记可以完美完成,但是如何将其转换为轮廓呢?
Marks with img[markers == -1] = [255, 255, 255]
are done perfectly, but how to convert it into contours?
谢谢!
推荐答案
您无法在img
上找到轮廓,但是可以使用markers
.
You cannot find contours on img
but you can using markers
.
现在数组markers
包含值-1,它是一个有符号整数.我将其转换为包含有符号整数markers1 = markers.astype(np.uint8)
的数组,其中带有-1
的值将替换为255
的值.然后在结果上应用Otsu阈值,然后找到轮廓.
Now the array markers
contains values of -1 which is a signed integer. I converted it to an array containing signed integers markers1 = markers.astype(np.uint8)
, where values with -1
will be replaced by values of 255
. Then applying Otsu threshold on the result I then found contours.
这是您必须添加到现有代码中的额外代码:
Here is the extra code that you have to add to the existing one:
代码:
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()
结果:
这篇关于在分水岭opencv之后查找轮廓的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!