Watershed fails to properly segmented objects
00:04 12 Nov 2025

Currently I'm working on object detection for counting how many object presented on the frame. I already successfully separate some of them. There's still some object which is very close together which it turns into one blob I still don't know how to separate it properly since other touching object which just the tip can be separated. Also there are objects which in my distance transformation visualization looks pretty clear but some how the peak_local_max() function not recognized the object so its not giving a peak coordinates correctly and then on the watershed section that object is gone. Are there something I did wrong? Here is my debugging image.

Debug View

Here is my sample_image if you wanted to try.

sample_image

My watershed code is simple, I use a helper scipy's ndimage

mask_filled = cv2.erode(mask_filled, kernel=np.ones((2,2), np.uint8), iterations=1)

 dist = ndimage.distance_transform_edt(mask_filled.copy())
peaks = peak_local_max(dist, min_distance=40, labels=mask_filled.copy())
dist_visual = cv2.normalize(dist, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) 

peak_map = cv2.cvtColor(dist_visual.copy() * 255, cv2.COLOR_GRAY2BGR)
for (py, px) in peaks:
    cv2.circle(peak_map, (px, py), 3, (0, 0, 255), -1)

local_max = np.zeros_like(dist, dtype=bool)
local_max[tuple(peaks.T)] = True
markers = ndimage.label(local_max)[0]
labels = watershed(-dist, markers, mask=mask_filled.copy())

watershed_vis = np.zeros((mask_filled.copy().shape[0], mask_filled.copy().shape[1], 3), dtype=np.uint8)
for label in np.unique(labels):
    if label == 0:
       continue
# generate random color for each region
color = np.random.randint(15, 255, size=(3,), dtype=np.uint8)
watershed_vis[labels == label] = color
python opencv computer-vision watershed