Watershed Segmentation in Python with cv2/skimage (grayscale image)

91 Views Asked by At

How do I get the watershed segmentation to work properly?

I want to use the watershed segmentation for a grayscale image, however i do not get the results i want/expect. There are clearly spots in my image which the segmentation does not recognize...

With the watershed segmentation i hoped to isolate every spot in my image, this is the raw version: raw image to be processed I already tried using skimage and opencv, orientated on the documentation and other tutorials. This is the best result i got: best result, done with opencv And here is my code for that:

#image is already grayscale
image = tif_stack[0]

ret1, thresh = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
kernel = np.ones((3,3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations = 0)

from skimage.segmentation import clear_border
opening = clear_border(opening)

sure_bg = cv2.dilate(opening, kernel, iterations=0)
opening = np.uint8(opening)
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 3)
ret2, sure_fg = cv2.threshold(dist_transform, 0.5*dist_transform.max(), 255, 0)
sure_fg = np.uint8(sure_fg)

unknown = np.zeros(image.shape, np.uint8)
sure_bg = np.uint8(sure_bg)
unknown = cv2.subtract(sure_bg,sure_fg, unknown)
ret3, markers = cv2.connectedComponents(sure_fg)

markers = markers + 10
markers[unknown==255] = 0

#create RGB version of image for watershed func
image3 = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
image3 = np.uint8(image3)
markers_w = cv2.watershed(image3, markers)

#just noticed that i used the wrong markers (markers instead of markers_w)
#to edit the original image
#however when using the correct one, the result gets worse (see following image)
image[markers==-1]= 255

#display image
plt.figure()
plt.imshow(image, cmap = "gist_gray", interpolation= "nearest")
plt.show()

Here is the result image when using image[markers_w==-1]= 255: result when using markers_w

0

There are 0 best solutions below