I have a color image in ppm format and would like to convert it into a grayscale image. The text for this ppm image is in the ASCII code and I get the following when I open it in the text editor:
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. 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.
Problem 2) I then inserted the header line manually and inserted the first number (122) in the correct place. I now had a ppm file, but the new image does not fill the corresponding area completely. 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!