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;
}
四. 运行效果如下: