手写的字符模板匹配在Matlab中

时间:2013-05-15 20:40:50

标签: matlab image-processing template-matching

使用手写数据输入的模板匹配,但在Matlab中遇到一些非常新的问题。我想匹配这个模板
enter image description here
用这一个..
enter image description here

到目前为止,我做的是:

function result=test(image1,image2)
%*********************************************************

    image1=rgb2gray(image1);
    image2=rgb2gray(image2);

% check which one is target and which one is template using their size

if size(image1)>size(image2)
    Target=image1;
    Template=image2;
else
    Target=image2;
    Template=image1;
end

% find both images sizes
[r1,c1]=size(Target);
[r2,c2]=size(Template);
% mean of the template
image22=Template-mean(mean(Template));

%corrolate both images
M=[];
for i=1:(r1-r2+1)
    for j=1:(c1-c2+1)
        Nimage=Target(i:i+r2-1,j:j+c2-1);
        Nimage=Nimage-mean(mean(Nimage));  % mean of image part under mask
        corr=sum(sum(Nimage.*image22));
        %warning off
        M(i,j)=corr/sqrt(sum(sum(Nimage.^2)));
    end 
end
% plot box on the target image
result=plotbox(Target,Template,M);

对于情节框..

function result=plotbox(Target,Template,M)

%*********************************************************
[r1,c1]=size(Target);
[r2,c2]=size(Template);

[r,c]=max(M);
[r3,c3]=max(max(M));

i=c(c3);
j=c3;
result=Target;
for x=i:i+r2-1
   for y=j
       result(x,y)=255;
   end
end
for x=i:i+r2-1
   for y=j+c2-1
       result(x,y)=255;
   end
end
for x=i
   for y=j:j+c2-1
       result(x,y)=255;
   end
end
for x=i+r2-1
   for y=j:j+c2-1
       result(x,y)=255;
   end
end

为了测试我使用..

% read Template image
im1=imread('C:\Users\Shuvro\Desktop\New folder\1.jpg');
% read Traget Image
im2=imread('C:\Users\Shuvro\Desktop\New folder\2.jpg');
% apply templete matching using power of the image
result1=test(im1,im2);
figure,
subplot(2,2,1),imshow(im1);title('Template');
subplot(2,2,2),imshow(im2);title('Target');
subplot(2,2,3),imshow(result1);title('Matching Result using tmp');

但是这段代码通常无法在源图像中识别出该模板,也无法理解其中存在的错误。任何人都可以提供帮助?
基本上当我向系统输入2个图像时,我想使它们的高度相似。然后我想测量模板图像宽度然后我想根据该宽度扫描源图像并检查像素值。当模板的那些像素值时将与70%以上的源图像匹配然后我将给出找到它的结果,否则找不到。
这就是我想要做到这一点。非常感谢任何人可以通过编辑或提供建议来帮助完成上述代码。

1 个答案:

答案 0 :(得分:0)

首先,我想警告你size(image1)>size(image2)是一个矢量比较,通常你不会这样做。 (可能是allany)。

话虽如此:

在这种特定情况下,找出代码无法满足您预期效果的唯一方法是加载应该匹配但不匹配的输入。然后逐行逐步执行代码,直到看到任何意外行为。


当然你也可以尝试为matlab搜索模式匹配函数,应该有一些你可以在google上找到,或者甚至可以在stackoverflow上找到。