OpenCV--c++ 学习笔记

直方图方向投影

作用:在输入图像中寻找与模板图像最匹配的区域,即定位模板图像出现在输入图像的位置。

步骤:

  1. 加载模板图像和待反向投影图像;
  2. 加载图像颜色空间,gray/HSV;
  3. 计算模板图像的直方图;
  4. 将待方向投影和模板图像的直方图赋值给反向投影函数,得到投影结果。
    #include <opencv2/opencv.hpp>
    #include <iostream>
    #include <math.h>
    
    using namespace cv;
    using namespace std;
    
    void drawHist(Mat& hist, int type, string name) {
        int hist_w = 512;
        int hist_h = 400;
        int width = 2;
        Mat histImage = Mat::zeros(hist_h, hist_w, CV_8UC3);
        normalize(hist, hist, 255, 0, type, -1, Mat());  // normalize hist values between 0 and 1
        namedWindow(name, WINDOW_NORMAL);
        imshow(name, hist);
    }
    
    int main() {
        //加载图像
        Mat img = imread("D:/images/hamd3.jpg");
        Mat sub_img = imread("D:/images/hand1.jpg");
        resize(img, img, Size(img.cols / 3, img.rows / 3), 0, 0, INTER_LINEAR);
        resize(sub_img, sub_img, Size(sub_img.cols / 3, sub_img.rows / 3), 0, 0, INTER_LINEAR);
        //cvtColor(img, img, COLOR_BGR2GRAY);
        //cvtColor(sub_img, sub_img, COLOR_BGR2GRAY);
        Mat img_HSV, sub_HSV, hist;
        if (img.empty() || sub_img.empty()) {
            printf("could not load image...\n");
            return -1;
        }
    
        imshow("img", img);
        imshow("sub_img", sub_img);
        //转换色彩空间
        cvtColor(img, img_HSV, COLOR_BGR2HSV);
        cvtColor(sub_img, sub_HSV, COLOR_BGR2HSV);
        //计算模板图像直方图
        int h_bins = 32;
        int s_bins = 32;
        int histSize[] = { h_bins, s_bins };
        float h_ranges[] = { 0, 180 };
        float s_ranges[] = { 0, 256 };
        const float* ranges[] = { h_ranges, s_ranges };  // ranges should be an array of pointers
        int channels[] = { 0, 1 };  // the channels to be used for hist computation
    
        // Compute the histogram
        calcHist(&sub_HSV, 1, channels, Mat(), hist, 2, histSize, ranges, true, false);
        drawHist(hist, NORM_INF, "hist");
        //反向投影
        Mat backproj;
        // Perform backprojection
        calcBackProject(&img_HSV, 1, channels, hist, backproj, ranges, 1.0);
        imshow("反向投影后结果", backproj);  // Avoid using Chinese characters in window names
    
        waitKey(0);
        return 0;
    }
    

代码运行结果 

  • 38
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值