用c语言编写直方图均衡算法
时间: 2024-03-09 19:24:14 浏览: 66
以下是用C语言实现直方图均衡算法的代码:
```
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 256
#define HEIGHT 256
int main() {
unsigned char image[WIDTH][HEIGHT];
int histogram[WIDTH] = {0};
int cumulative_histogram[WIDTH] = {0};
int equalized_histogram[WIDTH] = {0};
int total_pixels = WIDTH * HEIGHT;
// 读取图像数据
FILE *fp = fopen("lena.raw", "rb");
fread(image, 1, total_pixels, fp);
fclose(fp);
// 计算原始直方图
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
histogram[image[i][j]]++;
}
}
// 计算累积直方图
cumulative_histogram[0] = histogram[0];
for (int i = 1; i < WIDTH; i++) {
cumulative_histogram[i] = cumulative_histogram[i-1] + histogram[i];
}
// 计算直方图均衡化后的像素值
for (int i = 0; i < WIDTH; i++) {
equalized_histogram[i] = (cumulative_histogram[i] * (WIDTH-1) + total_pixels/2) / total_pixels;
}
// 应用直方图均衡化
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
image[i][j] = equalized_histogram[image[i][j]];
}
}
// 输出结果
fp = fopen("lena_equalized.raw", "wb");
fwrite(image, 1, total_pixels, fp);
fclose(fp);
return 0;
}
```
该代码将图像数据读入一个二维数组中,然后计算原始直方图、累积直方图和直方图均衡化后的像素值,最后应用直方图均衡化,将结果输出到文件中。其中,WIDTH和HEIGHT分别表示图像的宽度和高度,lena.raw是输入文件名,lena_equalized.raw是输出文件名。
阅读全文