
在OpenCV中使用C++进行模板匹配时,如果你想利用边缘特征来提高匹配的鲁棒性,可以结合边缘检测算法(如Canny)来提取图像和模板的边缘信息,然后在这些边缘图像上进行模板匹配
            
            
              python
              
              
            
          
          #include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main() {
    // 加载图像和模板
    Mat img = imread("image.jpg", IMREAD_GRAYSCALE);
    Mat templ = imread("template.jpg", IMREAD_GRAYSCALE);
    if (img.empty() || templ.empty()) {
        cout << "Could not open or find the image or template!" << endl;
        return -1;
    }
    // 使用Canny边缘检测提取图像和模板的边缘
    Mat edges_img, edges_templ;
    Canny(img, edges_img, 50, 150);
    Canny(templ, edges_templ, 50, 150);
    // 创建结果矩阵
    Mat result;
    int result_cols = img.cols - templ.cols + 1;
    int result_rows = img.rows - templ.rows + 1;
    result.create(result_rows, result_cols, CV_32FC1);
    // 进行模板匹配
    matchTemplate(edges_img, edges_templ, result, TM_CCOEFF_NORMED);
    // 找到最佳匹配位置
    double minVal, maxVal;
    Point minLoc, maxLoc;
    minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
    // 在原始图像上绘制矩形框标记匹配区域
    Mat img_display;
    cvtColor(img, img_display, COLOR_GRAY2BGR);
    rectangle(img_display, maxLoc, Point(maxLoc.x + templ.cols, maxLoc.y + templ.rows), Scalar(0, 255, 0), 2);
    // 显示结果
    imshow("Source Image", img_display);
    imshow("Template", templ);
    imshow("Edges Image", edges_img);
    imshow("Edges Template", edges_templ);
    imshow("Result", result);
    waitKey(0);
    return 0;
}测试效果





