RGB转为灰度图是为了丢掉图片的颜色信息,而保留亮度信息
#include <opencv2/opencv.hpp> #include<opencv2/imgproc/imgproc.hpp> using namespace cv; // 显示灰度直方图 Mat getHistImg(const MatND& hist) { double maxVal=0; double minVal=0; //找到直方图中的最大值和最小值 minMaxLoc(hist,&minVal,&maxVal,0,0); int histSize=hist.rows; Mat histImg(histSize,histSize,CV_8U,Scalar(255)); // 设置最大峰值为图像高度的90% int hpt=static_cast<int>(0.9*histSize); for(int h=0;h<histSize;h++) { float binVal=hist.at<float>(h); int intensity=static_cast<int>(binVal*hpt/maxVal); line(histImg,Point(h,histSize),Point(h,histSize-intensity),Scalar::all(0)); } return histImg; } // 主函数 int main() { Mat Image=imread("I:\\work\\挑战杯\\颜色直方图原图.jpg"); imshow("原图", Image); cvtColor(Image,Image,CV_BGR2GRAY); const int channels[1]={0}; const int histSize[1]={256}; float hranges[2]={0,255}; const float* ranges[1]={hranges}; MatND hist; calcHist(&Image,1,channels,Mat(),hist,1,histSize,ranges); hist = getHistImg(hist); imshow("颜色直方图", hist); waitKey(0); return 0; }
时间: 2024-10-13 05:16:00