写一个C语言的直方图均衡化代码
时间: 2023-05-20 18:07:19 浏览: 75
直方图均衡化代码
#include <stdio.h>
#include <stdlib.h>
#define HIST_SIZE 256
int* calcHistogram(unsigned char* image, int width, int height){
int i;
int* histogram;
histogram = (int*)calloc(HIST_SIZE, sizeof(int));
for(i=0; i<width*height; i++){
histogram[image[i]]++;
}
return histogram;
}
unsigned char* histogramEqualize(unsigned char* image, int width, int height){
int i, j;
int* histogram;
unsigned char* eqImage;
int histSum=0;
float* cdf;
int* tmp;
histogram = calcHistogram(image, width, height);
eqImage = (unsigned char*)malloc(width*height*sizeof(unsigned char));
cdf = (float*)malloc(HIST_SIZE*sizeof(float));
tmp = (int*)malloc(HIST_SIZE*sizeof(int));
for(i=0; i<HIST_SIZE; i++){
histSum += histogram[i];
cdf[i] = histSum;
}
for(i=0; i<HIST_SIZE; i++){
cdf[i] /= (width*height);
}
tmp[0] = cdf[0]*HIST_SIZE;
for(i=1; i<HIST_SIZE; i++){
tmp[i] = (cdf[i]-cdf[i-1])*HIST_SIZE;
tmp[i] += tmp[i-1];
}
for(i=0; i<width*height; i++){
eqImage[i] = (unsigned char)tmp[image[i]];
}
free(histogram);
free(cdf);
free(tmp);
return eqImage;
}
int main(){
int i, j;
int width, height;
unsigned char* image;
unsigned char* eqImage;
FILE* fp;
fp = fopen("lena.raw", "rb");
if(fp==NULL){
perror("File open error.");
exit(1);
}
width = height = 256;
image = (unsigned char*)malloc(width*height*sizeof(unsigned char));
fread(image, sizeof(unsigned char), width*height, fp);
fclose(fp);
eqImage = histogramEqualize(image, width, height);
fp = fopen("lena_equal.raw", "wb");
fwrite(eqImage, sizeof(unsigned char), width*height, fp);
fclose(fp);
free(image);
free(eqImage);
return 0;
}
阅读全文