# Always missing one component in Image Segmentation with SelectComponents-WatershedComponents-GradientFilter Method

I hope this is not a too specific issue and it is probably something very simple, but it is driving me insane. I am trying some image processing on microscopy images to perform cell isolation as exemplified in the wolfram reference;

http://reference.wolfram.com/language/example/AnalyzeSegmentedCellsInAnImage.html

I start with the following test image "img":

And after the usual adjustments steps below:

iAdj = img // ImageAdjust;
grad = GradientFilter[iAdj, 1] // ImageAdjust;
bg = Binarize[grad];
dsc = DeleteSmallComponents[bg, 5];
merge = iAdj*.8 + bg*.2 // ImageAdjust;
bin2 = Binarize[merge];
dsc2 = DeleteSmallComponents[bin2, 5000];
max = MaxDetect[DistanceTransform[dsc2], 4] // ImageAdjust;
gf = GradientFilter[dsc2, 1];


I have the maximum points image to use as local markers ad the gradientfilter image that defines the different regions to isolate and

mgf = max + gf


looks good

however when I perform the component selection from the watershed components analysis:

gf = GradientFilter[dsc2, 1];
nuclei = SelectComponents[WatershedComponents[gf, max], "Area", 100 < # < 100000 &];
Colorize[nuclei];


I always get one cell less than what I should.

Please note that this is not due to the Area parameter as the cells have all an area less than 100000 and setting it to 1000000 does not solve the problem. Furthermore changing the GradientFilter radius from 1 to 2 to 3 etc... results in a different cell missing:

with:

 gf = GradientFilter[dsc2, 2];
nuclei = SelectComponents[WatershedComponents[gf, max], "Area", 100 < # < 100000 &];
Colorize[nuclei];


I get:

with:

 gf = GradientFilter[dsc2, 3];
nuclei = SelectComponents[WatershedComponents[gf, max], "Area", 100 < # < 100000 &];
Colorize[nuclei];


I get:

Any help to solve the issue or at least to understand what is happening is highly appreciated.

• Adding an extra marker for the background seems to do the trick: ReplaceImageValue[max, {0, ImageDimensions[max][[2]]} -> 1]. This way you can remove it by doing SelectComponents[matrix, #Label != 1 &]. There is still an issue with cells on the top left corner though... – Batracos May 24 '18 at 18:09