#include <opencv2\opencv.hpp>void colorreduce (cv::mat &image, int div=64) {int nr= image.rows;//number of row s int nc= image.cols * image.channels (); Total number of elements per line for (int j=0; j<nr; J + +) {//Get the address of row j//ptr:it is a template meth OD that returns the address of row number j:uchar* Data= image.ptr<uchar> (j); for (int i=0; i<nc; i++) {//we could has equivalently used pointer arithmetic to move from column to column//Proces s each pixel---------------------//data[i]= data[i]/div*div + div/2; data[i]= Data[i]-data[i]%div + div/2;//mask used to round the pixel valueint n=6;uchar mask= 0xff<<n;data[i]= (dat A[i]&mask) + div/2;//e.g. for div=16, mask= 0xf0//end of pixel Processing----------------}}} int main (int argc,char* argv[]) {Cv::mat pimg;pimg=cv::imread ("lena.jpg"); Cv::namedwindow ("Image"); Cv::imshow (" Image ", pImg); Colorreduce (PIMG); Cv::namedwindow (" pImg "); Cv::imshow (" pImg ", PIMG); CV:: Waitkey (0); CV::d Estroywindow ("Image"); return 0;}
Color reduction is achieved by taking advantage of a integer division that floors the division result to the nearest Lowe R integer:
data[i]= Data[i]/div*div + div/2;
The reduced color could has also been computed using the modulo operator which brings us to the nearest multiple of Div ( The 1D reduction Factor):
data[i]= Data[i]–data[i]%div + div/2;
But this computation are a bit slower because it requires reading each pixel value twice.
Another option would is to use bitwise operators. Indeed, if we restrict the reduction factor to a power of 2, that's, Div=pow (2,n), then masking the first n bits of the P Ixel value would give us the nearest lower multiple of Div. This mask would is computed by a simple bit shift:
Mask used to round the pixel value
Uchar mask= 0xff<<n;
e.g. for div=16, mask= 0xF0
The color reduction would is given by:
Data[i]= (data[i]&mask) + DIV/2;
In general, bitwise operations leads to very efficient code, so they could constitute a powerful alternative when Efficienc Y is a requirement.
Opencv.2.computer.vision.application.programming.cookbook--scanning an image with pointers