Matlab图像处理学习笔记---基于匹配的目标识别

匹配是在一幅图像中寻找已知物体最有效且简单的方法。
在目标识别的方法中,匹配属于基于决策理论方法的识别,匹配方法可以是最小距离分类器,相关匹配。
涉及的主要知识点包括:
1.目标识别
2.基于决策理论方法的识别
3.匹配(最小距离分类器、相关匹配)
4.空间相关(相关匹配涉及)
步骤:
匹配之前,需要先将图像转化为灰度图,函数为rgb2gray,由于matlab对浮点型支持比较完善,因此还需要将图像数据类型转化为double,用到的函数为im2double,之后再将原始图像补0,这样才能遍历图像中的每一个点,函数为padarray。
决策函数的计算为:djx=x’mj-0.5mj’*mj;之后寻找最佳匹配。
该方法运行较慢,相关匹配要快一些。
代码如下:

%function:
%       基于最小距离分类器的模板匹配
%       寻找图片中与已知模板的匹配区域
%referrence:
%      冈萨雷斯的《数字图像处理》(第三版)第十二章 目标识别

%清空变量,读取图像
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.
%原始图像补0
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图像处理学习笔记---基于匹配的目标识别_第1张图片
测试图像:
在这里插入图片描述
Matlab图像处理学习笔记---基于匹配的目标识别_第2张图片

你可能感兴趣的:(Matlab图像处理学习笔记---基于匹配的目标识别)