Watershed algorithm (there is a problem with the code, who can see it, please comment, thank you)

Watershed algorithm

step:

1 Load the original image

2 Threshold segmentation, the image is divided into black and white parts

3 Perform an open operation on the image, that is, first corrode and then expand

4 The result of the split operation is expanded to get the area that is mostly the background

5 Obtain the foreground area through Distance Transform

6 The background area sure_bg and the foreground area sure_fg are subtracted to obtain an overlapping area with both foreground and background

7 Connected area processing

8 Finally, use the watershed algorithm

There is a problem with the code, I don't know what is wrong. .

import cv2
import numpy as np
img = cv2.imread('test4.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
##第二:阈值分割,将图像分为黑白两部分
ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
#第三步:对图像进行开运算,先腐蚀再膨胀
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel,iterations=2)
#第四步:对开运算的结果进行膨胀,得到大部分都是背景的区域
sure_bg = cv2.dilate(opening,kernel,iterations=3)
cv2.imshow("sure_jpg",sure_bg)
cv2.waitKey(0)
cv2.destroyAllWindows()
#第五步:通过distanceTransform获取前景区域
dist_transform = cv2.distanceTransform(opening,jcv2.DIST_L2,5)
print(dist_transform.max())
ret,sure_fg = cv2.threshold(dist_transform,0.1*dist_transform.max(),255,0)
cv2.imshow('sure_fg',sure_fg)
cv2.waitKey()
cv2.destoryAllWindows()
#第六步:sure_bg与sure_fg相减,得到既有前景又有背景的重合区域
sure_fg = np.uint8(sure_fg)
unknow = cv2.subtract(sure_bg,sure_fg)
cv.imshow("unknow",unknow)
cv2.waitKey(0)
cv2.destoryAllWindows()
#第七步:连通区域处理
ret,markers = cv2.connectedComponents(sure_fg,connectivity=8)
print(ret)
markers = markers +1
markers[unknow==255] =0
#第八步:分水岭算法
markers = cv2.watershed(img,markers)
#分水岭算法后,所有轮廓的像素点被标注为-1
img[markers==-1]=[0,0,255]
cv2.imshow("dst",img)
cv2.waitKey()
cv2.destoryAllWindows()

The result of the code is only the first picture. I don't know what is wrong. Ask for answers

Guess you like

Origin blog.csdn.net/winggyn/article/details/113108096