5 void hist_eq(unsigned char *data, int len, int n)
9 for( int i=0; i<256; ++i ) hist[i] = 0;
10 unsigned char *bp = data;
11 for( int i=len; --i>=0; ++bp ) ++hist[*bp];
12 for( int t=0, i=0; i<256; ++i ) { t += hist[i]; hist[i] = t; }
14 int mn = 0; while( mn<255 && !hist[mn] ) ++mn;
15 int mx = 256; while( mx>mn && hist[mx-1]==len ) --mx;
16 double r = (double)(mx - mn) / (256-1);
17 int map[256]; map[0] = 0; map[255] = 255;
18 double dv = (len-1) / 256., v = dv;
19 for( int i=1; i<255; ++i, v+=dv ) {
21 map[i] = i * (1-(v - hist[j])/len);
23 //for( int i=0; i<256; ++i ) fprintf(stderr,"%d\n",map[i]);
25 for( int i=len; --i>=0; ++bp ) *bp = map[*bp];
29 int main(int ac, char **av)
31 FILE *ifp = !strcmp(av[1],"-") ? stdin : fopen(av[1],"r");
32 FILE *ofp = !strcmp(av[2],"-") ? stdout : fopen(av[2],"w");
34 fgets(line,sizeof(line),ifp); fputs(line,ofp);
35 fgets(line,sizeof(line),ifp); fputs(line,ofp);
36 int w, h; if( sscanf(line,"%d %d\n",&w,&h) != 2 ) exit(1);
37 fgets(line,sizeof(line),ifp); fputs(line,ofp);
39 unsigned char data[len], *bp = data;
40 for( int ch, i=len; --i>=0 && (ch=getc(ifp)) >= 0; ++bp ) *bp = ch;
41 for( int i=1; --i>=0; ) hist_eq(data,len, 3);
43 for( int i=len; --i>=0; ++bp ) putc(*bp,ofp);
45 if( ifp != stdin ) fclose(ifp);
46 if( ofp != stdout ) fclose(ofp);