c语言代码实现直方图均衡进行灰度变换的代码
时间: 2023-10-26 14:04:12 浏览: 83
下面是C语言代码实现直方图均衡进行灰度变换的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define Gray_Level 256
// 直方图均衡化函数
void hist_equalization(unsigned char* img, int width, int height)
{
int i, j, pixel_num, gray_sum;
int gray_scale[Gray_Level] = {0};
int gray_map[Gray_Level] = {0};
// 计算每个灰度级的像素数量
pixel_num = width * height;
for (i = 0; i < pixel_num; i++)
{
gray_scale[*(img + i)]++;
}
// 计算每个灰度级新的映射值
gray_sum = 0;
for (i = 0; i < Gray_Level; i++)
{
gray_sum += gray_scale[i];
gray_map[i] = (int)(255.0 * gray_sum / pixel_num + 0.5);
}
// 对图像进行直方图均衡化
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
*(img + i * width + j) = gray_map[*(img + i * width + j)];
}
}
}
int main()
{
// 加载图像
unsigned char* img = 0;
int width, height;
FILE* fp = fopen("lena.pgm", "rb");
if (!fp)
{
printf("Load image failed!");
return -1;
}
fscanf(fp, "%*s %d %d %*d", &width, &height);
img = (unsigned char*)malloc(sizeof(unsigned char) * width * height);
fread(img, sizeof(unsigned char), width * height, fp);
fclose(fp);
// 对图像进行直方图均衡化
hist_equalization(img, width, height);
// 保存结果
fp = fopen("lena_histeq.pgm", "wb");
fprintf(fp, "P5\n%d %d\n%d\n", width, height, 255);
fwrite(img, sizeof(unsigned char), width * height, fp);
fclose(fp);
// 释放内存
free(img);
return 0;
}
```
阅读全文