写一段代码画出一个图像的灰度直方图(不能用MATLAB自带的imhist函数),并作直方图均衡化处理。
时间: 2023-03-27 13:03:05 浏览: 102
以下是一段画出图像灰度直方图并进行直方图均衡化处理的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define WIDTH 256
#define HEIGHT 256
int main()
{
FILE *fp;
unsigned char image[WIDTH][HEIGHT];
int hist[WIDTH] = {};
int cdf[WIDTH] = {};
int min_cdf = WIDTH * HEIGHT;
int i, j;
// 读取图像
fp = fopen("lena.raw", "rb");
fread(image, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
// 计算灰度直方图
for (i = ; i < WIDTH; i++) {
for (j = ; j < HEIGHT; j++) {
hist[image[i][j]]++;
}
}
// 计算累积分布函数
for (i = ; i < WIDTH; i++) {
if (i == ) {
cdf[i] = hist[i];
} else {
cdf[i] = cdf[i - 1] + hist[i];
}
if (cdf[i] < min_cdf && hist[i] > ) {
min_cdf = cdf[i];
}
}
// 直方图均衡化
for (i = ; i < WIDTH; i++) {
for (j = ; j < HEIGHT; j++) {
image[i][j] = (unsigned char)((cdf[image[i][j]] - min_cdf) * 255. / (WIDTH * HEIGHT - min_cdf));
}
}
// 输出均衡化后的图像和直方图
fp = fopen("lena_eq.raw", "wb");
fwrite(image, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
fp = fopen("hist.txt", "w");
for (i = ; i < WIDTH; i++) {
fprintf(fp, "%d\n", hist[i]);
}
fclose(fp);
return ;
}
```
这段代码读取名为"lena.raw"的灰度图像,计算出其灰度直方图,并进行直方图均衡化处理,最终输出均衡化后的图像和直方图。
阅读全文