Watershed segmentation and background subtraction
Separating touching objects with markers and a distance transform, and finding moving objects with a median background model.
- Build markers from a distance transform and run marker-based watershed
- Estimate a static background as a per-pixel median over time
- Explain why the median survives passing objects and the mean does not
Two classical segmentation techniques close the course: one for objects that touch, one for objects that move.
Watershed: splitting touching coins
Thresholding the coins image gives one white blob: the coins touch, so cv2.connectedComponents on the cleaned mask finds a single object. watershed_algorithm_revision.py separates them in seven steps:
ret, thresh = cv.threshold(gray_img, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU)
opening = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=2) # remove specks
sure_bg = cv.dilate(opening, kernel, iterations=3) # surely background outside
dist_transform = cv.distanceTransform(opening, cv.DIST_L2, 5)
ret, sure_fg = cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
unknown = cv.subtract(sure_bg, np.uint8(sure_fg))
ret, markers = cv.connectedComponents(np.uint8(sure_fg))
markers = markers + 1 # background becomes 1, not 0
markers[unknown == 255] = 0 # 0 = let watershed decide
markers = cv.watershed(image=img, markers=markers)
The distance transform gives each foreground pixel its distance to the nearest background pixel. Coin centres are far from any edge, the necks where coins touch are close, so thresholding at 70% of the maximum leaves one small seed per coin. Watershed then floods the image from those seeds, treating intensity as height; where two floods meet it builds a dam, labelled −1.
The seed threshold (0.7) is the knob: too high and a small coin gets no seed and merges with a neighbour; too low and seeds of touching coins join into one.
Background subtraction
14_app_01.py estimates the background of a video with a fixed camera: pick 25 random frames and take the median of each pixel over time.
frameIds = cap.get(cv2.CAP_PROP_FRAME_COUNT) * np.random.uniform(size=25)
frames = []
for fid in frameIds:
cap.set(cv2.CAP_PROP_POS_FRAMES, fid)
ret, frame = cap.read()
frames.append(frame)
medianFrame = np.median(frames, axis=0).astype(dtype=np.uint8)
A car passes any one pixel only briefly. As long as the pixel shows the road in more than half of the sampled frames, the median is the road. The mean has no such protection — every car drags it towards its own colour:
The script’s video is not in the repository, so the same steps were run on the traffic clip from the optical-flow lesson:
Then each frame is compared with the background:
dframe = cv2.absdiff(frame, grayMedianFrame)
th, dframe = cv2.threshold(dframe, 30, 255, cv2.THRESH_BINARY)
As in lesson 10, the loop while ret: ret, frame = cap.read(); cv2.cvtColor(frame, ...) converts the None returned after the last frame and fails; checking ret before using frame ends it cleanly. The script also imports skimage.data, filters without using them, which adds a dependency for nothing.
For cameras that move slightly or scenes whose lighting drifts, OpenCV’s adaptive models update the background continuously: cv2.createBackgroundSubtractorMOG2() keeps a mixture of Gaussians per pixel.
Try it yourself. In the watershed script, change the seed threshold from 0.7 to 0.4 and 0.9 and count the regions each time. For the background, replace np.median with np.mean and compare the foreground masks; then try cv2.createBackgroundSubtractorMOG2 on the same video and compare its mask after the first 100 frames.