本文共 1810 字,大约阅读时间需要 6 分钟。
#include#include #include using namespace cv;using namespace std;Mat src, temp, dst;int max_track = 5;int match_method = CV_TM_SQDIFF;char *output = "output image";void Match_Demo(int, void*);int main() { // 加载图像 temp = imread("E:\\vs2015\\opencvstudy\\26templates.png"); src = imread("E:\\vs2015\\opencvstudy\\26test.png"); if (!src.data) { cout << "could not load image!" << endl; return -1; } imshow("src", src); imshow("template", temp); const char* track_title = "Match Algo Type"; createTrackbar("Size", output, &match_method, max_track, Match_Demo); Match_Demo(0, 0); waitKey(0); return 0;}void Match_Demo(int, void*) { int width = src.cols - temp.cols + 1; int height = src.rows - temp.rows + 1; cout << "width" << endl; cout << "height" << endl; Mat result(width, height, CV_32FC1); matchTemplate(src, temp, result, match_method, Mat()); normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat()); Point minLoc; Point maxLoc; src.copyTo(dst); double min, max; minMaxLoc(result, &min, &max, &minLoc, &maxLoc, Mat()); Point temLoc; if (match_method == CV_TM_SQDIFF && match_method == CV_TM_SQDIFF_NORMED) { temLoc = minLoc; } else { temLoc = maxLoc; } // 绘制矩形 rectangle(dst, Rect(temLoc.x, temLoc.y, temp.cols, temp.rows), Scalar(0, 0, 255), 2, 8); rectangle(result, Rect(temLoc.x, temLoc.y, temp.cols, temp.rows), Scalar(0, 0, 255), 2, 8); imshow("result", result); imshow("dst", dst); return;}
这段代码实现了一个基本的图像匹配和特征追踪算法。首先,加载了两张图像作为源图像和模板图像。然后,通过OpenCV的matchTemplate函数进行图像匹配,并使用normalize函数对匹配结果进行归一化处理。接着,调用minMaxLoc函数获取匹配结果的最小值和最大值,并确定匹配区域的位置。根据匹配方法的不同,确定最终的匹配点位置,最后绘制匹配区域并显示结果。
该代码可以在OpenCV环境下编译和运行,用户可以通过调节trackbar来选择不同的匹配算法,观察结果的变化。
转载地址:http://smsfk.baihongyu.com/