参考资料:
[1] opencv计算机视觉编程手册
#include<iostream>
#include<opencv2/opencv.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using std::cout;
int main()
{
//...............灰度直方图.........................................
cv::Mat image = cv::imread("group.jpg",0);
if (!image.data)
return 0;
cv::namedWindow("Image");
cv::imshow("Image",image);
cv::MatND hist;
int channels[1];//只有一个通道
int histSize[1];//项的数量
const float* ranges[1];
float hranges[2];//像素的最小和最大值
histSize[0] = 256;
hranges[0] = 0.0;
hranges[1] = 255.0;
ranges[0] = hranges;
channels[0] = 0;//默认情况下,我们考察0号通道
cv::calcHist(&image, //
1, //计算单张图像的直方图
channels, //通道数量
cv::Mat(),//不使用图像作为掩码
hist, //返回的直方图
1, //这是1D的直方图,直方图的维度,1维的直方图
histSize, //项的数量
ranges); //像素值的范围
//每个灰度的数量
for (int i = 0; i < 256; i++)
{
cout << "Value " << i << "=" << hist.at<float>(i) << endl;
}
//.......................灰度直方图用图显示..........................
double maxVal = 0;
double minVal = 0;
cv::minMaxLoc(hist,&minVal,&maxVal,0,0);
cout <<"min value: "<< minVal << endl;
cout << "max value: "<<maxVal << endl;
cv::Mat histImg(histSize[0],histSize[0],CV_8U,cv::Scalar(255));
int hpt = static_cast<int>(0.9*histSize[0]);
for (int h = 0; h < histSize[0]; h++)
{
float binVal = hist.at<float>(h);
int intensity = static_cast<int>(binVal/maxVal*hpt);
//
cv::line(histImg,cv::Point(h,histSize[0]),
cv::Point(h,histSize[0]-intensity),cv::Scalar::all(0));
}
cv::namedWindow("Histgram");
cv::imshow("Histgram",histImg);
//.......................图像阈值化........................
cv::Mat thresholded;
cv::threshold(image,thresholded,60,255,cv::THRESH_BINARY);
cv::namedWindow("Threshold");
cv:imshow("Threshold", thresholded);
cv::Mat result;
//直方图均衡化,一幅图像应该平均使用所有的像素强度,用来增强图像的对比度
cv::equalizeHist(image,result);
cv::namedWindow("result");
cv::imshow("result",result);
cv::waitKey(1000000);
}