How to do it...

The watershed segmentation is obtained through the use of the cv::watershed function. The input for this function is a 32-bit, signed, integer-marker image in which each nonzero pixel represents a label.

The idea is to mark some pixels of the image that are known to belong to a given region. From this initial labeling, the watershed algorithm will determine the regions to which the other pixels belong:

  1. First, we will create the marker image as a gray-level image and then convert it into an image of integers. We have conveniently encapsulated this step into a WatershedSegmenter class. Refer to the following code:
class WatershedSegmenter { private: cv::Mat markers; public: void setMarkers(const cv::Mat& markerImage) { // ...

Get OpenCV 4 Computer Vision Application Programming Cookbook - Fourth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.