OpenCV学习记录24

一 学习内容

1 计算每个通道的直方图,用红绿蓝3条线显示

1.1 提取每个通道的数据

1.2 值域归一化(最大-最小归一化)

1.3 绘制线

二 代码调试

#include
#include
#include

using namespace cv;
using namespace std;

int main() {
	Mat src;
	src = imread("e:/2 opencv_projects_zl/Hua2.jpg");
	if (src.empty()) {
		printf("Load Error.../n");
		return -1;
	}
	namedWindow("Figure1",CV_WINDOW_AUTOSIZE);
	imshow("Figure1",src);

	//学习新内容:计算每个通道的直方图,用红绿蓝3条线显示
	//1.分别提取b-g-r3个单通道
	vector bgr_planes;
	split(src,bgr_planes);
	namedWindow("Figure2-0", CV_WINDOW_AUTOSIZE);
	imshow("Figure2-0", bgr_planes[0]);
	namedWindow("Figure2-1", CV_WINDOW_AUTOSIZE);
	imshow("Figure2-1", bgr_planes[1]);
	namedWindow("Figure2-2", CV_WINDOW_AUTOSIZE);
	imshow("Figure2-2", bgr_planes[2]);

	//2.计算直方图
	int HistSize = 256;
	float range[] = { 0,256 };
	const float *HistRange = {range};//指针
	Mat b_Hist, g_Hist, r_Hist;
	//2.1 计算
	calcHist(&bgr_planes[0],1,0,Mat(),b_Hist,1,&HistSize,&HistRange,true,false);
	calcHist(&bgr_planes[1], 1, 0, Mat(), g_Hist, 1, &HistSize, &HistRange, true, false);
	calcHist(&bgr_planes[2], 1, 0, Mat(), r_Hist, 1, &HistSize, &HistRange, true, false);
	//2.2 绘制直方图
	int Hist_h = 400;
	int Hist_w = 512;
	int bin_w = Hist_w / HistSize;//每个柱子的宽度
	Mat histImage(Hist_w, Hist_h,CV_8UC3,Scalar(0,0,0));
	//2.2.1 归一化(为了显示时的最大值不超过Hist_h)
	normalize(b_Hist,b_Hist,0,Hist_h,NORM_MINMAX,-1,Mat());//将值归一化为0--Hist_h
	normalize(g_Hist, g_Hist, 0, Hist_h, NORM_MINMAX, -1, Mat());//将值归一化为0--Hist_h
	normalize(r_Hist, r_Hist, 0, Hist_h, NORM_MINMAX, -1, Mat());//将值归一化为0--Hist_h
	//2.2.2 绘图
	for (int i = 1; i < HistSize; i++)
	{
		line(histImage, Point((i - 1)*bin_w, Hist_h - cvRound(b_Hist.at(i - 1))), Point((i)*bin_w, Hist_h - cvRound(b_Hist.at(i))),Scalar(255,0,0),2,LINE_4);
		line(histImage, Point((i - 1)*bin_w, Hist_h - cvRound(g_Hist.at(i - 1))), Point((i)*bin_w, Hist_h - cvRound(g_Hist.at(i))), Scalar(0, 255, 0), 2, LINE_4);
		line(histImage, Point((i - 1)*bin_w, Hist_h - cvRound(r_Hist.at(i - 1))), Point((i)*bin_w, Hist_h - cvRound(r_Hist.at(i))), Scalar(0, 0, 255), 2, LINE_4);
	}
	namedWindow("Figure3", CV_WINDOW_AUTOSIZE);
	imshow("Figure3", histImage);
	/*备注:
		cvRound():返回跟参数最接近的整数值,即四舍五入;
		cvFloor():返回不大于参数的最大整数值,即向下取整;
		cvCeil():返回不小于参数的最小整数值,即向上取整;
		*/

	waitKey(0);
	return 0;
}

三 调试结果

OpenCV学习记录24_第1张图片

你可能感兴趣的:(OpenCV学习)