如果要在一幅圖像中尋找已知物體,最常用且最簡單的方法之一就是匹配。
在目標識別的方法中,匹配屬於基於決策理論方法的識別。匹配方法可以是最小距離分類器,相關匹配。本文code是基於最小距離分類器,基於相關匹配的與此類似。
本文涉及到的知識點如下:
1、目標識別.
2、基於決策理論方法的識別
3、匹配(最小距離分類器、相關匹配)
4、空間相關(相關匹配涉及)
匹配之前,需要先將圖像轉換為灰度圖,函數為rgb2gray,由於matlab對浮點型支持較為完善,我們還需將圖像數據類型更改為double,函數為im2double。之后再將原始圖像補0,這樣才能遍歷圖像的每一點,函數padarray。
決策函數的計算為djx=x'*mj-0.5*mj'*mj;岡薩雷斯的《數字圖像處理》Page561中有寫。之后尋找最佳匹配。
本文算法主要參考岡薩雷斯的《數字圖像處理》。
轉載請注明出處。
已知問題:運行較慢,相關匹配要快一點。
代碼如下:
%function:
% 基於最小距離分類器的模板匹配
% 尋找圖片中與已知模板的匹配區域
%referrence:
% 岡薩雷斯的《數字圖像處理》(第三版)第十二章 目標識別
%date:2015-1-8
%author:chenyanan
%轉載請注明出處:http://blog.csdn.net/u010278305
%清空變量,讀取圖像
clear;close all
template_rgb = imread('images/eye.jpg');
src_rgb = imread('images/head.jpg');
%轉換為灰度圖
template=rgb2gray(template_rgb); template = im2double(template);
src=rgb2gray(src_rgb); src = im2double(src);
figure('name','模板匹配結果'),
subplot(1,2,1),imshow(template_rgb),title('模板'),
%球的模板與原始圖像的大小
tempSize=size(template);
tempHeight=tempSize(1); tempWidth=tempSize(2);
srcSize=size(src);
srcHeight=srcSize(1); srcWidth=srcSize(2);
%在圖片的右側與下側補0
%By default, paddarray adds padding before the first element and after the last element along the specified dimension.
srcExpand=padarray(src,[tempHeight-1 tempWidth-1],'post');
%初始化一個距離數組 tmp:mj template:x
%參見《數字圖像處理》 Page561
distance=zeros(srcSize);
for height=1:srcHeight
for width= 1:srcWidth
tmp=srcExpand(height:(height+tempHeight-1),width:(width+tempWidth-1));
%diff= template-tmp;
%distance(height,width)=sum(sum(diff.^2));
%計算決策函數
distance(height,width)=sum(sum(template'*tmp-0.5.*(tmp'*tmp)));
end
end
%尋找決策函數最大時的索引
maxDis=max(max(distance));
[x, y]=find(distance==maxDis);
%繪制匹配結果
subplot(1,2,2),imshow(src_rgb);title('匹配結果'),hold on
rectangle('Position',[x y tempWidth tempHeight],'LineWidth',2,'LineStyle','--','EdgeColor','r'),
hold off
運行結果如下:

模板及圖像源文件已上傳。


