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

  1. Read and Convert the Image to Grayscale
    matlab
    Copy
    % Read the image
    I = imread('coins.png');
    % Convert to grayscale if necessary
    if size(I, 3) == 3
        I = rgb2gray(I);
    end
  2. Compute Gradient Magnitude
    matlab
    Copy
    % Calculate gradient magnitude
    [Gmag, ~] = imgradient(I);
  3. Morphological Preprocessing to Identify Markers
    • Smooth the Image using morphological operations to remove noise.
      matlab
      Copy
      se = strel('disk', 20);
      I_opened = imopen(I, se);
      I_closed = imclose(I_opened, se);
    • Identify Foreground Markers using regional maxima.
      matlab
      Copy
      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.
      matlab
      Copy
      bw = imbinarize(I_closed);
      D = bwdist(bw);
      DL = watershed(D);
      bgm = DL == 0; % Watershed ridge lines as background
  4. Impose Markers on Gradient Magnitude
    matlab
    Copy
    % Combine foreground and background markers
    modified_grad = imimposemin(Gmag, fgm | bgm);
  5. Apply Watershed Algorithm
    matlab
    Copy
    L = watershed(modified_grad);
  6. Visualize the Result
    matlab
    Copy
    % 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 imregionalmaximclearborder, and bwareaopen to clean up markers.
  • Gradient Modificationimimposemin ensures only the specified markers are treated as minima, controlling segmentation.