Matlab圖像處理學習筆記(三):基於匹配的目標識別

若是要在一幅圖像中尋找已知物體,最經常使用且最簡單的方法之一就是匹配。算法

在目標識別的方法中,匹配屬於基於決策理論方法的識別。匹配方法能夠是最小距離分類器,相關匹配。本文code是基於最小距離分類器,基於相關匹配的與此相似。數組

本文涉及到的知識點以下:函數

一、目標識別.
post

二、基於決策理論方法的識別.net

三、匹配(最小距離分類器、相關匹配)code

四、空間相關(相關匹配涉及)blog

匹配以前,須要先將圖像轉換爲灰度圖,函數爲rgb2gray,因爲matlab對浮點型支持較爲完善,咱們還需將圖像數據類型更改成double,函數爲im2double。以後再將原始圖像補0,這樣才能遍歷圖像的每一點,函數padarray。索引

決策函數的計算爲djx=x'*mj-0.5*mj'*mj;岡薩雷斯的《數字圖像處理》Page561中有寫。以後尋找最佳匹配。圖片

本文算法主要參考岡薩雷斯的《數字圖像處理》。ci

轉載請註明出處。

已知問題:運行較慢,相關匹配要快一點。

代碼以下:

%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


運行結果以下:


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

相關文章
相關標籤/搜索