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

#pragma pack(2)
typedef struct {
    short bfType;
    int bfSize;
    short bfReserved1;
    short bfReserved2;
    int bfOffBits;
} BITMAPFILEHEADER;

typedef struct {
    int biSize;
    int biWidth;
    int biHeight;
    short biPlanes;
    short biBitCount;
    int biCompression;
    int biSizeImage;
    int biXPelsPerMeter;
    int biYPelsPerMeter;
    int biClrUsed;
    int biClrImportant;
} BITMAPINFOHEADER;

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

int main() {
    FILE *fp_in = fopen("3.bmp", "rb");
    if (fp_in == NULL) {
        printf("open file failed!\n");
        return 0;
    }

    BITMAPFILEHEADER file_header;
    BITMAPINFOHEADER info_header;

    fread(&file_header, sizeof(BITMAPFILEHEADER), 1, fp_in);
    fread(&info_header, sizeof(BITMAPINFOHEADER), 1, fp_in);

    int width = info_header.biWidth;
    int height = info_header.biHeight;
    int line_byte = (width * 24 + 31) / 32 * 4;

    RGB **data = (RGB**)malloc(sizeof(RGB*) * height);
    for (int i = 0; i < height; i++) {
        data[i] = (RGB*)malloc(sizeof(RGB) * width);
        fread(data[i], sizeof(RGB), width, fp_in);
        fseek(fp_in, line_byte - width * sizeof(RGB), SEEK_CUR);
    }
    fclose(fp_in);

    // 直方图均衡
    int histogram[256] = {0};
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            histogram[data[i][j].g]++;
        }
    }

    int equalization[256] = {0};
    int sum = 0;
    for (int i = 0; i < 256; i++) {
        sum += histogram[i];
        equalization[i] = sum * 255 / (width * height);
    }

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            data[i][j].g = equalization[data[i][j].g];
        }
    }

    // 写入文件
    FILE *fp_out = fopen("5.bmp", "wb");
    if (fp_out == NULL) {
        printf("create file failed!\n");
        return 0;
    }

    fwrite(&file_header, sizeof(BITMAPFILEHEADER), 1, fp_out);
    fwrite(&info_header, sizeof(BITMAPINFOHEADER), 1, fp_out);

    for (int i = 0; i < height; i++) {
        fwrite(data[i], sizeof(RGB), width, fp_out);
        fwrite("\0\0\0\0", 1, line_byte - width * sizeof(RGB), fp_out);
    }

    fclose(fp_out);

    for (int i = 0; i < height; i++) {
        free(data[i]);
    }
    free(data);

    return 0;
}
用C语言编写一段代码对大小为256×256大小 24 位真彩的bmp格式的图像进行相应操作并且读写要求用到fread 、fwrite 函数等将图像3bmp中的色彩R G B分量 中的G分量进行直方图均衡将对G分量进行直方图均衡衡后的图像输出为名字为5bmp的图像

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

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