Matlab图像处理学习笔记(三):基于匹配的目标识别

如果要在一幅图像中寻找已知物体,最常用且最简单的方法之一就是匹配。

在目标识别的方法中,匹配属于基于决策理论方法的识别。匹配方法可以是最小距离分类器,相关匹配。本文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


运行结果如下:

Matlab图像处理学习笔记(三):基于匹配的目标识别

模板及图像源文件已上传。

Matlab图像处理学习笔记(三):基于匹配的目标识别

 

你可能感兴趣的:(matlab)