函数中主要使用的 calcHist() 函数来统计一个直方图,直方图统计类的头文件和源文件,头文件代码如下:
#ifndef HISTOGRAM1D_H #define HISTOGRAM1D_H #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; class Histogram1D { public: Histogram1D(); MatND getHistogram(const Mat &source); Mat getHistogramImage(const Mat &source); private: int histSize[1]; //直方图项数 int channels[1]; //通道数量 float histMinMax[2]; //像素最小值最大值 const float* ranges[1]; //像素值范围 }; #endif // HISTOGRAM1D_H
#include "histogram1d.h" Histogram1D::Histogram1D() { //1D参数初始化 histSize[0] = 256; histMinMax[0] = 0.0; histMinMax[1] = 255.0; ranges[0] = histMinMax; channels[0] = 0; } MatND Histogram1D::getHistogram(const Mat &source) { MatND Hist; calcHist(&source, 1, channels, Mat(), Hist, 1, histSize, ranges); return Hist; } Mat Histogram1D::getHistogramImage(const Mat &source) { MatND hist = getHistogram(source);//计算直方图 double maxVal = 0; double minVal = 0; minMaxLoc(hist, &minVal, &maxVal);//获取最大值和最小值 Mat histImg(histSize[0], histSize[0], CV_8U, Scalar(255));//用于显示直方图图像 int topPoint = static_cast<int>(0.9*histSize[0]); for ( int i = 0; i < histSize[0]; i ++ ) { float binVal = hist.at<float>(i); int intensity = static_cast<int>(binVal*topPoint/maxVal); line(histImg, Point(i, histSize[0]), Point(i, histSize[0]-intensity), Scalar::all(0)); } return histImg; }
#include <QCoreApplication> #include <histogram1d.h> using namespace cv; using namespace std; int main() { Mat src = imread("lena.jpg",0); Histogram1D Hg; Mat HistImg = Hg.getHistogramImage(src); namedWindow("HistImg", 0); imshow("HistImg", HistImg); waitKey(0); return 0; }
函数介绍:
void calcHist(const Mat* arrays, //输入的源图像 int narrays, //计算直方图数量 const int* channels, //通道数量 InputArray mask, //掩码 OutputArray hist, //返回的直方图 int dims, //维数 const int* histSize, //直方图项数 const float** ranges, //像素值范围 bool uniform = true,// bool accumulate = false );//2、MatND 类型是一个通用类,可以操作N维矩阵。他也定义了一维、二维、三维矩阵的 at 方法。