输入灰度图像输出直方图图像c语言
时间: 2023-07-13 16:18:49 浏览: 124
以下是一个使用C语言实现灰度图像输出直方图图像的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define IMAGE_WIDTH 256
#define IMAGE_HEIGHT 200
#define HIST_HEIGHT 100
// 计算灰度图像的直方图
void calc_histogram(uint8_t* image_data, uint32_t image_size, uint32_t* histogram)
{
for (uint32_t i = 0; i < image_size; i++) {
histogram[image_data[i]]++;
}
}
// 归一化直方图
void normalize_histogram(uint32_t* histogram, uint32_t size)
{
uint32_t max_val = 0;
for (uint32_t i = 0; i < size; i++) {
if (histogram[i] > max_val) {
max_val = histogram[i];
}
}
for (uint32_t i = 0; i < size; i++) {
histogram[i] = histogram[i] * HIST_HEIGHT / max_val;
}
}
// 绘制直方图
void draw_histogram(uint32_t* histogram, uint8_t* hist_image_data)
{
for (uint32_t y = 0; y < HIST_HEIGHT; y++) {
for (uint32_t x = 0; x < IMAGE_WIDTH; x++) {
if (y >= HIST_HEIGHT - histogram[x]) {
hist_image_data[y * IMAGE_WIDTH + x] = 255;
} else {
hist_image_data[y * IMAGE_WIDTH + x] = 0;
}
}
}
}
int main(int argc, char* argv[])
{
FILE* fp;
uint8_t* image_data;
uint32_t image_size;
uint32_t histogram[256] = { 0 };
uint8_t hist_image_data[HIST_HEIGHT * IMAGE_WIDTH] = { 0 };
// 读取灰度图像文件
if ((fp = fopen("gray_image.raw", "rb")) == NULL) {
printf("Cannot open file.\n");
return -1;
}
fseek(fp, 0, SEEK_END);
image_size = ftell(fp);
image_data = (uint8_t*)malloc(image_size);
fseek(fp, 0, SEEK_SET);
fread(image_data, 1, image_size, fp);
fclose(fp);
// 计算直方图
calc_histogram(image_data, image_size, histogram);
// 归一化直方图
normalize_histogram(histogram, 256);
// 绘制直方图
draw_histogram(histogram, hist_image_data);
// 写入直方图图像文件
if ((fp = fopen("hist_image.raw", "wb")) == NULL) {
printf("Cannot open file.\n");
return -1;
}
fwrite(hist_image_data, 1, HIST_HEIGHT * IMAGE_WIDTH, fp);
fclose(fp);
free(image_data);
return 0;
}
```
在这个示例代码中,我们首先定义了一些常量,包括图像的宽度、高度和直方图的高度。然后,我们定义了三个函数,分别用于计算直方图、归一化直方图和绘制直方图。在主函数中,我们首先读取灰度图像文件,并计算对应的直方图。然后,我们归一化直方图并绘制直方图。最后,我们将直方图图像数据写入文件中。注意,此示例代码仅适用于8位灰度图像。如果您的图像不是8位灰度图像,请相应地修改代码。
阅读全文