我正在MATLAB中开发一个模板匹配程序。代码运行良好,并找到最接近的结果。我的第一个问题,在这段代码中,我正在使用函数corr2()
。我想尝试一个使用公式的版本(我试图上传一张图片,但我需要10个声誉)。
我理解公式本身,但我不确定应该使用哪些变量来使用它。例如,我的图片中m
和n
的含义到底在哪里可以得到它们?换句话说,公式作为输入是什么?
第二个问题是,当我运行我现在拥有的代码时,需要很长时间,有什么东西可以改变来加快速度吗?
Original = imread('Red.jpg'); % Read original image
Template = imread('temp.png'); % Read template image
OriDu = im2double(Original); % convert original image
TempDu = im2double(Template); % convert template
OriH = size(Original, 1); %height of the Original image
OriW = size(Original, 2); %width of the Original image
OriD = size(Original, 3); %colour depth
TempH = size(Template, 1); %height of the Template image
TempW = size(Template, 2); %width of the Template image
TempD = size(Template, 3); %colour depth
TempDu = reshape(TempDu, TempH*TempW, 3);
corr = 0; % to check the best correlation found
%% two for loops to go through the original image.
for i = 1:OriH-TempH
for j = 1:OriW-TempW
% take a segment of the original image( same size as the template size)
segment = OriDu(i: (i - 1) + TempH, j: (j - 1) + TempW, :);
segment = reshape(segment, TempH*TempW, 3);
output = corr2(TempDu, segment);
if output > corr
corr = output;
x = i;
y = j;
end
end
end
figure;
subplot(1,2,1), imshow(Template), title('Template');
subplot(1,2,2), imshow(OriDu(x:x+TempH, y:y+TempW, :)),title('Segment of the similar part');