无法通过将 RGB 像素与数字相乘来正确缩放?

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

我确实遍历了所有我能找到的东西,但图像处理仍然很混乱。 作为最简单的任务,我想对 4 个像素进行灰度化。使用我发现的两组数字中的任何一个,输出都不是灰色的问题。感谢您的帮助!

我现在的算法(遗憾的是我不能只使用 opencv 这个 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");

four.ppm:

P3
2 2
255

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

输入:

输出(应该是灰色的):

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