c++imagecimg

Can't get greyscaling right by multiplying RBG pixels with numbers?


I really went through everything I could find but image processing is still pretty confusing. As the simplest of tasks, I want to greyscale 4 pixels. The problem that the output is not grey using either of the two sets of numbers I found. Thank you for your help!

My algorithm right now (sadly I can't use opencv only this cimg thingy):

CImg<unsigned char> img1("/content/gdrive/My Drive/four.ppm");

int width = img1.width();
int height = img1.height();

int init;
unsigned char oldRed, oldGreen, oldBlue, newRed, newGreen, newBlue;
int index = 0;

for(int i = 0; i < width * height; i++){
    init = index;

    oldRed = img1.data()[index];
    index++;
    oldGreen = img1.data()[index];
    index++;
    oldBlue = img1.data()[index];

    newRed  = (oldRed * 0.21) + (oldGreen * 0.72) + (oldBlue * 0.07);
    newGreen = (oldRed * 0.21) + (oldGreen * 0.72) + (oldBlue * 0.07);
    newBlue = (oldRed * 0.21) + (oldGreen * 0.72) + (oldBlue * 0.07);

    index = init;
    img1.data()[index] = newRed;
    index++;
    img1.data()[index] = newGreen;
    index++;
    img1.data()[index] = newBlue;
    index++;
}

img1.save("out.ppm");

The four.ppm:

P3
2 2
255

0 255 255
255 0 255
255 255 0
0 0 255

Input:

enter image description here

Output (should be grey):

enter image description here


Solution

  • You're falsely assuming that the pixels are stored R1G1B1R2G2B2R3G3B3. In CImg the pixels are stored As R1R2R3....G1G2G3...B1B2B3.... see the docs