OpenCV基础课程笔记25直方图计算
写在前面
这里贾志刚老师做绘制的Mat长宽弄反了……但是……他没看出来……
 东西都在注释里,不多说。
代码
#include<iostream>
#include<opencv2/opencv.hpp>
#include<cmath>
#include<string>
using namespace std;
using namespace cv;
int main() {
	Mat src = imread("A:\\专用\\TestForTheCV\\代替女友出境.jpg");
	Mat dst;
	imshow("图片", src);
	//分通道显示
	vector<Mat> bgrimage;
	split(src, bgrimage);
	String bgrWinString[3] = { "B","G","R" };
	for (int i = 0; i < 3; i++) {
		imshow(bgrWinString[i], bgrimage[i]);
	}
	//计算直方图
	int histsize = 256;
	float range[] = { 0, 256 };
	const float *histranges = { range };	//这里不加const,calcHist函数不接受
	Mat bhist, ghist, rhist;
	calcHist(&bgrimage[0], 1, 0, Mat(), bhist,1, &histsize, &histranges, true, false);
	calcHist(&bgrimage[1], 1, 0, Mat(),ghist, 1, &histsize, &histranges, true, false);
	calcHist(&bgrimage[2], 1, 0, Mat(), rhist, 1, &histsize, &histranges, true, false);
	//为了显示上面的计算结果,所以进行归一化并且绘制直方图
	int hist_h = 400;
	int hist_w = 512;
	int bin_w = hist_w / histsize;
	Mat histimage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0));//在做这个Mat的时候,贾志刚老师长宽放反了
	normalize(bhist, bhist, 0, hist_h, NORM_MINMAX, -1, Mat());
	normalize(ghist, ghist, 0, hist_h, NORM_MINMAX, -1, Mat());
	normalize(rhist, rhist, 0, hist_h, NORM_MINMAX, -1, Mat());
	//绘制
	for (int i = 1; i < histsize; i++) {
		line(histimage,
			Point((i - 1)*bin_w, hist_h - cvRound(bhist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(bhist.at<float>(i))),
			Scalar(255, 0, 0), 2, LINE_AA
		);
		line(histimage,
			Point((i - 1)*bin_w, hist_h - cvRound(ghist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(ghist.at<float>(i))),
			Scalar(0, 255, 0), 2, LINE_AA
		);
		line(histimage,
			Point((i - 1)*bin_w, hist_h - cvRound(rhist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(rhist.at<float>(i))),
			Scalar(0, 0, 255), 2, LINE_AA
		);
	}
	imshow("彩色直方图", histimage);
	waitKey(0);
	return 0;
}
 
运行结果

 
                    
                
                
            
        
浙公网安备 33010602011771号