一、環境
OpenCV3.4.1
VS2015
二、代碼
#include <opencv2/opencv.hpp>
using namespace std;
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")
#define cvQueryHistValue_1D( hist, idx0 ) ((float)cvGetReal1D( (hist)->bins, (idx0)))
void FillWhite(IplImage *pImage)
{
cvRectangle(pImage, cvPoint(0, 0), cvPoint(pImage->width, pImage->height), CV_RGB(255, 255, 255), CV_FILLED);
}
// 創建灰度圖像的直方圖
CvHistogram* CreateGrayImageHist(IplImage **ppImage)
{
int nHistSize = 256;
float fRange[] = { 0, 255 }; //灰度級的範圍
float *pfRanges[] = { fRange };
CvHistogram *pcvHistogram = cvCreateHist(1, &nHistSize, CV_HIST_ARRAY, pfRanges);
cvCalcHist(ppImage, pcvHistogram);
return pcvHistogram;
}
// 根據直方圖創建直方圖圖像
IplImage* CreateHisogramImage(int nImageWidth, int nScale, int nImageHeight, CvHistogram *pcvHistogram)
{
IplImage *pHistImage = cvCreateImage(cvSize(nImageWidth * nScale, nImageHeight), IPL_DEPTH_8U, 1);
FillWhite(pHistImage);
//統計直方圖中的最大直方塊
float fMaxHistValue = 0;
cvGetMinMaxHistValue(pcvHistogram, NULL, &fMaxHistValue, NULL, NULL);
//分別將每個直方塊的值繪製到圖中
int i;
for (i = 0; i < nImageWidth; i++)
{
float fHistValue = cvQueryHistValue_1D(pcvHistogram, i); //像素爲i的直方塊大小
int nRealHeight = cvRound((fHistValue / fMaxHistValue) * nImageHeight); //要繪製的高度
cvRectangle(pHistImage,
cvPoint(i * nScale, nImageHeight - 1),
cvPoint((i + 1) * nScale - 1, nImageHeight - nRealHeight),
cvScalar(i, 0, 0, 0),
CV_FILLED
);
}
return pHistImage;
}
int main(int argc, char** argv)
{
const char *pstrWindowsSrcTitle = "原圖(https://blog.csdn.net/Aidam_Bo)";
const char *pstrWindowsGrayTitle = "灰度圖(https://blog.csdn.net/Aidam_Bo)";
const char *pstrWindowsHistTitle = "直方圖(https://blog.csdn.net/Aidam_Bo)";
// 從文件中加載原圖
IplImage *pSrcImage = cvLoadImage("test.jpg", CV_LOAD_IMAGE_UNCHANGED);
IplImage *pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
// 灰度圖
cvCvtColor(pSrcImage, pGrayImage, CV_BGR2GRAY);
// 灰度直方圖
CvHistogram *pcvHistogram = CreateGrayImageHist(&pGrayImage);
// 創建直方圖圖像
int nHistImageWidth = 255;
int nHistImageHeight = 150; //直方圖圖像高度
int nScale = 2;
IplImage *pHistImage = CreateHisogramImage(nHistImageWidth, nScale, nHistImageHeight, pcvHistogram);
// 顯示
cvNamedWindow(pstrWindowsSrcTitle, CV_WINDOW_AUTOSIZE);
cvNamedWindow(pstrWindowsGrayTitle, CV_WINDOW_AUTOSIZE);
cvNamedWindow(pstrWindowsHistTitle, CV_WINDOW_AUTOSIZE);
cvShowImage(pstrWindowsSrcTitle, pSrcImage);
cvShowImage(pstrWindowsGrayTitle, pGrayImage);
cvShowImage(pstrWindowsHistTitle, pHistImage);
cvWaitKey(0);
cvReleaseHist(&pcvHistogram);
cvDestroyWindow(pstrWindowsSrcTitle);
cvDestroyWindow(pstrWindowsGrayTitle);
cvDestroyWindow(pstrWindowsHistTitle);
cvReleaseImage(&pSrcImage);
cvReleaseImage(&pGrayImage);
cvReleaseImage(&pHistImage);
return 0;
}
注意:這裏用到函數 cvQueryHistValue_1D是OpenCV2的,在OpenCV3中沒有這個函數,筆者使用的OpenCV是3.4.1版本,所以定義宏來使用cvQueryHistValue_1D:
#define cvQueryHistValue_1D( hist, idx0 ) ((float)cvGetReal1D( (hist)->bins, (idx0)))
三、結果展示