灰度直方图

参考资料:
[1] opencv计算机视觉编程手册

#include
#include
#include
#include
#include

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(i) << endl;
    }
    //.......................灰度直方图用图显示..........................
    double maxVal = 0;
    double minVal = 0;
    cv::minMaxLoc(hist,&minVal,&maxVal,0,0);

    cout <<"min value: "<< minVal << endl;
    cout << "max value: "<(0.9*histSize[0]);

    for (int h = 0; h < histSize[0]; h++)
    {
        float  binVal = hist.at(h);
        int intensity = static_cast(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);




}

你可能感兴趣的:(灰度直方图)