OpenCV-学习历程24- 直方图计算(直方图概念等)

OPENCV系列博客主要记录自己学习OPENCV的历程,以及存储已经实现的代码,以备后续回顾使用,代码中包含了主要的备注。

一.直方图概念 

 

 

二.直方图主要API的内容

 

三.代码测试

#include <opencv2/opencv.hpp>
#include <iostream>


using namespace std;
using namespace cv;


//测试使用OpenCV自带的HoughLineP提取图像边缘

Mat src, gray_src, average_histogram;
void update_remap(void);
int index;
Mat map_x, map_y;


//这个例子主要作用是:输入RGB图像,分别计算并显示RGB三个通道的直方图

int main(int argc, char** argv) {

	//Step1 读取图片
	src = imread("E:/OpenCVLearning/Project/source_image/sample.jpg"); //注意斜线方向
	if (!src.data) {
		cout << "Could not load the image ...." << endl;
		return -1;
	}
	char input_image[] = "input image";
	namedWindow("input_image", CV_WINDOW_AUTOSIZE);
	imshow(input_image, src);

	//Step2 将RGB分通道显示
	vector<Mat> bgr_planes;
	split(src, bgr_planes);  //!!将RGB图像分成三个通道

	//Step3  计算每个通道的直方图
	int histSize = 256;			//直方图的通道数:每一个通道0~255
	float range[] = {0,256};
	const float* histrange = {range};
	Mat b_hist, r_hist, g_hist; 
	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);

	//Step4 由于计算出的直方图有可能超限,所以需要进行归一化,以便于在一个图像中能够显示出全部曲线
	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));    //创建显示直方图的窗口
	normalize(b_hist,b_hist,0,hist_h,NORM_MINMAX,-1,Mat());//归一化:
	normalize(g_hist, g_hist, 0, hist_h, NORM_MINMAX, -1, Mat());//归一化:
	normalize(r_hist, r_hist, 0, hist_h, NORM_MINMAX, -1, Mat());//归一化:


	//Step5 遍历归一化之后的数值,然后显示在窗口内
	//      实际上就是遍历每两个点,依次收尾相连,并且用不同颜色显示出来
	for (int i = 1; i < histSize; i++) {
		line(histImage,Point((i-1)*bin_w,hist_h-cvRound(b_hist.at<float>(i-1))),
			  Point((i) * bin_w, hist_h - cvRound(b_hist.at<float>(i))),Scalar(255,0,0),2,LINE_AA);

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

		line(histImage, Point((i - 1) * bin_w, hist_h - cvRound(r_hist.at<float>(i - 1))),
			Point((i)*bin_w, hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 2, LINE_AA);
	}
	imshow("histogram", histImage);

	waitKey(0);
	return 0;
}



四. 运行效果如下:

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值