Thursday, October 25, 2012

C code for Histogram


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<graphics.h>
#include<stdlib.h>
#include<math.h>

char path[30];
void histo(float hist[],float p1)
{
float histn[256];
int i=0,gdriver=DETECT,gmode;
initgraph(&gdriver,&gmode,"c:\\tcpp\\bgi");
for(i=0;i<256;i++)
histn[i]=hist[i]/p1;
setbkcolor(LIGHTCYAN);
setcolor(RED);
line(20,400,540,400);
moveto(20,400);
for(i=0;i<256;i++)
{lineto((20+(2*i)),(400-(histn[i]*4000)));
moveto(20+(2*(i+1)),400);
}
outtextxy(530,410,"pixelvalue");
outtextxy(25,20,"hist[i]");
outtextxy(200,460,"histogram for");
outtextxy(400,460,path);
getch();
}
main()
{
struct imagefheader
{
char ftype[2];
unsigned long fsize;
unsigned long res;
unsigned long boffset;
}h1;
struct info
{
unsigned long nobyte;
unsigned long width;
unsigned long height;
unsigned int cplanes;
unsigned int bperpix;
unsigned long typcmpr;
unsigned long size;
unsigned long hres;
unsigned long vres;
unsigned long indexu;
unsigned long indimp;
unsigned char b;
unsigned char g;
unsigned char r;
unsigned char f;
}infor;
FILE*ifile,*nfile;
struct palettetype p;
int i,m,ch;
float hist[256],p1,cont,cdf[256];
int gdriver=DETECT,gmode,x,y;
clrscr();

initgraph(&gdriver,&gmode,"c:\\tcpp\\bgi");
printf("\n enter file path");
scanf("%s",path);
ifile=fopen(path,"rb+");
if(ifile==NULL)
{printf("\n can not open image");
getch();
}

flushall();
fread(&h1,sizeof(h1),1,ifile);
fread(&infor,sizeof(infor),1,ifile);
clrscr();
for(i=0;i<256;i++)
hist[i]=0;
getpalette(&p);
for(i=0;i<p.size;i++)
setrgbpalette(p.colors[i],i*4,i*4,i*4);

fseek(ifile,h1.boffset,SEEK_SET);
for(y=infor.height;y>0;y--)
for(x=0;x<infor.width;x++)
{m=(fgetc(ifile));
hist[m]++;
putpixel(x,y,(m/16));
}
getch();
clrscr();
p1=infor.width*infor.height;
histo(hist,p1);
getch();
closegraph();
restorecrtmode();
clrscr();
initgraph(&gdriver,&gmode,"c:\\tcpp\\bgi");
getpalette(&p);
for(i=0;i<p.size;i++)
setrgbpalette(p.colors[i],i*4,i*4,i*4);
rewind(ifile);
cdf[0]=hist[0];
for(i=1;i<256;i++)
cdf[i]=hist[i]+cdf[i-1];
for(i=1;i<256;i++)
hist[i]=0;
fseek(ifile,h1.boffset,0);
for(y=infor.height;y>0;y--)
for(x=350;x<infor.width+350;x++)
{ch=fgetc(ifile);
ch=(cdf[ch]*255)/p1;
hist[ch]++;
putpixel(x,y,ch/16);
}
getch();
histo(hist,p1);
getch();
}

No comments:

Post a Comment