#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
//绘制1维直方图。
int main()
{
//1 载入源图,转换为hsv图。
Mat srcimage = imread("放牛图.jpg");
//2.准备calchist参数。
Mat histb, histg, histr;
int channelb[] = {0};
int channelg[] = {1};
int channelr[] = {2};
int size = 256;
int hist_size[] = { size };
float range[] = { 0,256 };
const float* ranges[] = { range };
//3.计算b,g,r通道直方图。
calcHist(&srcimage,1,channelb,Mat(),histb,1,hist_size,ranges,true,false);
calcHist(&srcimage,1,channelg,Mat(),histg,1,hist_size,ranges,true,false);
calcHist(&srcimage,1,channelr,Mat(),histr,1,hist_size,ranges,true,false);
//4.准备画图参数。
int scal = 1;
Mat result = Mat::zeros(size*scal,size*3,CV_8UC3);
double maxvalueb,maxvalueg,maxvaluer;
minMaxLoc(histb,0,&maxvalueb,0,0);
minMaxLoc(histg,0,&maxvalueg,0,0);
minMaxLoc(histr,0,&maxvaluer,0,0);
//5.画图。
for (int i = 0; i < size; i++)
{
float pexelb = histb.at<float>(i);
float pexelg = histg.at<float>(i);
float pexelr = histr.at<float>(i);
int yb = cvRound(pexelb*size/maxvalueb);
int yg = cvRound(pexelg*size/maxvalueg);
int yr = cvRound(pexelr*size/maxvaluer);
rectangle(result,Point(i*scal,size*scal),Point((i+1)*scal,size-yb),Scalar(255,0,0),FILLED);
rectangle(result,Point(i*scal+size*scal,size*scal),Point((i+1)*scal+size*scal,size-yg),Scalar(0,255,0),FILLED);
rectangle(result,Point(i*scal+2*size*scal,size*scal),Point((i+1)*scal+2*size*scal,size-yr),Scalar(0,0,255),FILLED);
}
//6 显示图片
imshow("result",result);
imshow("srcimage",srcimage);
waitKey(0);
return 0;
}
绘制rgb三维维直方图
最新推荐文章于 2022-04-15 16:18:58 发布