编程环境:windows下结合opencv.
//计算并获取图像的均匀灰度直方图
//dst表示灰度直方图图像,三通道彩色图像
//nBins表示灰度直方图划分的间隔数
//scalarHistColor表示灰度直方图的颜色
void GrayHist(IplImage* src, IplImage* dst, int nBins, CvScalar scalarHistColor);
void GrayHist(IplImage* src, IplImage* dst, int nBins, CvScalar scalarHistColor)
{
if (!src || !dst)
{
return;
}
if (src->nChannels == 3)
{
cvCvtColor(src, src, CV_BGR2GRAY);
}
//直方图中单个条形图的长度和高度
int nWidth = dst->width / nBins;
int nHeight = 0;
int nSizeArray[] = {nBins};
float fRangeArray[] = {0, 255};
float* fRange = fRangeArray;
CvHistogram* pHistGray = cvCreateHist(1, nSizeArray, CV_HIST_ARRAY, &fRange, 1);
float fMaxVal;//灰度直方图最大值
double dVal;
cvCalcHist(&src, pHistGray);//计算灰度直方图
//cvNormalizeHist(pHistGray, 1.0);//归一化直方图
//cvThreshHist(pHistGray, 0.01);//阈值化直方图,将小于0.01的剔除
cvGetMinMaxHistValue(pHistGray, NULL, &fMaxVal);//获取直方图最大值
//画出灰度直方图
cvZero(dst);//填充底色
for(int i = 0; i < nBins; i++)
{
dVal = cvQueryHistValue_1D(pHistGray, i);
nHeight = (dVal / fMaxVal) * dst->height;//计算当前条形图的高度
//绘制直方图
cvRectangle(dst, cvPoint(nWidth * i, dst->height - nHeight),
cvPoint(nWidth * (i + 1), dst->height), scalarHistColor);
}
//绘制阈值线
//nHeight = (0.01 / fMaxVal) * dst->height;//计算阈值线高度
//cvLine(dst, cvPoint(0, dst->height - nHeight), cvPoint(dst->width, dst->height - nHeight), CV_RGB(255, 0, 0));
cvReleaseHist(&pHistGray);
}