ccs实现直方图均衡化C语言代码
时间: 2023-10-17 22:22:39 浏览: 86
直方图均衡化是一种图像处理方法,可以增强图像的对比度和亮度。以下是一个简单的 C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_PIXEL_VALUE 255
#define HISTOGRAM_SIZE 256
int main() {
int width, height, max_gray;
int i, j, k, pixel;
unsigned char *image_in, *image_out;
int histogram[HISTOGRAM_SIZE] = {0};
int cumulative_hist[HISTOGRAM_SIZE] = {0};
float cumulative_hist_norm[HISTOGRAM_SIZE] = {0.0};
// 读取图像数据
FILE *file_in = fopen("input_image.pgm", "rb");
if (!file_in) {
printf("Error: Could not open input file.\n");
return 1;
}
fscanf(file_in, "P5\n%d %d\n%d\n", &width, &height, &max_gray);
image_in = (unsigned char*)malloc(sizeof(unsigned char) * width * height);
fread(image_in, sizeof(unsigned char), width * height, file_in);
fclose(file_in);
// 计算直方图
for (i = 0; i < width * height; i++) {
histogram[image_in[i]]++;
}
// 计算累积直方图和归一化的累积直方图
cumulative_hist[0] = histogram[0];
cumulative_hist_norm[0] = (float)cumulative_hist[0] / (float)(width * height);
for (i = 1; i < HISTOGRAM_SIZE; i++) {
cumulative_hist[i] = cumulative_hist[i-1] + histogram[i];
cumulative_hist_norm[i] = (float)cumulative_hist[i] / (float)(width * height);
}
// 应用直方图均衡化
image_out = (unsigned char*)malloc(sizeof(unsigned char) * width * height);
for (i = 0; i < width * height; i++) {
pixel = image_in[i];
image_out[i] = (unsigned char)(MAX_PIXEL_VALUE * cumulative_hist_norm[pixel] + 0.5);
}
// 保存输出图像
FILE *file_out = fopen("output_image.pgm", "wb");
fprintf(file_out, "P5\n%d %d\n%d\n", width, height, MAX_PIXEL_VALUE);
fwrite(image_out, sizeof(unsigned char), width * height, file_out);
fclose(file_out);
// 释放内存
free(image_in);
free(image_out);
return 0;
}
```
注意:该代码仅适用于 PGM 格式的灰度图像。如果你使用其他格式或彩色图像,需要做出相应的修改。
阅读全文