I was developing a simple program to read an 24-bit BMP image, convert it into 8-bit intensity map and then display it as a grayscale image. Please review this code and tell me where I am getting an error...
#include<stdio.h>
#include<conio.h>
#pragma pack(2)
typedef struct
{
unsigned short int type;
unsigned int size;
unsigned short int reserved1,reserved2;
unsigned int offset;
}HEADER;
typedef struct
{
unsigned int size;
int width,height;
unsigned short int bits;
unsigned int compression;
unsigned int imagesize;
int xresolution,yresolution;
unsigned int ncolors;
unsigned int impcolors;
}INFOHEADER;
typedef struct
{
unsigned int R,G,B;
}PIXEL;
void main()
{
HEADER headfirst;
INFOHEADER headsecond;
PIXEL pix;
FILE *fin,*fout,*f1;
char *read;
int ch=0,i,j,mat[768],R[256],G[256],B[256],Gray[256];
float Y[256];
fin=fopen("C:/Dev-Cpp/1.bmp","rb+");
if(fin==NULL)
{
printf("Error");
exit(0);
}
fread(&headfirst,sizeof(headfirst),1,fin);
if(headfirst.type!=19778)
{
printf("Not BMP");
getch();
return(0);
}
printf("Header %x ",headfirst.type);
printf("%u ",headfirst.size);
printf("%u %u ",headfirst.reserved1,headfirst.reserved2);
printf("%u\n",headfirst.offset);
fin=fopen("C:/Dev-Cpp/1.bmp","rb+");
fread(&headsecond,sizeof(headsecond),1,fin);
printf("IFD %u",headsecond.size);
printf("%d %d %u %u %u %d %d %u %u\n",headsecond.width,headsecond.height,headsecond.height,headsecond.bits,headsecond.compression,headsecond.imagesize,headsecond.xresolution,headsecond.yresolution,headsecond.ncolors,headsecond.impcolors);
fin=fopen("C:/Dev-Cpp/1.bmp","rb+");
if(fin==0)
{return(0);
}
for(i=0;i<headfirst.offset;i++)
{
ch=getc(fin);
}
i=0;
while ((ch=fgetc(fin))!=EOF)
{
mat[i]=(int)ch;
i++;
}
fclose(fin);
printf("Blue Plane\n");
i=0,j=0;
while(i<768)
{
B[j]=mat[i];
printf("%3d ",mat[i]);
i=i+3;
j++;
}
printf("\n\n");
printf("Green Plane\n");
i=1,j=0;
while(i<768)
{
G[j]=mat[i];
printf("%3d ",mat[i]);
i=i+3;
j++;
}
printf("\n\n");
printf("Red Plane\n");
i=2,j=0;
while(i<768)
{
R[j]=mat[i];
printf("%3d ",mat[i]);
i=i+3;
j++;
}
printf("\n\n Gray Scale Image\n");
for(i=0;i<256;i++)
{
Y[i]=0.2989 * R[i] + 0.5870 * G[i] + 0.1140 * B[i] ;
G[i]=(int)Y[i];
printf("%3d ",G[i]);
}
fout=fopen("C:/Dev-Cpp/1.bmp","wb+");
fwrite(&headfirst,sizeof(headfirst),1,fout);
fout=fopen("C:/Dev-Cpp/1.bmp","wb+");
fwrite(&headsecond,sizeof(headsecond),1,fout);
fout=fopen("C:/Dev-Cpp/1.bmp","wb+");
for(i=0;i<255;i++)
{
read[i]=(char)G[i];
}
read[i]='\0';
for(i=0;i<255;i++)
{
fwrite (read,sizeof(G),1,fout);
}
getch();
}
|