26 #define DEFAULT_NUMBINS 256
43 static int parse_params(
program_params *param,
int argc,
char *argv[]);
47 puts(
"Histogram equalization, P. Getreuer 2011\n");
48 puts(
"Usage: histeq [options] <input file> <output file>\n"
51 puts(
" -b <number> number of histogram bins (default 256)");
53 puts(
" -q <number> quality for saving JPEG images (0 to 100)\n");
58 int equalize_image(
float *image,
int width,
int height,
int num_bins)
60 const long num_pixels = ((long)width) * ((long)height);
61 const long num_el = 3 * num_pixels;
62 const int num_bins_minus_one = num_bins - 1;
63 float *histogram1d[3] = {NULL, NULL, NULL};
66 int n, channel, success = 0;
68 if(!(histogram1d[0] = (
float *)
Malloc(
sizeof(
float)*3*num_bins)))
71 histogram1d[1] = histogram1d[0] + num_bins;
72 histogram1d[2] = histogram1d[0] + 2*num_bins;
74 for(channel = 0; channel < 3; channel++)
75 for(i = 0; i < num_bins; i++)
76 histogram1d[channel][i] = 0;
79 for(i = 0; i < num_el; i += 3)
81 histogram1d[0][(int)(image[i + 0]*num_bins_minus_one + 0.5f)]++;
82 histogram1d[1][(int)(image[i + 1]*num_bins_minus_one + 0.5f)]++;
83 histogram1d[2][(int)(image[i + 2]*num_bins_minus_one + 0.5f)]++;
86 for(channel = 0; channel < 3; channel++)
87 for(i = 0; i < num_bins; i++)
88 histogram1d[channel][i] /= num_pixels;
91 for(channel = 0; channel < 3; channel++)
93 for(n = 0, accum = 0; n < num_bins; n++)
95 accum += histogram1d[channel][n];
96 histogram1d[channel][n] = accum - histogram1d[channel][n]/2;
99 histogram1d[channel][0] = 0;
100 histogram1d[channel][num_bins - 1] = 1;
104 for(i = 0; i < num_el; i += 3)
106 image[i + 0] = histogram1d[0][
107 (int)(image[i + 0]*num_bins_minus_one + 0.5f)];
108 image[i + 1] = histogram1d[1][
109 (int)(image[i + 1]*num_bins_minus_one + 0.5f)];
110 image[i + 2] = histogram1d[2][
111 (int)(image[i + 2]*num_bins_minus_one + 0.5f)];
116 Free(histogram1d[0]);
121 int main(
int argc,
char **argv)
125 unsigned long time_start;
126 int width, height, status = 0;
128 if(!parse_params(¶m, argc, argv))
132 IMAGEIO_RGB | IMAGEIO_FLOAT)))
135 time_start = Clock();
137 if(!equalize_image(image, width, height, param.
num_bins))
140 printf(
"CPU Time: %.3f s\n", 0.001f*(Clock() - time_start));
154 static int parse_params(
program_params *param,
int argc,
char *argv[])
156 static char *default_output_file = (
char *)
"out.png";
174 for(i = 1; i < argc;)
176 if(argv[i] && argv[i][0] ==
'-')
178 if((option_char = argv[i][1]) == 0)
185 option_string = &argv[i][2];
187 option_string = argv[i];
197 param->
num_bins = atoi(option_string);
201 ErrorMessage(
"Number of bins must be between 2 and 10000.\n");
205 #ifdef LIBJPEG_SUPPORT
211 fprintf(stderr,
"JPEG quality must be between 0 and 100.\n");
220 if(isprint(option_char))