1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv;
#define WINDOW_NAME1 "Original" #define WINDOW_NAME2 "Match"
Mat g_srcImage; Mat g_templateImage; Mat g_resultImage; int g_nMatchMethod; int g_nMaxTrackbarNum = 5;
void on_Matching(int, void *); static void ShowHelpText();
int main() { ShowHelpText();
g_srcImage = imread("1.jpg", 1); g_templateImage = imread("2.jpg", 1);
namedWindow(WINDOW_NAME1, WINDOW_AUTOSIZE); namedWindow(WINDOW_NAME2, WINDOW_AUTOSIZE);
createTrackbar("Method", WINDOW_NAME1, &g_nMatchMethod, g_nMaxTrackbarNum, on_Matching); on_Matching(0, 0);
waitKey(0); return 0; }
void on_Matching(int, void *) { Mat srcImage; g_srcImage.copyTo(srcImage);
int resultImage_rows = g_srcImage.rows - g_templateImage.rows + 1; int resultImage_cols = g_srcImage.cols - g_templateImage.cols + 1; g_resultImage.create(resultImage_rows, resultImage_cols, CV_32FC1);
matchTemplate(g_srcImage, g_templateImage, g_resultImage, g_nMatchMethod); normalize(g_resultImage, g_resultImage, 0, 1, NORM_MINMAX, -1, Mat());
double minValue; double maxValue; Point minLocation; Point maxLocation; Point matchLocation; minMaxLoc(g_resultImage, &minValue, &maxValue, &minLocation, &maxLocation, Mat());
if (g_nMatchMethod == TM_SQDIFF || g_nMatchMethod == TM_SQDIFF_NORMED) { matchLocation = minLocation; } else { matchLocation = maxLocation; }
rectangle(srcImage, matchLocation, Point(matchLocation.x + g_templateImage.cols, matchLocation.y + g_templateImage.rows), Scalar(0, 0, 255), 2, 8, 0); rectangle(g_resultImage, matchLocation, Point(matchLocation.x + g_templateImage.cols, matchLocation.y + g_templateImage.rows), Scalar(0, 0, 255), 2, 8, 0);
imshow(WINDOW_NAME1, srcImage); imshow(WINDOW_NAME2, g_resultImage); }
static void ShowHelpText() { printf("\n\n\t\t\t非常感谢购买《OpenCV3编程入门》一书!\n"); printf("\n\n\t\t\t此为本书OpenCV3版的第84个配套示例程序\n"); printf("\n\n\t\t\t 当前使用的OpenCV版本为:" CV_VERSION); printf("\n\n ----------------------------------------------------------------------------\n"); printf("\t欢迎来到【模板匹配】示例程序~\n"); printf("\n\n\t请调整滑动条观察图像效果\n\n"); printf("\n\t滑动条对应的方法数值说明: \n\n" "\t\t方法【0】- 平方差匹配法(SQDIFF)\n" "\t\t方法【1】- 归一化平方差匹配法(SQDIFF NORMED)\n" "\t\t方法【2】- 相关匹配法(TM CCORR)\n" "\t\t方法【3】- 归一化相关匹配法(TM CCORR NORMED)\n" "\t\t方法【4】- 相关系数匹配法(TM COEFF)\n" "\t\t方法【5】- 归一化相关系数匹配法(TM COEFF NORMED)\n"); }
|