#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include <math.h>
#pragma pack(1)
typedef struct tagBITMAPFILEHEADER
{
unsigned char bfType[2];
unsigned long bfSize;
unsigned short bfReserved1;
unsigned short bfReserved2;
unsigned long bfOffBits;
}fileHeader;
#pragma pack()
#pragma pack(1)
typedef struct tagBITMAPINFOHEADER
{
unsigned long biSize;
long biWidth;
long biHeight;
unsigned short biPlanes;
unsigned short biBitCount;
unsigned long biCompression;
unsigned long biSizeImage;
long biXPixPerMeter;
long biYPixPerMeter;
unsigned long biClrUsed;
unsigned long biClrImporant;
}fileInfo;
#pragma pack()
typedef struct tagRGBQUAD
{
unsigned char rgbBlue;
unsigned char rgbGreen;
unsigned char rgbRed;
unsigned char rgbReserved;
}rgbq;
#pragma pack()
int main()
{
unsigned char ImgData2[640][640];
unsigned char ImgData3[1000];
int i, j, k;
FILE * fpGray, * fpGrayAverage;
fileHeader* fh;
fileInfo* fi;
rgbq* fq;
char filename1[20], filename2[20];
errno_t error;
printf("输入图像文件名:");
scanf_s("%s", filename1, 20);
error = fopen_s(&fpGray, filename1, "rb+");
if (error != 0)
{
printf("打开文件失败");
exit(0);
}
printf("输出直方图均衡后图像文件名:");
scanf_s("%s", filename2, 20);
error = fopen_s(&fpGrayAverage, filename2, "wb");
if (error != 0)
{
printf("创建文件失败");
exit(0);
}
fh = (fileHeader*)malloc(sizeof(fileHeader));
fi = (fileInfo*)malloc(sizeof(fileInfo));
fread(fh, sizeof(fileHeader), 1, fpGray);
fread(fi, sizeof(fileInfo), 1, fpGray);
fi->biBitCount = 8;
fi->biSizeImage = ((fi->biWidth * 3 + 3) / 4) * 4 * fi->biHeight;
fi->biClrUsed=256;
fh->bfOffBits = sizeof(fileHeader) + sizeof(fileInfo) + 256 * sizeof(rgbq);
fh->bfSize = fh->bfOffBits + fi->biSizeImage;
fq = (rgbq*)malloc(256 * sizeof(rgbq));
for (i = 0; i < 256; i++)
{
fq[i].rgbBlue = fq[i].rgbGreen = fq[i].rgbRed = i;
fq[i].rgbReserved=0;
}
fread(fq, sizeof(rgbq), 256, fpGray);
fwrite(fh, sizeof(fileHeader), 1, fpGrayAverage);
fwrite(fi, sizeof(fileInfo), 1, fpGrayAverage);
fwrite(fq, sizeof(rgbq), 256, fpGrayAverage);
int count[256] = { 0 };
float probability[256] = { 0 }, sumprob[256] = { 0 };
for (i = 0; i < fi->biHeight; i++)
{
for (j = 0; j <fi->biWidth; j++)
{
fread(&ImgData2[i][j], 1, 1, fpGray);
}
}
for (i = 0; i < fi->biHeight; i++)
{
for (j = 0; j < fi->biWidth; j++)
{
count[ImgData2[i][j]]++;
}
}
if (i == fi->biHeight)
{
for (int x = 0; x < 256; x++)
probability[x] = (float)count[x] / (float)(fi->biWidth * fi->biHeight);
for (int x = 0; x < 256; x++)
{
if (x == 0)
sumprob[x] = probability[x];
else
sumprob[x] = sumprob[x - 1] + probability[x];
}
}
for (i = 0; i < fi->biHeight; i++)
{
for (j = 0; j < fi->biWidth; j++)
{
ImgData3[j] = (int)floor((double)(255 * sumprob[ImgData2[i][j]]+0.5));
}
fwrite(ImgData3, j, 1, fpGrayAverage);
}
free(fh);
free(fi);
free(fq);
fclose(fpGray);
fclose(fpGrayAverage);
printf("success\n");
return 0;
}
运行示例: 输入:
输出:
|