C语言实现BMP图像B分量直方图均衡化
#include <stdio.h>
#include <stdlib.h>
#pragma pack(1)
typedef struct {
unsigned short type;
unsigned int size;
unsigned short reserved1;
unsigned short reserved2;
unsigned int offset;
} BMPFileHeader;
typedef struct {
unsigned int size;
int width;
int height;
unsigned short planes;
unsigned short bitsPerPixel;
unsigned int compression;
unsigned int imageSize;
int xPixelsPerMeter;
int yPixelsPerMeter;
unsigned int colorsUsed;
unsigned int colorsImportant;
} BMPInfoHeader;
typedef struct {
unsigned char blue;
unsigned char green;
unsigned char red;
} BMPColor;
int main() {
FILE* file = fopen('3.bmp', 'rb');
if (!file) {
printf("Failed to open file.\n");
return 1;
}
BMPFileHeader fileHeader;
fread(&fileHeader, sizeof(fileHeader), 1, file);
BMPInfoHeader infoHeader;
fread(&infoHeader, sizeof(infoHeader), 1, file);
BMPColor* colors = (BMPColor*) malloc(sizeof(BMPColor) * infoHeader.width * infoHeader.height);
fread(colors, sizeof(BMPColor), infoHeader.width * infoHeader.height, file);
fclose(file);
// Calculate histogram
int histogram[256] = {0};
for (int i = 0; i < infoHeader.width * infoHeader.height; i++) {
histogram[colors[i].blue]++;
}
// Calculate cumulative distribution function
int cdf[256] = {0};
int sum = 0;
for (int i = 0; i < 256; i++) {
sum += histogram[i];
cdf[i] = sum;
}
// Compute equalization map
int map[256] = {0};
float factor = 255.0 / (infoHeader.width * infoHeader.height);
for (int i = 0; i < 256; i++) {
map[i] = (int)(cdf[i] * factor + 0.5);
}
// Apply equalization map to blue component
for (int i = 0; i < infoHeader.width * infoHeader.height; i++) {
colors[i].blue = map[colors[i].blue];
}
// Write output file
file = fopen('6.bmp', 'wb');
if (!file) {
printf("Failed to create output file.\n");
return 1;
}
fwrite(&fileHeader, sizeof(fileHeader), 1, file);
fwrite(&infoHeader, sizeof(infoHeader), 1, file);
fwrite(colors, sizeof(BMPColor), infoHeader.width * infoHeader.height, file);
fclose(file);
free(colors);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/jCZO 著作权归作者所有。请勿转载和采集!