How it works...

The core process of this algorithm is easy to build. It is a simple scanning loop that goes over each pixel, comparing its color with the target color. Using what we learned in the Scanning an image with iterators recipe of Chapter 2, Manipulating the Pixels, this loop can be written as follows:

     // get the iterators 
     cv::Mat_<cv::Vec3b>::const_iterator it=  
                           image.begin<cv::Vec3b>(); 
     cv::Mat_<cv::Vec3b>::const_iterator itend=  
                           image.end<cv::Vec3b>(); 
     cv::Mat_<uchar>::iterator itout= result.begin<uchar>(); 
 
     // for each pixel 
     for ( ; it!= itend; ++it, ++itout) { 
 
            // compute distance from target color 
            if (getDistanceToTargetColor(*it)<=maxDist) { 
                  *itout= 255; 
            } else { 
                 *itout= 0; 
            } 
    } 

The cv::Mat variable's image refers to the input ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.