直方图

#include <stdio.h>
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
	Mat src, dst;
	src = imread("lena.jpg");
	if (src.empty())
	{
		cout << "No Data!----------the error of reading image." << endl;
		return -1;
	}

	// 将源图像分割成3个单通道的图像
	vector<Mat> rgb_planes;
	split(src, rgb_planes);

	int histSize = 255;			// 特征空间子区段bin的数目
	float range[] = {0, 255};   // 特征空间的取值范围
	const float* histRange = {range};

	bool uniform = true;
	bool accumulate = false;

	// 计算直方图
	Mat r_hist, g_hist, b_hist;
	calcHist(&rgb_planes[0], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate);
	calcHist(&rgb_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate );
	calcHist(&rgb_planes[2], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate);

	// 创建直方图画布
	int hist_w = 400; 
	int hist_h = 400;
	int bin_w  = cvRound((double)hist_w / histSize);
	Mat histImage(hist_w, hist_h, CV_8UC3, Scalar(0, 0, 0));

	// 将直方图归一化到[0, histImage.rows]
	normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());
	normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());
	normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat());

	// 画直方图
	for (int i = 1; i < histSize; i++)
	{
		line(histImage, Point2f(bin_w * (i-1), hist_h - cvRound(r_hist.at<float>(i-1))),
			            Point2f(bin_w * (i), hist_h - cvRound(r_hist.at<float>(i))), 
			            Scalar( 0, 0, 255), 2, 8, 0 );


		line(histImage, Point2f(bin_w * (i-1), hist_h - cvRound(g_hist.at<float>(i-1))),
						Point2f(bin_w * (i), hist_h - cvRound(g_hist.at<float>(i))), 
						Scalar( 0, 255, 0), 2, 8, 0 );

		line(histImage, Point2f(bin_w * (i-1), hist_h - cvRound(b_hist.at<float>(i-1))),
						Point2f(bin_w * (i), hist_h - cvRound(b_hist.at<float>(i))), 
						Scalar( 255, 0, 0), 2, 8, 0 );
	}

	/// 显示直方图
	namedWindow("calcHist Demo", CV_WINDOW_AUTOSIZE );
	imshow("calcHist Demo", histImage );

	waitKey(0);

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值