Watershed Algorithm setting removing all connected components
<p>I'm using the watershed algorithm to try and segment touching nuclei. A typical image may look like:<a href="https://i.stack.imgur.com/KF7xV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KF7xV.jpg" alt="enter image description here"></a>
or this: <a href="https://i.stack.imgur.com/mh3m5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mh3m5.jpg" alt="enter image description here"></a></p>

<p>I'm trying to apply the watershed algorithm with this code:</p>

<pre><code>show(RGB_img)


%Convert to grayscale image
I = rgb2gray(RGB_img);

%Take structuring element of a disk of size 10, for the morphological transformations
%Attempt to subtract the background from the image: top hat is the
%subtraction of the open image from the original


%Morphological transformation to subtract background noise from the image
%Tophat is the subtraction of an opened image from the original. Remove all
%images smaller than the structuring element of 10
I1 = imtophat(I, strel('disk', 10));

%Increases contrast
I2 = imadjust(I1);
%show(I2,'contrast')
%Assume we have background and foreground and assess thresh as such 
level = graythresh(I2);
%Convert to binary image based on graythreshold
BW = im2bw(I2,level);
show(BW,'C');



BW = bwareaopen(BW,8);
show(BW,'C2');

BW = bwdist(BW) &lt;= 1;
show(BW,'joined');
%Complement because we want image to be black and background white
C = ~BW;
%Use distance tranform to find nearest nonzero values from every pixel
D = -bwdist(C);

%Assign Minus infinity values to the values of C inside of the D image
%   Modify the image so that the background pixels and the extended maxima
%   pixels are forced to be the only local minima in the image (So you could
%   hypothetically fill in water on the image

D(C) = -Inf;

%Gets 0 for all watershed lines and integers for each object (basins)
L = watershed(D);
show(L,'L');

%Takes the labels and converts to an RGB (Using hot colormap)
fin = label2rgb(L,'hot','w');

% show(fin,'fin');
im = I;

%Superimpose ridgelines,L has all of them as 0 -&gt; so mark these as 0(black)
im(L==0)=0;

clean_img = L;
show(clean_img)
</code></pre>

<p>For whatever reason after <code>C = ~BW;</code> the whole image goes dark. This very same code block has worked on a handful of other images, all of which were more "solid" or not as grainy as these. However, I thought I compensated for this with <code>BW = bwdist(BW) &lt;= 1;</code>. I've experimented a ton and I don't really know what's happening. Any help would be great!</p>

<p>Ps. this is the image after <code>BW = bwareaopen(BW,8);</code>
<a href="https://i.stack.imgur.com/EJFMi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EJFMi.png" alt="Image description here"></a></p>