OpenCV 4 Computer Vision Application Programming Cookbook(Fourth Edition)
上QQ阅读APP看书,第一时间看更新

How to do it...

To reduce the number of colors in an image, follow the next steps:

  1. The signature of our color reduction function will be as follows. The user provides an image and the per-channel reduction factor div:
void colorReduce(cv::Mat image, int div=64); 

Here, the processing is done in-place; that is, the pixel values of the input image are modified by the function. See the There's more... section of this recipe for a more general function signature with input and output arguments.

  1. The processing is done simply by creating a double loop that goes over all the pixel values. The first loop scans every row, getting the pointer of the row image data:
   for (int j=0; j<image.rows; j++) { 
 
        // get the address of row j 
        uchar* data= image.ptr<uchar>(j); 
  1. The second loop goes over every column of the row pointer and applies the reduction of color with this formula:
        for (int i=0; i<nc; i++) { 
 
            // process each pixel --------------------- 
                  
                  data[i]=    data[i]/div*div + div/2; 
 
            // end of pixel processing ---------------- 
 
        } // end of line                    
     } 
}
  1. This function can be tested by loading an image and calling the function as follows:
   // read the image 
   image= cv::imread("boldt.jpg"); 
   // process the image 
   colorReduce(image,64); 
   // display the image 
   cv::namedWindow("Image"); 
   cv::imshow("Image",image);

This will give you, for example, the following image (refer to the book's graphics PDF to view this image in color), as shown in this screenshot:

Let's see how the preceding instructions work when we execute them.