设图像变换前的灰度级为[0,255],图像变换后的灰度级也为[0,255],那
那么变化的目的就是改变图像的分布。
其映射函数: y = f(x)
对于x是单调递增的(0-255),对应得到的y也要求是递增的,其范围也需为(0-255)。
这里,主要问题就是映射函数f的定义。
假设我们定义映射函数为阶段函数:y =f(n)= f(n-1)+n;f(0)=1;
得到:
f(0) = 1;
f(1) = 2;
f(2) = 4;
f(3) = 7
...
f(255) =32641 ;
这里就会有一个问题,f(255)的值已经超过255。
因此,进行调整,设y = f(x) = (n^2+1)*(255/32641 ).这样就保证了f(255) = 255.
得到:
f(0) = 0;
...
f(15) = 0;
f(16) = 1;
...
f(255) = 255
我们定义的这个函数就可以作为变换函数来对原图像进行映射变化。
直方图均衡化的思想同上面的一致,只是其求和的是该灰度值在图像像素中出现的个数。
具体步骤:
原灰度图像:
统计各灰度在图像中出现的频数。得到直方图:
用频数的累积和作为函数f(x),由于f(255) = 总像素个数,所以定义f(x)要除以总像素个数。
然后进行图像变换得到新图像:
其对应的直方图为:
代码:
// HelloOpenCV.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <math.h>
#include <cv.h>
#include <highgui.h>
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
int main(int argc, _TCHAR* argv[])
{
const char * imagePath = "C:\\Users\\lenmovo\\Pictures\\Lena.jpg";
IplImage* src = cvLoadImage(imagePath);
IplImage* dst_gray = ::cvCreateImage(cvGetSize(src),src->depth,1);
cvSetZero(dst_gray);
cvCvtColor(src,dst_gray,CV_BGR2GRAY);//得到灰度图
//显示直方图规范化前的灰度图
cvShowImage("RGB", dst_gray);
cvWaitKey(0);
//opencv直方图均衡化函数
//cvEqualizeHist(dst_gray,dst_gray);
uchar* dstData = (uchar*)dst_gray->imageData;
float count[256];
//统计各灰度级的图像个数
for(int i=0;i<256;i++) count[i]=0.0f;
for( int x = 0; x < dst_gray->height; x++)
for(int y = 0; y < dst_gray->width; y++)
{
int value = dstData[x*dst_gray->widthStep+y];
count[value]=count[value]+1.0f;
}
//统计总像素个数
float allCount = dst_gray->height*dst_gray->width;
//统计阶段和,用于分布映射
for(int i=1;i<256;i++)
count[i]+=count[i-1];
//直方图均衡化变换
for( int x = 0; x < dst_gray->height; x++)
for(int y = 0; y < dst_gray->width; y++)
{
int beforeValue = dstData[x*dst_gray->widthStep+y];
int afterValue = count[beforeValue]*255/allCount;
dstData[x*dst_gray->widthStep+y] =afterValue;
}
cvShowImage("RGB", dst_gray);
cvWaitKey(0);
//统计各灰度级的图像个数
for(int i=0;i<256;i++) count[i]=0.0f;
for( int x = 0; x < dst_gray->height; x++)
for(int y = 0; y < dst_gray->width; y++)
{
int value = dstData[x*dst_gray->widthStep+y];
count[value]=count[value]+1.0f;
}
::cvReleaseImage(&src);
::cvReleaseImage(&dst_gray);
return 0;
}