通过将RBG像素乘以数字不能正确获得灰度?

问题描述

我确实经历了我能找到的所有事情,但是图像处理仍然令人困惑。 作为最简单的任务,我要灰度4像素。使用我发现的两组数字之一,输出不是灰色的问题。谢谢您的帮助!

我现在的算法(不幸的是,我不能仅使用此cimg来使用opencv):

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");

四个ppm:

P3
2 2
255

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

输入:

enter image description here

输出(应为灰色):

enter image description here

解决方法

您错误地假设像素存储在R1G1B1R2G2B2R3G3B3中。 在CImg中,像素存储为R1R2R3 .... G1G2G3 ... B1B2B3...。 see the docs