In the previous post, we saw how to create a very small PGM image using a text file. We could have been doing it with any other programming language, as PGM is in text format. We will use C to create a PPM image, but before we must understand the structure of this format.
In a PGM image, each pixel is represented with one numerical value. With PPM , things change a little. Because PPM is an RGB format, we need three numerical value to represent the three channels of each pixel. If we write the data directly to a file, for three red pixels, after the header, we need to write:
255 0 0 255 0 0 255 0 0 ...
The magic number for a PPM image is P3, if the file is written in ascii mode, and P6 if it's written directly in binary. The following is a program that create a 5 by 3 PPM image containing random colours:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
FILE * file = fopen("image.ppm", "wb");
if(!file)
{
printf("Error! Cannot open file image.ppm");
exit(EXIT_FAILURE);
}
int width = 5;
int height = 3;
int i, j;
//header
fprintf(file, "P6\n%d %d\n255\n", width, height);
for(i=0; i<height; i++)
for(j=0; j<width; j++)
{
fputc((random()%255), file);//red
fputc((random()%255), file);//green
fputc((random()%255), file);//blue
}
fclose(file);
return 0;
}
The image below is a scaled version of the one generated by the code above on my machine:
In the next post we will do some image processing, using only a PPM image and our best friend language, C.
No comments:
Post a Comment