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

在目标识别的方法中,匹配属于基于决策理论方法的识别。匹配方法可以是最小距离分类器,相关匹配。本文code是基于最小距离分类器,基于相关匹配的与此类似。

本文涉及到的知识点如下:

1、目标识别.

2、基于决策理论方法的识别

3、匹配(最小距离分类器、相关匹配)

4、空间相关(相关匹配涉及)

匹配之前,需要先将图像转换为灰度图,函数为rgb2gray,由于matlab对浮点型支持较为完善,我们还需将图像数据类型更改为double,函数为im2double。之后再将原始图像补0,这样才能遍历图像的每一点,函数padarray。

决策函数的计算为djx=x'*mj-0.5*mj'*mj;冈萨雷斯的《数字图像处理》Page561中有写。之后寻找最佳匹配。

本文算法主要参考冈萨雷斯的《数字图像处理》。

转载请注明出处。

已知问题:运行较慢,相关匹配要快一点。

代码如下:

1. %function:
2. % 基于最小距离分类器的模板匹配
3. % 寻找图片中与已知模板的匹配区域
4. %referrence:
5. % 冈萨雷斯的《数字图像处理》(第三版)第十二章 目标识别
6. %date:2015-1-8
7. %author:chenyanan
8. %转载请注明出处:http://blog.csdn.net/u010278305
9.
10. %清空变量,读取图像
11. clear;close all
12. template_rgb = imread('images/eye.jpg');
13. src_rgb = imread('images/head.jpg');
14.
15. %转换为灰度图
16. template=rgb2gray(template_rgb); template = im2double(template);
17. src=rgb2gray(src_rgb); src = im2double(src);
18.
19. figure('name','模板匹配结果'),
20. subplot(1,2,1),imshow(template_rgb),title('模板'),
21.
22. %球的模板与原始图像的大小
23. tempSize=size(template);
24. tempHeight=tempSize(1); tempWidth=tempSize(2);
25. srcSize=size(src);
26. srcHeight=srcSize(1); srcWidth=srcSize(2);
27.
28. %在图片的右侧与下侧补0
29. %By default, paddarray adds padding before the first element and after the last element along the specified dimension.
30. srcExpand=padarray(src,[tempHeight-1 tempWidth-1],'post');
31.
32. %初始化一个距离数组 tmp:mj template:x
33. %参见《数字图像处理》 Page561
34. distance=zeros(srcSize);
35. for height=1:srcHeight
36. for width= 1:srcWidth
37. tmp=srcExpand(height:(height+tempHeight-1),width:(width+tempWidth-1));
38. %diff= template-tmp;
39. %distance(height,width)=sum(sum(diff.^2));
40. %计算决策函数
41. distance(height,width)=sum(sum(template'*tmp-0.5.*(tmp'*tmp)));
42. end
43. end
44.
45. %寻找决策函数最大时的索引
46. maxDis=max(max(distance));
47. [x, y]=find(distance==maxDis);
48.
49. %绘制匹配结果
50. subplot(1,2,2),imshow(src_rgb);title('匹配结果'),hold on
51. rectangle('Position',[x y tempWidth tempHeight],'LineWidth',2,'LineStyle','--','EdgeColor','r'),
52. hold off

运行结果如下:

基于匹配的目标识别_2d

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

基于匹配的目标识别_相关匹配_02

基于匹配的目标识别_目标识别_03