To perform image segmentation using the watershed algorithm in MATLAB while minimizing over-segmentation
To perform image segmentation using the watershed algorithm in MATLAB while minimizing over-segmentation, follow these steps:
Step-by-Step Explanation and Code
- Read and Convert the Image to Grayscale
% Read the image I = imread('coins.png'); % Convert to grayscale if necessary if size(I, 3) == 3 I = rgb2gray(I); end
- Compute Gradient Magnitude
% Calculate gradient magnitude [Gmag, ~] = imgradient(I);
- Morphological Preprocessing to Identify Markers
- Smooth the Image using morphological operations to remove noise.
se = strel('disk', 20); I_opened = imopen(I, se); I_closed = imclose(I_opened, se);
- Identify Foreground Markers using regional maxima.
fgm = imregionalmax(I_closed); fgm = imclearborder(fgm); % Remove edge artifacts fgm = bwareaopen(fgm, 20); % Remove small regions
- Identify Background Markers using thresholding and distance transform.
bw = imbinarize(I_closed); D = bwdist(bw); DL = watershed(D); bgm = DL == 0; % Watershed ridge lines as background
- Smooth the Image using morphological operations to remove noise.
- Impose Markers on Gradient Magnitude
% Combine foreground and background markers modified_grad = imimposemin(Gmag, fgm | bgm);
- Apply Watershed Algorithm
L = watershed(modified_grad);
- Visualize the Result
% Convert labels to RGB for visualization Lrgb = label2rgb(L, 'jet', 'w', 'shuffle'); figure; imshow(Lrgb); title('Watershed Segmentation with Markers'); % Overlay watershed boundaries on original image boundaries = L == 0; superimposed = imoverlay(I, boundaries, [1 0 0]); figure; imshow(superimposed); title('Segmentation Overlay');
Key Considerations:
- Morphological Structuring Element Size: Adjust the disk size (
strel('disk', N)
) based on object sizes in your image. - Marker Refinement: Use
imregionalmax
,imclearborder
, andbwareaopen
to clean up markers. - Gradient Modification:
imimposemin
ensures only the specified markers are treated as minima, controlling segmentation.