Lyber Lyber - 1 year ago 208
C++ Question

OpenCV: Grayscale color reduction

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

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 = (<Vec3b>(r, c)[0] +<Vec3b>(r, c)[1] +<Vec3b>(r, c)[2])/3 ;
tmp = (tmp/4)* 4;<Vec3b>(r, c)[0] = tmp;<Vec3b>(r, c)[1] = tmp;<Vec3b>(r, c)[2] = tmp;


my expected result is enter image description here

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

my image looks the same as the original image;enter image description here

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

enter image description hereand 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download