1、绘制直方图有两种方法
- 通过line函数,绘制直线实现
- 通过rectangle函数,绘制矩形实现
源码如下:
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char ** argv) {
Mat srcImage = imread("1.jpg", 0);
if (srcImage.empty()) {
printf("could not load this picture!\n");
return -1;
}
//调用calcHist函数,得到直方图数组
int bins = 256;
int * histsize = &bins;
int channel = 0;
float hRange[] = { 0, 256 };
const float * range = { hRange };
MatND histValue;
calcHist(&srcImage, 1, &channel, Mat(), histValue, 1, histsize, &range);
//归一化处理
int hist_w = 256; //输入图片的宽
int hist_h = 256; //输出图片的高
Mat histImage = Mat(hist_h, hist_w, CV_8UC3, Scalar(255, 255, 255));
int scale = cvRound(hist_w / bins); //输入图片的宽与bin的比值,为了下文等距绘制直方图
normalize(histValue, histValue, 0, histImage.rows,NORM_MINMAX, -1, Mat());
//绘制图像直方图
//for (size_t i = 0; i < bins - 1; i++) {
// line(histImage, Point(scale * i, histValue.rows - cvRound(histValue.at<float>(i))),
// Point(scale * i, histImage.rows - cvRound(histValue.at<float>(i + 1))), Scalar(), 1, LINE_AA);
//}
//使用矩形绘制图像直方图
/*
* 绘制矩形时,需要两个锚点p1和p2
* p1是指矩形左下角的点,特征是:x = i, y = 0
* p2是指矩形右上角的点,特征是:x = i+1, y = 屏幕的高减去此点的值
*/
for (size_t i = 0; i < bins - 1; i++) {
rectangle(histImage, Point(scale * i, 0),
Point(scale * (i + 1), histValue.rows - cvRound(histValue.at<float>(i + 1))), Scalar(0, 0, 0), 1, LINE_AA);
}
imshow("效果图", histImage);
imshow("源图像", srcImage);
waitKey(0);
return 0;
}