嘿,我的代码需要一些帮助,我读取了 ppm 文件,将颜色更改为黑色和白色,并希望将其保存到新文件中。我可以读取文件的标题并将其写入新文件,但我在更改颜色方面遇到了困难。我知道我可以用以下公式得到灰度值:0.299 * 红色分量 + 0.587 * 绿色分量 + 0.114 * 蓝色分量。有谁知道我如何将其编写为代码?
int main(int argc, char **argv)
{
FILE *oldFile, *newFile;
int width, height, max_colour;
oldFile = fopen("oldpic.ppm","rb");
newFile = fopen("newpic.ppm","wb");
fscanf (oldFile, "P6\n %d %d %d", &width, &height, &max_colour);
unsigned char *data = malloc(width*height);
fread(data,1,width*height,oldFile);
fprintf(newFile, "P6\n%d %d\n%d\n", width, height, max_colour);
for (int j = 0; j < width; ++j)
{
for (int i = 0; i < height; ++i)
{
unsigned char color[3];
color[0] = 0.299 * ? + 0.587 * ? + 0.114 * ?; /* red */
color[1] = 0.299 * ? + 0.587 * ? + 0.114 * ?; /* green */
color[2] = 0.299 * ? + 0.587 * ? + 0.114 * ?; /* blue */
(void) fwrite(color, 1, 3, newFile);
}
}
(void) fclose(newFile);
return 0;
}