I would like to explain a simple code on how to use the watershed here. I use OpenCV-Python, but I hope you can easily understand.
In this code, I use the watershed as a tool to highlight the background. (This example is a copy of the python C ++ code in the OpenCV cookbook). This is a simple case to understand the watershed. In addition, you can use the watershed to count the number of objects in this image. This will be a slightly extended version of this code.
1 . First, we download the image, convert it to shades of gray and set it to the appropriate value. I took Otsu binarization , so it will find the best threshold value.
import cv2 import numpy as np img = cv2.imread('sofwatershed.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
Below is the result:

(even this result is good because there is a lot of contrast between the front and background images)
2 - Now we need to create a marker. A marker is an image with the same size as the original image, which is 32SC1 (32-bit signed one channel).
Now in the original image there will be some areas where you are just sure that the part belongs to the front. Mark this area 255 in the marker image. Now the area in which you are sure to be the background is marked with the icon 128. The region in which you are not sure is marked with the sign 0. This we will do next.
A - Foreground area : - We already have a threshold image where the pills are white. We destroy them a bit, so we are sure that the remaining area belongs to the foreground area.
fg = cv2.erode(thresh,None,iterations = 2)
fg :

B - Background area : - Here we expand the threshold image so that the background area decreases. But we are sure that the remaining black area is 100% background. We set it to 128.
bgt = cv2.dilate(thresh,None,iterations = 3) ret,bg = cv2.threshold(bgt,1,128,1)
Now we get bg as follows:

C - Now add both fg and bg :
marker = cv2.add(fg,bg)
Below we get:

Now we can clearly understand from the above image that the white region is 100% ahead, the gray region is 100% background, and the black region is not sure.
Then convert it to 32SC1:
marker32 = np.int32(marker)
3 - Finally, apply the watershed and convert the result back to a uint8 image:
cv2.watershed(img,marker32) m = cv2.convertScaleAbs(marker32)
m:

4 - We spawn it correctly to get the mask and execute bitwise_and with the input image:
ret,thresh = cv2.threshold(m,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) res = cv2.bitwise_and(img,img,mask = thresh)
res:

Hope this helps !!!
THE ARK