In order to avoid oversegmentation by the watershed algorithm in Matlab, I would like to force the algorithm to segment into a specific number of segments (in the example here, the algorithm segments automatically into 4, and I would like it to segment into 2). Is there a general way to define the allowed number of output segments?
The code that I am currently using:
% Load the image
grayscaleImg = imread('https://i.sstatic.net/KyatF.png');
white_in_current_bits = 65535;
% Display the original image
figure;
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
hold on;
imshow(grayscaleImg);
title('The origianl image');
% Binarize the image.
binaryImageElement = grayscaleImg < white_in_current_bits;
% Calculate the distance transform
D = -bwdist(~binaryImageElement);
% Find the regional minima of the distance matrix:
mask = imextendedmin(D,2);
%Display the mask on top of the binary image:
figure;
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
imshowpair(binaryImageElement,mask,'blend');
title('Blend of binary image and the regional minima mask');
%Impose the regional minima on the distance transform:
D2 = imimposemin(D,mask);
%Watershed the distance transform after imposing the regional minima:
Ld2 = watershed(D2);
%Display the binary image with the watershed segmentation lines:
bw3 = binaryImageElement;
bw3(Ld2 == 0) = 0;
figure;
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
imshow(bw3);
title('Binary image after watershedding');
There is no direct way to specify the number of regions that the watershed will produce. The watershed will always produce one region per local minimum. But you can modify the image to reduce the number of local minima. One approach is the H-minima transform. This function removes all local minima that are less deep than a threshold.
The idea would be to iterate (this might not be fast...) over thresholds until you get the desired number of regions.
% iterate over h, starting at 0
tmp = imhmin(D2,h);
Ld2 = watershed(tmp);
% count regions in Ld2, increase h and repeat
I just noticed that you impose minima in D2
. You determine these minima using imextendedmin
. This means you apply the H minima, find the resulting local minima, then impose those again. You might as well skip this step, and directly apply the H minima transform.