Lyber - 1 month ago 17

C++ Question

I'm trying to reduce my grayscale image color from 256 to 4 using this formula

from http://docs.opencv.org/2.4/doc/tutorials/core/how_to_scan_images/how_to_scan_images.html

I assume that n is the reduction factor, for this case, it will be 10 color from the formula.

My code is as below.

`void Reduction(Mat image1)`

{

for (int r = 0;r < image1.rows;r++) {

for (int c = 0;c < image1.cols;c++) {

// get pixel

int tmp = (image1.at<Vec3b>(r, c)[0] + image1.at<Vec3b>(r, c)[1] + image1.at<Vec3b>(r, c)[2])/3 ;

tmp = (tmp/4)* 4;

image1.at<Vec3b>(r, c)[0] = tmp;

image1.at<Vec3b>(r, c)[1] = tmp;

image1.at<Vec3b>(r, c)[2] = tmp;

}

}

}

my expected result is

but from tmp = (tmp/4)*4; or tmp = ( tmp/8)*8;

my image looks the same as the original image;

then i tried changing it to tmp = (tmp/40)*40;

and I got this as the result which is similar to what I wanted for my result.

How does the formula works and what should I edit from my code to accurately get the result I wanted? ( like the expected result above)

Answer

This is a color quantization. This is a simple technique to reduce the number of colors in an image that relies on the *integer division*

Since the starting range has `256`

values, if you want to end up with `N`

colors, you need to *integer divide* and then multiply by `K = 256 / N`

.

So in your case, for `N=8`

you need a `K = 256 / 8 = 32`

, and for `N = 4`

you need `K = 256 / 4 = 64`

.

Source (Stackoverflow)

Comments