灰度直方图代码实现以及注释如下:
#include<opencv2\opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
/*灰度直方图的实现*/
int main() {
Mat srcImage, grayImage;
//图像获取与判断
srcImage = imread("D:/VSproject/tupian/1(6).jpg");
if (srcImage.empty()) {
cout << "could not load the image..." << endl;
return 0;
}
imshow("srcImage", srcImage);
//灰度图转换
cvtColor(srcImage, grayImage,CV_BGR2GRAY);
//定义直方图参数
const int channels[1] = { 0 };
const int histSize[1] = { 256 };
float pranges[2] = { 0,255 };
const float*ranges[1] = { pranges };
MatND hist;
//计算直方图
calcHist(&grayImage, 1, channels, Mat(), hist, 1, histSize, ranges);
//初始化画布参数
int hist_w = 500;
int hist_h = 500;
int nHistSize = 255;
//区间
int bin_w = cvRound((double)hist_w / nHistSize);
Mat histImage(hist_w, hist_h, CV_8UC3, Scalar(255, 255, 255));
//将直方图归一化到[0,histImage,rows]
normalize(hist, hist, 0, histImage.rows,NORM_MINMAX,-1,Mat());
//在直方图画布中画出直方图
for (int i = 1; i < nHistSize; i++) {
line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(hist.at<float>(i - 1))),
Point(bin_w*(i), hist_h - cvRound(hist.at<float>(i))),Scalar(0, 0, 255), 2, 8, 0);
}
imwrite("dstImage.jpg", histImage);
imshow("histImage", histImage);
waitKey();
return 0;
}
![](https://img-blog.csdnimg.cn/20181215225100628.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxODAwOTgz,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20181215225136831.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxODAwOTgz,size_16,color_FFFFFF,t_70)