简体   繁体   English

将 ppm 图像转换为灰度图像

[英]Convert a ppm image into a grayscale image

I have a color image in ppm format and would like to convert it into a grayscale image.我有一个 ppm 格式的彩色图像,想将其转换为灰度图像。 The text for this ppm image is in the ASCII code and I get the following when I open it in the text editor:此 ppm 图像的文本采用 ASCII 代码,当我在文本编辑器中打开它时,我得到以下信息:

P3
# Created by GIMP version 2.10.0 PNM plug-in
500 539
255
187
107
74
181
101
68
189
... 

The real file is of course much longer.真正的文件当然要长得多。 I just copied the first lines in here.我只是在这里复制了第一行。 Here's what I've been trying to do to convert the image:这是我一直在尝试转换图像的方法:

#include <stdio.h>
#include <stdlib.h>
int main()
{

    int number1;

    int number2;

    int number3;

    FILE *in;

    in = fopen("image.ppm", "rb");

    FILE *out;

    out = fopen("newimage.ppm", "wb");

    fseek(in, 60, SEEK_SET);

    fseek(out, 60, SEEK_SET);

        while(!feof(in)) {

            fscanf(in,"%d",&number1);

            fscanf(in,"%d",&number2);

            fscanf(in,"%d",&number3);

            fprintf(out,"%d\n",(number1+number2+number3)/3);
        }

    fclose(in);

    fclose(out);


        return 0;

}

There are two problems:有两个问题:

1) The header will not be transferred to the new file. 1) header 不会被转移到新文件中。 If I execute the program as indicated above, the text editor shows:如果我按照上面的说明执行程序,文本编辑器会显示:

                     122
116
124
126
119
127
133
... 

I wanted to leave the first 60 bytes unchanged, because they are part of the header, instead they are replaced by spaces.我想保持前 60 个字节不变,因为它们是 header 的一部分,而是用空格代替。

Problem 2) I then inserted the header line manually and inserted the first number (122) in the correct place.问题 2) 然后我手动插入 header 行并将第一个数字 (122) 插入正确的位置。 I now had a ppm file, but the new image does not fill the corresponding area completely.我现在有一个 ppm 文件,但是新图像没有完全填充相应的区域。 The converted grayscale image now appears three times side by side in the first third of the image, while the lower section is black.转换后的灰度图像现在在图像的前三分之一处并排出现了三次,而下半部分是黑色的。

Thank you!谢谢!

If you want to keep the first 60 bytes identical, you shouldn't seek past them, but read 60 bytes from the source and then write those to the destination.如果你想保持前 60 个字节相同,你不应该越过它们,而是从源读取 60 个字节,然后将它们写入目标。

Also check this link to see why while(!feof(in)) is a bad idea: Why is “while (?feof (file) )” always wrong?还请查看此链接以了解为什么while(!feof(in))是一个坏主意: 为什么“while (?feof (file))”总是错误的?

Finally, you're writing only 1/3 of the data.最后,您只写入了 1/3 的数据。 You could repeat fprintf(out,"%d\n",(number1+number2+number3)/3);你可以重复fprintf(out,"%d\n",(number1+number2+number3)/3); 3 times to fix that. 3次来解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM