图像直方图
图像直方图是以0-255作为横坐标,以图中对应像素值出现的次数作为纵坐标的图像统计图,利用图像直方图可以比较直观的看到图像的统计信息
直方图均衡化
直方图均衡是根据变换函数
计算的得到的,可以理解为在任意间隔内的灰度密度等于灰度间隔除以总灰度级,那么这个灰度分布就是均衡的。
参考代码
void HistogramEqualize(BYTE *pImg, int width, int height)
{
BYTE *pCur, *pEnd = pImg+width*height;
unsigned int hist[256];
int LUT[256], i, sum;
// step.1---Hist---------------------//
memset(hist, 0, sizeof(int)*256);
for (pCur = pImg; pCur<pEnd;) hist[*(pCur++)]++;
// step.2---A[g]--------------------//
int A[256];
int g;
for (g = 0; g<256; g++)
{
sum = 0;
for (i = 0; i<=g; i++)
{
sum += hist[i];
}
A[g] = sum;
}
// step.3---N-----------------------//
int N = 0;
for (g = 0; g<256; g++)
{
if (hist[g]) N++;
}
//N=100;
int A0 = A[255];
// step.4---LUT---------------------//
for (g = 0; g<256; g++)
{
LUT[g]=N*A[g]/A0;
}
// step.5---F-----------------------//
for (pCur = pImg; pCur<pEnd;) *(pCur++) = LUT[*pCur];
// step.6---return------------------//
return;
}
当然代码还可以优化
void HistogramEqualize(BYTE *pImg, int width, int height)
{
BYTE *pCur, *pEnd = pImg+width*height;
unsigned int hist[256];
int LUT[256];
// step.1---Hist---------------------//
memset(hist, 0, sizeof(int)*256);
for (pCur = pImg; pCur<pEnd;) hist[*(pCur++)]++;
// step.2---A[g]--------------------//
int A[256];
int g;
for (g = 1,A[0]=hist[0]; g<256; g++)
{
A[g] = A[g-1]+hist[g];
}
int A0 = A[255];
// step.4---LUT---------------------//
for (g = 0; g<256; g++)
{
LUT[g] = 255*A[g]/A0;
}
// step.5---F-----------------------//
for (pCur = pImg; pCur<pEnd;) *(pCur++) = LUT[*pCur];
// step.6---return------------------//
return;
}
当然代码还可以优化
void RmwHistogramEqualize(BYTE *pImg, int width, int height)
{
BYTE *pCur, *pEnd = pImg+width*height;
unsigned int hist[256];
int LUT[256], g, A;
memset(hist, 0, sizeof(int)*256);
for (pCur = pImg; pCur<pEnd;) hist[*(pCur++)]++;
//LUT[0] = 255*hist[0]/(width*height);
//for (g = 1, A = hist[0], LUT[0]=0; g<256; g++)
for (g = 1, A = hist[0]; g<256; g++)
{
A = A+hist[g];
LUT[g] = 255*A/(width*height);
}
for (pCur = pImg; pCur<pEnd;) *(pCur++) = LUT[*pCur];
}
实验结果