1 Mat imgMat = imread("fish.png", IMREAD_GRAYSCALE); // 原图 2 Mat m1 = imread("fish_single.png", IMREAD_GRAYSCALE); // 模板图 3 Mat m2; 4 Mat m3; 5 Mat canny_out; 6 imshow("m1", m1); 7 8 9 matchTemplate(imgMat, m1, m2, TM_CCOEFF_NORMED ); 10 11 imshow("m2", m2); 12 double minVal; 13 double maxVal; 14 Point minLoc; 15 Point maxLoc; 16 minMaxLoc(m2, &minVal, &maxVal, &minLoc, &maxLoc); // 提取极值 17 imgMat.copyTo(m3); 18 rectangle(m3, Point(maxLoc), Point(maxLoc.x + m1.cols, maxLoc.y + m1.rows), 19 Scalar(0, 0, 255), 3); // 绘制得分最高结果的矩形边界 20 imshow("m3", m3); 21 22 // 给所有阈值大于0.8的结果绘制矩形 23 float threshold = 0.8; 24 for(int row = 0; row < m2.rows; row++) 25 { 26 for (int col = 0;col < m2.cols; col++ ) 27 { 28 // Mat.at<float>(i, j) 返回对应float值 29 float value = m2.at<float>(row, col); 30 if(value > threshold) 31 rectangle(imgMat, Point(col, row), Point(col + m1.cols, row + m1.rows), 32 Scalar(0, 0, 255)); 33 } 34 } 35 imshow("imgMat", imgMat);
原图
模板
m1
m2
m3
imgMat