美文网首页
opencv模板匹配

opencv模板匹配

作者: 一路向后 | 来源:发表于2021-12-20 21:16 被阅读0次

    1.源码实现

    #include <cstdio>
    #include <iostream>
    #include <opencv2/highgui/highgui.hpp>
    #include <opencv2/imgproc/imgproc.hpp>
    
    using namespace std;
    using namespace cv;
    
    void MatchingMethod(Mat &img, Mat &temp, Mat &result, const int match_method)
    {
        //将被显示的原图像
        Mat img_display;
    
        img.copyTo(img_display);
    
        //创建输出结果的矩阵
        int result_cols = img.cols - temp.cols + 1;
        int result_rows = img.rows - temp.rows + 1;
    
        //进行匹配和标准化
        matchTemplate(img, temp, result, match_method);
        normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
    
        //通过函数 minMaxLoc 定位最匹配的位置
        Point minLoc, maxLoc, matchLoc;
        double minVal, maxVal;
    
        minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
    
        //对于方法 SQDIFF 和 SQDIFF_NORMED, 越小的数值代表更高的匹配结果. 而对于其他方法, 数值越大匹配越好
        if(match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED)
        {
            matchLoc = minLoc;
        }
        else
        {
            matchLoc = maxLoc;
        }
    
        //看看最终结果
        rectangle(img_display, matchLoc, Point(matchLoc.x + temp.cols , matchLoc.y + temp.rows), Scalar(0, 0, 255), 2, 8, 0);
        rectangle(result, matchLoc, Point(matchLoc.x + temp.cols , matchLoc.y + temp.rows), Scalar::all(0), 2, 8, 0);
    
        //cout << img_display << endl;
    
        imwrite("matchresult.jpg", img_display);
    }
    
    int main(int argc, char **argv)
    {
        if(argc <= 2)
        {
            return -1;
        }
    
        //载入原图像和模板块
        Mat img = imread(argv[1], 1);
        Mat temp = imread(argv[2], 1);
        Mat result;
    
        //设置方法Method: 0: SQDIFF 1: SQDIFF NORMED 2: TM CCORR 3: TM CCORR NORMED 4: TM COEFF 5: TM COEFF NORMED
        int method = 1;
    
        MatchingMethod(img, temp, result, method);
    
        return 0;
    }
    

    2.编译源码

    $ g++ -o test test.cpp -std=c++11 -I/usr/local/include/opencv4 -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lopencv_ml -Wl,-rpath=/usr/local/lib
    

    3.运行及其结果

    3.jpg
    6.jpg
    matchresult.jpg

    相关文章

      网友评论

          本文标题:opencv模板匹配

          本文链接:https://www.haomeiwen.com/subject/shzzfrtx.html