直方图与匹配

1 计算直方图:calcHist()函数
void calcHist(const Matimages,int nimages,const intchannels,InputArray mask,OutputArray hist,int dims,const inthistSize,const float**ranges,bool uniform=true,bool.accumulate=false)

2 找寻最值:minMaxLoc函数
void minMaxLoc(InputArray src,double
minVal,doublemaxVal=0,PointminLoc=0,Point*maxLoc=0,InputArray mask=noArray())

计算并绘制直方图:

include "opencv2/highgui/highgui.hpp"

include "opencv2/imgproc/imgproc.hpp"

include

using namespace cv;
using namespace std;

//-----------------------------------【ShowHelpText( )函数】-----------------------------
// 描述:输出一些帮助信息
//----------------------------------------------------------------------------------------------
void ShowHelpText()
{
//输出欢迎信息和OpenCV版本
printf(" 非常感谢购买《OpenCV3编程入门》一书! ");
printf(" 此为本书OpenCV3版的第80个配套示例程序 ");
printf(" 当前使用的OpenCV版本为:" CV_VERSION );
printf(" ---------------------------------------------------------------------------- ");
}

//--------------------------------------【main( )函数】-----------------------------------------
// 描述:控制台应用程序的入口函数,我们的程序从这里开始执行
//-------------------------------------------------------------------------------------------------
int main()
{
//【1】载入原图并显示
Mat srcImage = imread("1.jpg", 0);
imshow("原图",srcImage);
if(!srcImage.data) {cout << "fail to load image" << endl; return 0;}

system("color 1F");
ShowHelpText();

//【2】定义变量
MatND dstHist;       // 在cv中用CvHistogram *hist = cvCreateHist
int dims = 1;
float hranges[] = {0, 255};
const float *ranges[] = {hranges};   // 这里需要为const类型
int size = 256;
int channels = 0;

//【3】计算图像的直方图
calcHist(&srcImage, 1, &channels, Mat(), dstHist, dims, &size, ranges);    // cv 中是cvCalcHist
int scale = 1;

Mat dstImage(size * scale, size, CV_8U, Scalar(0));
//【4】获取最大值和最小值
double minValue = 0;
double maxValue = 0;
minMaxLoc(dstHist,&minValue, &maxValue, 0, 0);  //  在cv中用的是cvGetMinMaxHistValue

//【5】绘制出直方图
int hpt = saturate_cast<int>(0.9 * size);
for(int i = 0; i < 256; i++)
{
	float binValue = dstHist.at<float>(i);           //   注意hist中是float类型    而在OpenCV1.0版中用cvQueryHistValue_1D
	int realValue = saturate_cast<int>(binValue * hpt/maxValue);
	rectangle(dstImage,Point(i*scale, size - 1), Point((i+1)*scale - 1, size - realValue), Scalar(255));
}
imshow("一维直方图", dstImage);
waitKey(0);
return 0;

}

原文地址:https://www.cnblogs.com/shuguomeifuguo/p/12008189.html