opencv中的模板匹配

1 匹配函数

opencv 提供了一个专门用于模板匹配的函数 cv::matchTemplate();其调用方式如下:

void cv::matchTemplate(

    cv::InputArray image, // 用于搜索的输入图像, 8U 或 32F, 大小 W-H

    cv::InputArray templ, // 用于匹配的模板,和image类型相同, 大小 w-h

    cv::OutputArray result, // 匹配结果图像, 类型 32F, 大小 (W-w+1)-(H-h+1)

    int method // 用于比较的方法

);

1.1 method

其中第四个参数int method代表指定的匹配方法,opencv提供了6中匹配方式:

1、平方差匹配算法method=TM_SQDIFF

这类方法利用平法差来进行匹配,最好匹配为0,而若匹配越差,匹配值则越大

2、归一化平方差匹配法method=TM_SQDIFF_NORMED

3、相关匹配法method=TM_CCORR

这类方法采用模板和图像之间的惩罚操作,所以较大的数表示匹配程度较高,0标识最坏的匹配效果;

4、归一化相关匹配法method=TM_CCORR_NORMED

5、系数匹配法method=TM_CCOEFF

这类方法将模板对其均值的相对值与图像对其均值的相关值进行匹配,1表示完美匹配,-1表示糟糕匹配,而0表示没有任何相关性;

其中

6、化相关系数匹配法method=TM_CCOEFF_NORMED

 6个使用时均可以在其前加上cv_前缀;

 1.2 result

        1.2.1 result的含义:

        模板匹配函数cv::MatchTemplate一次计算模板与待测图像的相似度,并将结果存入映
图像result中,也就是result图像中的每一个点的值代表一次相似度比较结果;其中,模
通过在待检测的图像上从左到右,从上到下滑动,每到达一个像素点,就会以这个像素点
左上角顶点从原图像中截取一个与模板大小一样的图像进行像素比较的运算,模板在滑动
过程中,将模板和当前截取的图像的比较计算结果储存在result矩阵中,result的大小为(W
w+1,H-h+1),在result中的每个位置(x,y)的值都表示以这个点为左上角顶点截取的图像
模板像素计算后的计算结果;模板在待测图像上每次在横向或者纵向上每次移动一个像素点
然后进行一次比较,所以横向比较W-w+1次,纵向比较H-h+1次,最终得到一个(W
w+1)x(H-h+1)的result矩阵;

        1.2.2 ROI区域的获取使用

        cv::MinMaxLoc(result,&min_val,&max_val,&min_loco,&max_loc,NULL);从result中提取最大值(相似度最高)以及最大值的位置(即在result中该最大值max_val的坐标位置max_loc,即模板滑行时左上角的坐标,类似于图中的坐标(x,y);
由此得到rect=cvRect(max_loc.x,max_loc.y,tmp->width,tmp->height); 其中rect表示最佳的匹配的矩形区域;

    minVal参数表示返回的最小值,如果不需要,则使用NULL。
    maxVal参数表示返回的最大值,如果不需要,则使用NULL。
    minLoc参数表示返回的最小位置的指针(在2D情况下); 如果不需要,则使用NULL。
    maxLoc参数表示返回的最大位置的指针(在2D情况下); 如果不需要,则使用NULL。

2 代码实现

2.1 单目标匹配

#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

int main()
{
    Mat img, templ, result;      //img为待测图 templ是目标图片  result是结构图
    img = imread("../1.jpg");
    templ = imread("../2.jpg");

    //1.构建结果图像resultImg(注意大小和类型)
    //如果原图(待搜索图像)尺寸为W x H, 而模版尺寸为 w x h, 则结果图像尺寸一定是(W-w+1)x(H-h+1)
    //结果图像必须为单通道32位浮点型图像
    int result_cols = img.cols - templ.cols + 1;       //result的尺寸大小
    int result_rows = img.rows - templ.rows + 1;
    result.create(result_cols, result_rows, CV_32FC1);

    //2.模版匹配
    //这里我们使用的匹配算法是标准平方差匹配 method=CV_TM_SQDIFF_NORMED,数值越小匹配度越好
    matchTemplate(img, templ, result, CV_TM_SQDIFF_NORMED);
    //3.正则化(归一化到0-1)
    normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());

    //4.找出resultImg中的最大值及其位置
    double minVal = -1;
    double maxVal;
    Point minLoc;
    Point maxLoc;
    Point matchLoc;
    cout << "匹配度:" << minVal << endl;
    // 定位极值的函数
    minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, Mat());
    cout << "匹配度:" << minVal << endl;
    cout << "minPosition: " << minLoc << endl;
    cout << "maxPosition: " << maxLoc << endl;

    matchLoc = minLoc;     
    //5.根据resultImg中的最大值位置在源图上画出矩形和中心点
    Point center = Point(minLoc.x + templ.cols / 2, minLoc.y + templ.rows / 2);
    rectangle(img, matchLoc, Point(matchLoc.x + templ.cols, matchLoc.y + templ.rows), Scalar(0, 255, 0), 2, 8, 0);
    circle(img, center, 2, Scalar(255, 0, 0), 2);

    imshow("img", img);
    imshow("template", templ);
    waitKey(0);

    return 0;
}

效果图:

 2.2 实时单目标识别

#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;

int main()
{
    //1.定义VideoCapture类对象video,打开摄像头
    VideoCapture video(0);
    //1.1.判断是否打开
    if (!video.isOpened())
    {
        cout << "video open error!" << endl;
        return 0;
    }
    //2.循环读取视频的每一帧,对每一帧进行模版匹配
    while (1)
    {
        //2.1.读取帧
        Mat frame;
        video >> frame;
        //2.2.对帧进行异常检测
        if (frame.empty())
        {
            cout << "frame empty" << endl;
            break;
        }
        //2.3.对帧进行模版匹配
        Mat tempImg = imread("../1.jpg", CV_LOAD_IMAGE_COLOR);
        cout << "Size of template: " << tempImg.size() << endl;
        //2.3.1.构建结果图像resultImg(注意大小和类型)
        //如果原图(待搜索图像)尺寸为W x H, 而模版尺寸为 w x h, 则结果图像尺寸一定是(W-w+1)x(H-h+1)
        //结果图像必须为单通道32位浮点型图像
        int width = frame.cols - tempImg.cols + 1;
        int height = frame.rows - tempImg.rows + 1;
        Mat resultImg(Size(width, height), CV_32FC1);
        //2.3.2.模版匹配
        matchTemplate(frame, tempImg, resultImg, CV_TM_CCOEFF_NORMED);
        imshow("result", resultImg);
        //2.3.3.正则化(归一化到0-1)
        normalize(resultImg, resultImg, 0, 1, NORM_MINMAX, -1);
        //2.3.4.找出resultImg中的最大值及其位置
        double minValue = 0;
        double maxValue = 0;
        Point minPosition;
        Point maxPosition;
        minMaxLoc(resultImg, &minValue, &maxValue, &minPosition, &maxPosition);
        cout << "minValue: " << minValue << endl;
        cout << "maxValue: " << maxValue << endl;
        cout << "minPosition: " << minPosition << endl;
        cout << "maxPosition: " << maxPosition << endl;
        //2.3.5.根据resultImg中的最大值位置在源图上画出矩形
        rectangle(frame, maxPosition, Point(maxPosition.x + tempImg.cols, maxPosition.y + tempImg.rows), Scalar(0, 255, 0), 1, 8);
        imshow("srcImg", frame);
        imshow("template", tempImg);
        if (waitKey(10) == 27)
        {
            cout << "ESC退出" << endl;
            break;
        };
    }
    return 0;
}

 2.3多目标模板匹配

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

Point getNextMinLoc(Mat &result, Point minLoc, int maxValue, int templatW, int templatH);

int main()
{
    Mat src = imread("../1.jpg");
    Mat srcCopy = src.clone();

    Mat temp = imread("../2.jpg");
    Mat result;

    if (src.empty() || temp.empty())
    {
        cout << "打开图片失败" << endl;
        return 0;
    }

    vector<Mat> templat;
    vector<float> minV;
    vector<Point> minL;

    int srcW, srcH, templatW, templatH, resultH, resultW;
    srcW = src.cols;
    srcH = src.rows;
    templat.push_back(temp);
    double minValue, maxValue;
    Point minLoc, maxLoc;

    for (int i=0;i<10;i++)
    {
        cout << i << ": ";
        templatW = templat[i].cols;
        templatH = templat[i].rows;

        if (srcW < templatW || srcH < templatH)
        {
            cout << "模板不能比原图大" << endl;
            return 0;
        }

        resultW = srcW - templatW + 1;
        resultH = srcH - templatH + 1;

        result.create(Size(resultW, resultH), CV_32FC1);
        matchTemplate(src, templat[i], result, CV_TM_SQDIFF_NORMED);

        minMaxLoc(result, &minValue, &maxValue, &minLoc, &maxLoc);

        cout << "min1: " << minValue << endl;
        if (minValue<=0.070055)
        {
            rectangle(srcCopy, minLoc, Point(minLoc.x + templatW, minLoc.y + templatH), Scalar(0, 0, 255), 2, 8, 0);

            Point new_minLoc;
            new_minLoc = getNextMinLoc(result, minLoc, maxValue, templatW, templatH);

            float *data = result.ptr<float>(new_minLoc.y);

            cout << "min2: " << data[new_minLoc.x] << " ";
            if (data[new_minLoc.x]<=0.5)
            {
                cout << "进这个函数了:" << i << ":" << new_minLoc.x;
                cout << " " << new_minLoc.y;
                rectangle(srcCopy, new_minLoc, Point(new_minLoc.x + templatW, new_minLoc.y + templatH),
                          Scalar(0, 255, 0), 2, 8, 0);
                new_minLoc = getNextMinLoc(result, new_minLoc, maxValue, templatW, templatH);
            }

            float *data1 = result.ptr<float>(new_minLoc.y);
            cout << "min3: " << data1[new_minLoc.x] << " " << endl;
            if (data1[new_minLoc.x] <= 0.4)
            {

                rectangle(srcCopy, new_minLoc, Point(new_minLoc.x + templatW, new_minLoc.y + templatH),
                          Scalar(255, 0, 0), 2, 8, 0);
            }
        }
        cout << "#" << endl;
        Mat temp_templat;
        resize(templat[i], temp_templat, Size(templat[i].cols / 1.1, templat[i].rows / 1.1));
        templat.push_back(temp_templat);
    }

    imshow("结果", srcCopy);
    waitKey(0);
    return 0;
}

Point getNextMinLoc(Mat &result, Point minLoc, int maxValue, int templatW, int templatH)
{
    //imshow("result", result);
    //cout << "maxvalue: " << maxValue << endl;
    int startX = minLoc.x - templatW / 3;
    int startY = minLoc.y - templatH / 3;
    int endX = minLoc.x + templatW / 3;
    int endY = minLoc.y + templatH / 3;
    if (startX < 0 || startY < 0)
    {
        startX = 0;
        startY = 0;
    }
    if (endX > result.cols - 1 || endY > result.rows - 1)
    {
        endX = result.cols - 1;
        endY = result.rows - 1;
    }
    int y, x;
    for (y = startY; y < endY; y++)
    {
        for (x = startX; x < endX; x++)
        {
            float *data = result.ptr<float>(y);

            data[x] = maxValue;
        }
    }
    double new_minValue, new_maxValue;
    Point new_minLoc, new_maxLoc;
    minMaxLoc(result, &new_minValue, &new_maxValue, &new_minLoc, &new_maxLoc);
    //imshow("result_end", result);
    return new_minLoc;
}

效果图:

通过得到的结果我们发现我们的模板匹配好像匹配区域与模板的尺寸是一致的,由此很容易产生误差,或是得到并不理想的区域,而在实际生活中,由于待测图像与摄像头之间的距离的变换,模板的大小因素的影响,若是想要得到较好的匹配结果,则需要我们实现自适应尺寸的模板匹配;

由此,我们开始进行自适应尺寸的模板匹配,载入的模板图像,另其进入循环,每次循环缩放一定的比例,在进行模板匹配,最终我们得到了不同比例下的ROI区域,对所有的ROI区域与我们的模板图片进行相似度的比较,选出相似度最高的匹配图像,同时获得最佳的匹配比例;

2.4 自适应目标匹配

代码流程:

        1,载入待测图像与模板;

        2,将模板图像等比例放大或缩小

        3,没改变一次进行一次模板匹配

        4,得到匹配区域的图片

        5,将得到的ROI图片与原始模板进行相似性比较

        6,筛选出相似性最好的ROI区域

        7,在待测图片上进行框选

        8,输出图片

代码如下:

下面的代码并没有做第六步的内容,可以考虑将相似性返回值进行比较,找到最优值后,进行输出,在这里我只是做了一个相当于阈值的比较;

#include <opencv2/opencv.hpp>
#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

int pHash(Mat matSrc1, Mat matSrc2)
//int main()
{
    Mat matDst1, matDst2;

//    Mat matSrc1 = imread("../1.jpg");
//    Mat matSrc2 = imread("../3.jpg");

    cv::resize(matSrc1, matDst1, cv::Size(32, 32), 0, 0, cv::INTER_CUBIC);
    cv::resize(matSrc2, matDst2, cv::Size(32, 32), 0, 0, cv::INTER_CUBIC);

    cv::cvtColor(matDst1, matDst1, CV_BGR2GRAY);
    cv::cvtColor(matDst2, matDst2, CV_BGR2GRAY);

    matDst1.convertTo(matDst1, CV_32F);
    matDst2.convertTo(matDst2, CV_32F);
    dct(matDst1, matDst1);
    dct(matDst2, matDst2);

    int iAvg1 = 0, iAvg2 = 0;
    int arr1[64], arr2[64];

    for (int i = 0; i < 8; i++)
    {
        uchar* data1 = matDst1.ptr<uchar>(i);
        uchar* data2 = matDst2.ptr<uchar>(i);

        int tmp = i * 8;

        for (int j = 0; j < 8; j++)
        {
            int tmp1 = tmp + j;

            arr1[tmp1] = data1[j];
            arr2[tmp1] = data2[j];

            iAvg1 += arr1[tmp1];
            iAvg2 += arr2[tmp1];
        }
    }

    iAvg1 /= 64;
    iAvg2 /= 64;

    for (int i = 0; i < 64; i++)
    {
        arr1[i] = (arr1[i] >= iAvg1) ? 1 : 0;
        arr2[i] = (arr2[i] >= iAvg2) ? 1 : 0;
    }

    int iDiffNum = 0;

    for (int i = 0; i < 64; i++)
        if (arr1[i] != arr2[i])
            ++iDiffNum;
//    cout<<iDiffNum<<endl;
    return iDiffNum;
}

//int main()
//{
//    Mat img,templ,result;
//    img = imread("../1.jpg");
//    templ = imread("../2.jpg");
//
//    int result_cols = img.cols - templ.cols + 1;
//    int result_rows = img.rows - templ.rows + 1;
//
//    result.create(result_cols,result_rows,CV_32FC1);
//    matchTemplate(img, templ, result, CV_TM_SQDIFF_NORMED);
//
//    Point minLoc;
//    Point maxLoc;
//    double minVal = -1;
//    double maxVal;
//
//    minMaxLoc(result,&minVal,&maxVal,&minLoc,&maxLoc,Mat());
//    cout<<"minLoc.x:"<<minLoc.x<<endl;
//    cout<<"minLoc.y:"<<minLoc.y<<endl;
//    cout<<"result_cols:"<<result_cols<<endl;
//
//    int ROI_rows =templ.rows - 0.05*templ.rows;
//    int ROI_cols =templ.cols - 0.05 *templ.cols;
//
//    Rect img_ROI = Rect(minLoc.x, minLoc.y,ROI_rows,ROI_cols);
//
//    Mat ROI = img(img_ROI);
//    pHash(ROI,templ);
//
//}

int main()
{
    //加载图片
    Mat src_img,temp_img,result_img;
    src_img = imread("../1.jpg");
    temp_img = imread("../2.jpg");

    imshow("src_img",src_img);
    imshow("temp_img",temp_img);

    //构建结果图像,结果图像必须是单通道32位浮点型图像
    int result_cols = src_img.cols - temp_img.cols + 1;       //result的尺寸大小
    int result_rows = src_img.rows - temp_img.rows + 1;
    result_img.create(result_cols, result_rows, CV_32FC1);

    int n = 0;

    //循环缩放模板图片
    for(int i = 0; i <10; i++)
    {
        cout<<i<<endl;
        Mat temp_imgc = temp_img.clone();
        int temp_imgc_col = temp_img.cols - i * 0.05 * temp_img.cols;
        int temp_imgc_row = temp_img.rows - i * 0.05 * temp_img.rows;
        resize(temp_imgc,temp_imgc,Size(temp_imgc_col,temp_imgc_row));

        //进行模板匹配
        matchTemplate(src_img,temp_imgc,result_img,0);

        double minVal = -1;
        double maxVal;
        Point minLoc;
        Point maxLoc;
        Point matchLoc;
        minMaxLoc(result_img, &minVal, &maxVal, &minLoc, &maxLoc, Mat());

        Rect ROI = Rect(minLoc.x,minLoc.y,temp_imgc_row,temp_imgc_col);

        Mat img_show = src_img.clone();
        matchLoc = minLoc;
        //5.根据resultImg中的最大值位置在源图上画出矩形和中心点
        Point center = Point(minLoc.x + temp_imgc.cols / 2, minLoc.y + temp_imgc.rows / 2);
        rectangle(img_show, matchLoc, Point(matchLoc.x + temp_imgc.cols, matchLoc.y + temp_imgc.rows), Scalar(0, 255, 0), 1, 8, 0);

//        imshow("result",img_show);
//        waitKey(0);

        //获取匹配得到区域
        Rect img_ROI = Rect(matchLoc,Point(matchLoc.x + temp_imgc.cols, matchLoc.y + temp_imgc.rows));
        Mat img = src_img.clone();
        Mat ROI_img = img(img_ROI);

//        imshow("ROI",ROI_img);
//        waitKey(0);

        //进行相似度比较
        if(pHash(ROI_img,temp_img) < 20)
        {
            n = pHash(ROI_img,temp_img);
            cout<<"n="<<n<<endl;
            imshow("zhy", img_show);
            waitKey(0);
        }
        
//        //获取模板匹配得到的区域
//        double minVal;
//        double maxVal;
//        Point minLoc;
//        Point maxLoc;
//        minMaxLoc(result_img,&minVal,&maxVal,&minLoc,&maxLoc,Mat());  //找矩阵中最小位置点的坐标
//        //画出ROI区域的矩形框
//        Rect ROI = Rect(minLoc.x,minLoc.y,temp_imgc_row,temp_imgc_col);
//
//        Mat result_img_ROI = result_img(ROI);
//        cout<<i<<endl;
//        imshow("show",result_img_ROI);
//        waitKey(0);
    }
}

效果:

  • 24
    点赞
  • 204
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
OpenCV模板匹配是一基于像素级别的图像匹配方法,它可以在一幅图像寻找与给定模板最相似的部分。模板匹配在计算机视觉领域有广泛的应用,例如目标检测、图像识别等。 OpenCV模板匹配函数为cv::matchTemplate(),它的原型如下: ``` void matchTemplate(InputArray image, InputArray templ, OutputArray result, int method); ``` 其,image为输入图像,templ为模板图像,result为输出的匹配结果,method为匹配方法,包括以下几: - CV_TM_SQDIFF:平方差匹配法 - CV_TM_SQDIFF_NORMED:归一化平方差匹配法 - CV_TM_CCORR:相关匹配法 - CV_TM_CCORR_NORMED:归一化相关匹配法 - CV_TM_CCOEFF:系数匹配法 - CV_TM_CCOEFF_NORMED:归一化系数匹配法 在匹配过程,首先将模板与输入图像的每一个像素位置进行比较,得到一个匹配值。然后,从这些匹配值选择最大值或最小值,即为匹配结果。最终结果是一个灰度图像,其匹配值最大(或最小)的像素位置表示模板在输入图像的位置。 下面是一个简单的示例代码,用于在一副图像寻找一个小图像的位置: ```cpp Mat img = imread("input.jpg"); Mat templ = imread("template.jpg"); Mat result; matchTemplate(img, templ, result, CV_TM_CCOEFF_NORMED); double minVal, maxVal; Point minLoc, maxLoc; minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // 在原图上绘制出匹配的矩形 rectangle(img, maxLoc, Point(maxLoc.x + templ.cols, maxLoc.y + templ.rows), Scalar(0, 0, 255), 2); imshow("Result", img); waitKey(0); ``` 这段代码,首先读入输入图像和模板图像,然后调用matchTemplate()函数进行匹配。最后,使用minMaxLoc()函数找到匹配值最大的像素位置,将其作为矩形的左上角,在原图上绘制出匹配的矩形。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值