OpenCV  4.1.1-pre
Open Source Computer Vision
Looking for a C++ dev who knows OpenCV?
I'm looking for work. Hire me!
Image Segmentation with Distance Transform and Watershed Algorithm

Prev Tutorial: Point Polygon Test

Next Tutorial: Out-of-focus Deblur Filter

Goal

In this tutorial you will learn how to:

  • Use the OpenCV function cv::filter2D in order to perform some laplacian filtering for image sharpening
  • Use the OpenCV function cv::distanceTransform in order to obtain the derived representation of a binary image, where the value of each pixel is replaced by its distance to the nearest background pixel
  • Use the OpenCV function cv::watershed in order to isolate objects in the image from the background

Theory

Code

Explanation / Result

  • Load the source image and check if it is loaded without any problem, then show it:
source.jpeg
  • Then if we have an image with a white background, it is good to transform it to black. This will help us to discriminate the foreground objects easier when we will apply the Distance Transform:
black_bg.jpeg
  • Afterwards we will sharpen our image in order to acute the edges of the foreground objects. We will apply a laplacian filter with a quite strong filter (an approximation of second derivative):
laplace.jpeg
sharp.jpeg
  • Now we transform our new sharpened source image to a grayscale and a binary one, respectively:
bin.jpeg
  • We are ready now to apply the Distance Transform on the binary image. Moreover, we normalize the output image in order to be able visualize and threshold the result:
dist_transf.jpeg
  • We threshold the dist image and then perform some morphology operation (i.e. dilation) in order to extract the peaks from the above image:
peaks.jpeg
  • From each blob then we create a seed/marker for the watershed algorithm with the help of the cv::findContours function:
markers.jpeg
  • Finally, we can apply the watershed algorithm, and visualize the result:
final.jpeg