#include "iostream"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
Mat img, gray;
img = imread("r4.jpg");
cvtColor(img, gray, COLOR_BGR2GRAY);
int nimages = 1;//图片数量
const int channels[] = { 0 };//需要统计直方图的第几通道
Mat hist ;//直方图计算的输出值 Mat
int dims = 1;
const int histSize[] = { 256 }; //直方图每一个维度划分的柱条的数目
float pranges[] = { 0, 255 };//取值区间
const float* ranges[] = { pranges };
calcHist(&gray, nimages, channels, Mat(), hist, dims, histSize, ranges);
Mat dst;
double alpha = 1;
double beta = 0;
int norm_type = NORM_INF;
int dtype = -1;
normalize(hist, dst, alpha, beta, NORM_INF, dtype, Mat());
int hist_height = 256;
int hist_width = 1024;
int unit_width = cvRound(hist_width / histSize[0]);
float rowvalue = 0;
Point zs, yx, ys;//直方图左上方的点,右上方的点,右下方的点
Mat picture = Mat::zeros(Size(hist_width, hist_height), CV_8UC3);
for (int i = 0; i < dst.rows; i++)
{
rowvalue = dst.at<float>(i);
int heighttemp = hist_height - cvRound(hist_height * rowvalue);//翻转
zs = Point(i*unit_width, heighttemp);
ys = Point(i*unit_width + 1, heighttemp);
yx = Point(i*unit_width + 1, hist_height);
//直方图
rectangle(picture, zs, yx, Scalar(255, 0, 0));
//线
line(picture, zs, ys, Scalar(0, 0, 255));
}
imshow("picture", picture);
waitKey(0);
return 1;
}