Step 1: Read in the Color Image and Convert it to Gray scale
Step 2: Use the Gradient Magnitude as the Segmentation Function
Use the Sobel edge masks, imfilter, and some simple arithmetic to compute the gradient magnitude. The gradient is high at the borders of the objects and low (mostly) inside the objects.
Can you segment the image by using the watershed transform directly on the gradient magnitude?
No. Without additional preprocessing such as the marker computations below, using the watershed transform directly often results in "oversegmentation.
Step 3: Mark the Foreground Objects
A variety of procedures could be applied here to find the foreground markers, which must be connected blobs of pixels inside each of the foreground objects. In this example you'll use morphological techniques called "opening-by-reconstruction" and "closing-by-reconstruction" to "clean" up the image. These operations will create flat maxima inside each object that can be located using imregionalmax.
Opening is an erosion followed by a dilation, while opening-by-reconstruction is an erosion followed by a morphological reconstruction. Let's compare the two. First, compute the opening using imopen.