如何在C中制作ppm文件的黑白图片? [英] How to do a black-and-white picture of a ppm file in C?

查看:70
本文介绍了如何在C中制作ppm文件的黑白图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我的代码需要一些帮助,我阅读了ppm文件,将颜色更改为黑白,并希望将其保存到新文件中.我可以读取文件的标题并将其写入新文件,但是我一直在努力改变颜色.我知道我可以使用以下公式获得灰度值:0.299 *红色分量+ 0.587 *绿色分量+ 0.114 *蓝色分量.有谁知道我该如何将其编写为代码?

hey I need a little help with my code, I read a ppm file, change the colors to black and white and want to save it to a new file. I could read the header of my file and write it to the new file but I've struggles with changing the colors. I know that I can get the grey value with the formula: 0.299 * red component + 0.587 * green component + 0.114 * blue component. Does anyone know how I can write this as a code?

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;
} 

推荐答案

您可能想要缩放的二进制算术.

You probably want scaled binary arithmetic.

此外,即使您可以将输入数据读取到一个大数组中,也可能更容易一次读取并处理一个像素.

Also, even though you can read the input data into a large array, it may be easier to read it and process it a pixel at a time.

在这里,您的代码经过重新设计以做到这一点:

Here's your code reworked to do just that:

int
main(int argc, char **argv)
{

    FILE *oldFile;
    FILE *newFile;
    int width;
    int height;
    int max_colour;

    oldFile = fopen("oldpic.ppm", "rb");
    newFile = fopen("newpic.ppm", "wb");

    fscanf(oldFile, "P6\n %d %d %d", &width, &height, &max_colour);

#if 0
    unsigned char *data = malloc(width * height);
    fread(data, 1, width * height, oldFile);
#endif

    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];
            unsigned int grey;

            fread(color, 1, 3, oldFile);

            grey = 0;
            grey += 299u * color[0];  // red
            grey += 586u * color[1];  // green
            grey += 114u * color[2];  // blue
            grey /= 1000;

            color[0] = grey;
            color[1] = grey;
            color[2] = grey;

            fwrite(color, 1, 3, newFile);
        }
    }

    fclose(oldFile);
    fclose(newFile);

    return 0;
}

这篇关于如何在C中制作ppm文件的黑白图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆