#include <fcntl.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void
histogramEqualisation(
int
cols,
int
rows,
char
* input_file_name,
char
* output_file_name)
{
unsigned
char
* image;
int
hist[256] = { 0 };
int
new_gray_level[256] = { 0 };
int
input_file, output_file, col, row, total, curr, i;
image = (unsigned
char
*)
calloc
(cols,
sizeof
(unsigned
char
));
input_file = open(input_file_name, O_RDONLY);
if
(input_file < 0) {
printf
("Error opening input file\n");
exit
(1);
}
output_file = create(output_file_name, 0666);
if
(output_file < 0) {
printf
("Error creating output file\n");
exit
(1);
}
for
(row = 0; row < rows; row++) {
read(input_file, &image[0], cols *
sizeof
(unsigned
char
));
for
(col = 0; col < cols; col++)
hist[(
int
)image[col]]++;
}
total = cols * rows;
curr = 0;
for
(i = 0; i < 256; i++) {
curr += hist[i];
new_gray_level[i] = round((((
float
)curr) * 255) / total);
}
close(input_file);
input_file = open(input_file_name, O_RDONLY);
for
(row = 0; row < rows; row++) {
read(input_file, &image[0], cols *
sizeof
(unsigned
char
));
for
(col = 0; col < cols; col++)
image[col] = (unsigned
char
)new_gray_level[image[col]];
write(output_file, &image[0], cols *
sizeof
(unsigned
char
));
}
free
(image);
close(input_file);
close(output_file);
}
int
main()
{
char
* input_file_name;
char
* output_file_name;
int
cols, rows;
cols = 512;
rows = 512;
input_file_name = "boat_512_512";
output_file_name = "boat_512_512_histogram_equalised";
histogramEqualisation(cols, rows, input_file_name, output_file_name);
return
0;
}