计算步骤:
1)统计各灰度值的概率;
2)计算了累积概率直方图(CDF);
3)取整扩展:Tk = int[ (L-1)*Tk];
代码
#include #include #include #include int main(int* argc, char** argv){FILE* fp = fopen("./01.bmp", "rb");if (fp == 0)return 0;BITMAPFILEHEADER fileHead;fread(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);BITMAPINFOHEADER infoHead;fread(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);int width = infoHead.biWidth;int height = infoHead.biHeight;int biCount = infoHead.biBitCount; int lineByte = (biCount*width / 8 + 3) / 4 * 4;RGBQUAD* pColorTable;pColorTable = new RGBQUAD[256];fread(pColorTable, sizeof(RGBQUAD), 256, fp); unsigned char* pBmpBuf;pBmpBuf = new unsigned char[lineByte*height];fread(pBmpBuf, lineByte*height, 1, fp);fclose(fp);// 统计概率double st[256] = { 0 };int st1[256] = { 0 };int t;for (int i = 0; i < height; ++i){for (int j = 0; j < width; ++j){t = *(pBmpBuf + i*lineByte + j);st[t]++;}}// 计算累加直方图并完成映射st[0] = st[0] / (width*height);st1[0] = round(double((256 - 1)*st[0]));for (int i = 1; i < 256; ++i){st[i] = st[i] / (width*height);st[i] = st[i] + st[i - 1];st1[i] = int(round(double((256 - 1)*st[i])));printf("st[i] = %d, st1[t] = %d", st[i], st1[i]);}// 新图像的像素填充unsigned char* pBmpBuf1;pBmpBuf1 = new unsigned char[lineByte*height];for (int i = 0; i < height; ++i){for (int j = 0; j < width; ++j){t = *(pBmpBuf + i*lineByte + j);*(pBmpBuf1 + i*lineByte + j) = st1[t];}} FILE* fop = fopen("./imhist.bmp", "wb");if (fop == 0)return 0;fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fop);fwrite(&infoHead, sizeof(BITMAPINFOHEADER), 1, fop);fwrite(pColorTable, sizeof(RGBQUAD), 256, fop);fwrite(pBmpBuf1, lineByte*height, 1, fop);fclose(fop); system("pause");return 0;}
效果展现
![e83873312ed5a90c408f05c15be56d1c.png](https://i-blog.csdnimg.cn/blog_migrate/50196602029acd2ce2165f975aa1a85f.jpeg)
原图
![39849b2d7ac09344f5ebf38220f4b74d.png](https://i-blog.csdnimg.cn/blog_migrate/5293a908e744d27ee8bb8db05a3dcf43.jpeg)
直方图均衡化的结果
编译环境
![983b37fc8b3bb71baeac7044741c78d8.png](https://i-blog.csdnimg.cn/blog_migrate/ff7648f05e5c56277afe3a6bbc0ccd04.jpeg)
VS2013