颜色直方图反向投影

参考:

[1]颜色直方图特征代码:https://blog.csdn.net/u012556077/article/details/47091833
[2]https://blog.csdn.net/zhu_hongji/article/details/80443585
[3] opencv计算机视觉编程手册
[4]https://github.com/zhengguoxian123/OpenCV2-Computer-Vision-Programming-Understanding/blob/master/Chapter_04/objectfinder/objectfinder.hpp

#include
#include
#include
#include
#include

using namespace std;
using std::cout;

cv::Mat getHist(cv::Mat& image)
{
    cv::MatND hist;
    int channels[3];//只有一个通道
    int histSize[3];//项的数量
    const float* ranges[3];
    float hranges[2];//像素的最小和最大值

    histSize[0] =histSize[1] = histSize[2] = 256 / 8;
    hranges[0] = 0.0;
    hranges[1] = 255.0;
    ranges[0] = hranges;
    ranges[1] = hranges;
    ranges[2] = hranges;

    channels[0] = 0;//3个通道
    channels[1] = 1;
    channels[2] = 2;

    cv::calcHist(&image,  //
        1,        //计算单张图像的直方图
        channels, //通道数量
        cv::Mat(),//不使用图像作为掩码
        hist,     //返回的直方图
        1,        //这是1D的直方图,直方图的维度,1维的直方图
        histSize, //项的数量
        ranges);  //像素值的范围
                  //每个灰度的数量


    return hist;
}


int main()
{

    
    //...............颜色直方图.........................................
    cv::Mat image = cv::imread("group.jpg");
    if (!image.data)
        return 0;

    cv::namedWindow("Image");
    cv::imshow("Image",image);


    cv::Mat imageROI;

    imageROI = image(cv::Rect(400,100,40,50));

    cv::namedWindow("imgROI");
    cv::imshow("imgROI",imageROI);

    cv::Mat hist = getHist(imageROI);

    for (int i = 0; i < 256 / 8; i++)
    {
        cout << "Value " << i << "=" << hist.at(i) << endl;
    }

    //归一化直方图,从频数变为百分比
    cv::normalize(hist,hist,1.0);

    int channels[3];

    cv::Mat result;
    float hranges[2];
    const float* ranges[3];

    channels[0] = 0;
    channels[1] = 1;
    channels[2] = 2;


    hranges[0] = 0.0;
    hranges[1] = 255.0;
    
    ranges[0] = hranges;
    ranges[1] = hranges;
    ranges[2] = hranges;




    //255是:反向投影直方图后每个像素的值都是概率,乘以255来进行缩放
    //反向投影直方图的原理是:目标图像中像素的值在感兴趣区域中找到对应灰度的概率。
    cv::calcBackProject(&image,1,channels,hist,result,ranges,255.0);

    //对反向投影直方图进行阈值化
    cv::threshold(result,result,60,255,cv::THRESH_BINARY);

    cv::namedWindow("BackProjectHist");
    cv::imshow("BackProjectHist",result);

    cv::waitKey(1000000);

}

你可能感兴趣的:(颜色直方图反向投影)