您的位置:首页 > 运维架构

opencv实现灰度图像的直方图点计算以及灰度直方图显示

2016-07-11 15:56 666 查看
#include<opencv2/core/core.hpp>

#include<opencv2/highgui/highgui.hpp>

#include<opencv2/opencv.hpp>

#include"iostream"

using namespace std;

using namespace cv;

class Histogram1D

{

private:
int histSize[1];//the number of 
float hranges[2];//the maximum and min of the pixel
const float*ranges[1];
int channels[1];//only use one channel

public:
Histogram1D(){
// the parementer of the 1D histogram
histSize[0]=256;
hranges[0]=0.0;
hranges[1]=255.0;
ranges[0]=hranges;
channels[0]=0;//the normal
}
//calculate the distribution of the 1d
cv::MatND getHistogram(const cv::Mat &image)
{
cv::MatND hist;
//calculate the histogram
cv::calcHist(&image,
1,//calculate the single image's histogram
channels,//the number of channels
cv::Mat(),// not use the image as mask;
hist,//return hist
1,//one-di
histSize,//the number of 
ranges//the range of pixel
);
return hist;
}
cv::Mat getHistogramImage(const cv::Mat &image)
{
//first ,calculate the histogram
cv::MatND hist = getHistogram(image);
//receive the max and min number
double maxVal = 0;
double minVal = 0;
cv::minMaxLoc(hist,&minVal,&maxVal,0,0);
//imshow the image of histogram
cv::Mat histImg(histSize[0],histSize[0],
CV_8U,cv::Scalar(255));
//set up the highest point is the 90 precent of the nbins
int hpt = static_cast<int>(0.9*histSize[0]);
// every level,draw a vertical line
for (int h =0;h<histSize[0];h++)
{
float binVal = hist.at<float>(h);
int intensity = static_cast<int>(binVal*hpt/maxVal);
//draw a line with two point
cv::line(histImg,cv::Point(h,histSize[0]),
cv::Point(h,histSize[0]-intensity),
cv::Scalar::all(0));
}
return histImg;
}

};

int main()

{
cv::Mat image = cv::imread("D:\\ben3.jpg");
// the histogram 
Histogram1D h;
//calculate hist
cv::MatND histo=h.getHistogram(image);
//scan the every level
for(int i=0;i<256;i++)
cout<<"Value"<<i<<"="<<
histo.at<float>(i)<<endl;
cv::namedWindow("Histogram");
cv::imshow("Histogram",
h.getHistogramImage(image));
cv::Mat thresholded;
cv::threshold(image,thresholded,80,255,cv::THRESH_BINARY);
cv::namedWindow("binary image");
cv::imshow("binary image",thresholded);
cv::waitKey(0);
system("pause");
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息