本文将介绍使用 C 语言对 256x256 大小的 24 位真彩色 BMP 格式图像进行直方图均衡化处理。

由于直方图均衡需要统计每个像素值的出现次数,因此需要先读入原图像,统计每个像素值的出现次数,然后计算累积分布函数,最后根据均衡化后的像素值重新生成图像。

以下是代码实现:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    unsigned char b;
    unsigned char g;
    unsigned char r;
} Pixel;

void histogram_equalization(Pixel* pixels, int width, int height) {
    int hist[256] = {0};
    for (int i = 0; i < width * height; i++) {
        hist[pixels[i].r]++;
    }

    int cdf[256] = {0};
    cdf[0] = hist[0];
    for (int i = 1; i < 256; i++) {
        cdf[i] = cdf[i-1] + hist[i];
    }

    for (int i = 0; i < width * height; i++) {
        pixels[i].r = (unsigned char)(cdf[pixels[i].r] * 255.0 / (width * height) + 0.5);
    }
}

int main() {
    FILE* fin = fopen('2.bmp', 'rb');
    FILE* fout = fopen('3.bmp', 'wb');

    // 读入bmp文件头
    unsigned char header[54];
    fread(header, 1, 54, fin);
    fwrite(header, 1, 54, fout);

    // 读入像素数据
    int width = *(int*)(header + 18);
    int height = *(int*)(header + 22);
    int row_size = (width * 24 + 31) / 32 * 4;
    Pixel* pixels = (Pixel*)malloc(width * height * sizeof(Pixel));
    for (int y = height - 1; y >= 0; y--) {
        fread(pixels + y * width, sizeof(Pixel), width, fin);
        fseek(fin, row_size - width * sizeof(Pixel), SEEK_CUR);
    }

    // 直方图均衡
    histogram_equalization(pixels, width, height);

    // 写入像素数据
    for (int y = height - 1; y >= 0; y--) {
        fwrite(pixels + y * width, sizeof(Pixel), width, fout);
        fseek(fout, row_size - width * sizeof(Pixel), SEEK_CUR);
    }

    free(pixels);
    fclose(fin);
    fclose(fout);
    return 0;
}

注意,这里假设输入的 bmp 图像是 24 位真彩色的,如果是其他格式的 bmp 图像,可能需要对代码进行相应修改。同时,由于 bmp 图像的像素数据在文件中是按行存储的,每行的字节数需要计算出来,并且在读写像素数据时需要跳过每行的填充字节。

C语言实现256x256 BMP图像直方图均衡化

原文地址: https://www.cveoy.top/t/topic/nniX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录