opencv 绘制图像直方图

为图像绘制直方图,效果图如下:


代码如下:

	// Separate image in BRg
	vector<Mat> bgr;
	split(img, bgr);
	// Create the histogram for 256 bins
	// The number of possibles values [0..255]
	int numbins = 256;
	/// Set the ranges ( for B,g,R) ), last is not included
	float range[] = { 0, 256 };
	const float* histRange = { range };
	Mat b_hist, g_hist, r_hist;
	calcHist(&bgr[0], 1, 0, Mat(), b_hist, 1, &numbins,
		&histRange);
	calcHist(&bgr[1], 1, 0, Mat(), g_hist, 1, &numbins,
		&histRange);
	calcHist(&bgr[2], 1, 0, Mat(), r_hist, 1, &numbins,
		&histRange);
	// Draw the histogram
	// We go to draw lines for each channel
	int width = 512;
	int height = 300;
	// Create image with gray base
	Mat histImage(height, width, CV_8UC3, Scalar(20, 20, 20));
	cout << histImage.size();
	// normalize the histograms to height of image
	normalize(b_hist, b_hist, 0, height, NORM_MINMAX);
	normalize(g_hist, g_hist, 0, height, NORM_MINMAX);
	normalize(r_hist, r_hist, 0, height, NORM_MINMAX);
	int binStep = cvRound((float)width / (float)numbins);
	for (int i = 1; i< numbins; i++)
	{
		line(histImage,
			Point(binStep*(i - 1), height - cvRound(b_hist.at<float>(i - 1))),
			Point(binStep*(i), height - cvRound(b_hist.at<float>(i))),
			Scalar(255, 0, 0));
		line(histImage,
			Point(binStep*(i - 1), height - cvRound(g_hist.at<float>(i - 1))),
			Point(binStep*(i), height - cvRound(g_hist.at<float>(i))),
			Scalar(0, 255, 0));
		line(histImage,
			Point(binStep*(i - 1), height - cvRound(r_hist.at<float>(i - 1))),
			Point(binStep*(i), height - cvRound(r_hist.at<float>(i))),
			Scalar(0, 0, 255));
	}
	imshow("Histogram", histImage);



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值