カラー画像からグレースケール画像フォーマットの変換
カラー画像からグレースケール画像フォーマットの変換するプログラムなんですが、いまいち理解できていません。 プログラムはRGB構造体を使ってのものなんですが添削お願いいたします。
#include<stdio.h>
#include<stdlib.h>
typedef struct _RGB
{
unsigned char r;
unsigned char g;
unsigned char b;
} RGB;
int main(int argc, char *argv[])
{
int x, y;
unsigned char *in, *out;
int i, j, Magic, level;
unsigned char tmp[255];
RGB **pixels;
int width = 255;
int height = 255;
int size = width * height;
FILE *fin, *fout;
if(argc != 3){
printf("Usage : %s input outpu \n", argv[0]);
exit(1);
}
fin = fopen(argv[1], "rb");
fgets(tmp, 255, fin);
if(tmp[0] != 'P'){
return 0;
}
sscanf(tmp, "P%d", &Magic);
if(Magic < 1 || Magic > 6){
return 0;
}
do{
fgets(tmp, 255, fin);
}
while(tmp[0] == '#');
sscanf(tmp, "%d %d", &x, &y);
if(x < 1 || y < 1){
return 0;
}
fgets(tmp, 255, fin);
sscanf(tmp, "%d", &level);
printf("P%d\n", &Magic);
printf("%d %d\n", x, y);
printf("%d\n", level);
in = (unsigned char *)malloc(sizeof(unsigned char) *x*y);
fread(in, sizeof(unsigned char), x*y, fin);
pixels = (RGB**)malloc(width*sizeof(RGB*));
pixels[0] = (RGB* )malloc(size * sizeof(RGB));
for(i = 1; i < width; i++){
pixels[i] = pixels[i - 1] + height;
}
free(pixels[0]);
for(i = 1; i < width * height * 3; i++){
out[i] = pixels[i][0].r * 0.299 + pixels[i][1].g * 0.587 + pixels[i][2].b * 0.114;
}
fout = fopen(argv[2], "wb");
fprintf(fout,"P%d\n",Magic);
fprintf(fout,"# My new PGM\n");
fprintf(fout,"%d %d\n",x, y);
fprintf(fout,"%d\n",level);
fwrite(out, sizeof(unsigned char),x*y, fout);
free(pixels);
free(in);
free(out);
free(fin);
free(fout);
}