[英]Different template matching result in OpenCV and Matlab
我使用帶有兩個示例圖像的OpenCV在MATLAB和C ++中進行模板匹配,但得到了不同的結果。
我的示例圖像是:
作物
溫度
當我使用時:
Mat crop = imread("crop.jpg",0),
temp = imread("temp.jpg",0);
int resultWidth = crop.cols-temp.cols + 1;
int resultHeigth = crop.rows -temp.rows + 1;
Mat result = cvCreateImage(cvSize(resultWidth ,resultHeigth),32,1);
matchTemplate(crop,temp,result ,CV_TM_CCORR_NORMED);
double minval, maxval;
CvPoint minloc, maxloc;
cvMinMaxLoc(&(IplImage)result ,&minval,&maxval,&minloc,&maxloc,NULL);
maxvalue
值為0.93058246374130249
。
在Matlab中:
temp = rgb2gray(imread('temp.jpg'));
crop = rgb2gray(imread('crop.jpg'));
tempMat = normxcorr2(tmep,crop);
[res,index] = max(max(abs(tempMat)));
在這種情況下,答案為0.5753
。
為什么歸一化互相關的最大值不同?
為了使其工作,我使用了以下參考圖像:
並作為模板:
這是要使用的(正確)OpenCV代碼:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
Mat1b templ = imread("path_to_template", IMREAD_GRAYSCALE);
// Compute match
Mat result;
matchTemplate(img, templ, result, TM_CCORR_NORMED);
// Get best match
Point maxLoc;
double maxVal;
minMaxLoc(result, NULL, &maxVal, NULL, &maxLoc);
// Display result
Mat3b res;
cvtColor(img, res, COLOR_GRAY2BGR);
rectangle(res, Rect(maxLoc.x, maxLoc.y, templ.cols, templ.rows), Scalar(0, 255, 0));
imshow("Match", res);
waitKey();
return 0;
}
產生以下結果:
這是要使用的(正確)Matlab代碼:
temp = rgb2gray(imread('path_to_template'));
img = rgb2gray(imread('path_to_image'));
% Perform cross-correlation
c = normxcorr2(temp,img);
% Find peak in cross-correlation
[ypeak, xpeak] = find(c==max(c(:)));
% Account for the padding that normxcorr2 adds
yoffSet = ypeak-size(temp,1);
xoffSet = xpeak-size(temp,2);
% Displat matched area
hFig = figure;
hAx = axes;
imshow(img,'Parent', hAx);
imrect(hAx, [xoffSet, yoffSet, size(temp,2), size(temp,1)]);
產生以下結果:
如您所見,結果是等效的。 匹配結果矩陣中的實際最大數量為:
OpenCV: 0.99999815225601196
Matlab: 0.999988754172261
我們可以認為是平等的。 細微的差異可能是由於內部實施中的細微差異,但並不相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.