直方图均衡化c++代码
时间: 2023-10-02 11:08:52 浏览: 38
以下是一个使用C语言实现直方图均衡化的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_GRAY_LEVEL 256
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s input_image output_image\n", argv[0]);
return 1;
}
char *input_file = argv[1];
char *output_file = argv[2];
// 读取输入图像文件
FILE *input = fopen(input_file, "rb");
if (input == NULL) {
printf("Failed to open input file %s\n", input_file);
return 1;
}
int width, height, max_gray;
char magic_number[3];
fscanf(input, "%s %d %d %d", magic_number, &width, &height, &max_gray);
if (strcmp(magic_number, "P5") != 0 || max_gray != MAX_GRAY_LEVEL - 1) {
printf("Invalid input image format or gray level\n");
fclose(input);
return 1;
}
unsigned char *image = (unsigned char*) malloc(width * height);
fread(image, sizeof(unsigned char), width * height, input);
fclose(input);
// 统计像素值频率
int histogram[MAX_GRAY_LEVEL] = {0};
for (int i = 0; i < width * height; i++) {
histogram[image[i]]++;
}
// 计算累计分布函数
int cdf[MAX_GRAY_LEVEL] = {0};
cdf[0] = histogram[0];
for (int i = 1; i < MAX_GRAY_LEVEL; i++) {
cdf[i] = cdf[i-1] + histogram[i];
}
// 计算均衡化映射函数
float pdf[MAX_GRAY_LEVEL];
for (int i = 0; i < MAX_GRAY_LEVEL; i++) {
pdf[i] = (float) cdf[i] / (width * height);
}
int mapping[MAX_GRAY_LEVEL];
for (int i = 0; i < MAX_GRAY_LEVEL; i++) {
mapping[i] = (int) ((MAX_GRAY_LEVEL - 1) * pdf[i] + 0.5);
}
// 应用均衡化映射函数到原图像
for (int i = 0; i < width * height; i++) {
image[i] = (unsigned char) mapping[image[i]];
}
// 写入输出图像文件
FILE *output = fopen(output_file, "wb");
if (output == NULL) {
printf("Failed to open output file %s\n", output_file);
return 1;
}
fprintf(output, "P5\n%d %d\n%d\n", width, height, MAX_GRAY_LEVEL - 1);
fwrite(image, sizeof(unsigned char), width * height, output);
fclose(output);
free(image);
return 0;
}
```
该代码的实现流程如下:
1. 读取输入图像文件,判断文件格式和灰度级是否合法。
2. 统计输入图像中每个像素值出现的频率,得到直方图。
3. 计算直方图的累计分布函数。
4. 根据累计分布函数