clear all;close all hidden;
load plate_region; %load located plate image
[m n]=size(pic2_gray);
borderm=5;bordern=10;
pic_seg=pic2_gray(borderm:m-borderm-5,bordern:n-bordern);
[m n]=size(pic_seg);
w=zeros(1,n);
for j=1:n
    for i=1:m
        w(j)=w(j)+double(pic_seg(i,j));
    end
end
w=smooth(w,n/10);
step=uint8(n/25);diff=(max(w)-min(w))/10;
k=2;
for i=step+1:n-step
    if w(i)<w(i-1) && w(i)<=w(i+1) && w(i-step)-w(i) > diff && w(i+step)-w(i) > diff
        point(k)=i;
        k=k+1;
    end
end
width=point(3)-point(2);
point(1)=point(2)-width;
point(4)=point(3)+width;
plot(w);
hold on;
plot(double(point(1))*ones(max(w),1),1:max(w),'r-');
plot(double(point(2))*ones(max(w),1),1:max(w),'r-');
plot(double(point(3))*ones(max(w),1),1:max(w),'r-');
plot(double(point(4))*ones(max(w),1),1:max(w),'r-');
hold off;
for k=1:4
    for i=1:m
        pic_seg(i,point(k))=0;
    end
end
imshow(pic_seg);

%number recognizing, 3 numbers
h2wratio=342/256; % height to width ratio of the template
level = graythresh(pic_seg);
bw = im2bw(pic_seg,level);   %convert pic_seg to binary image 
ntp=[4 4 10]; % 3 digits number, first digit 0~3, second 0~3, third 0~9
for k=1:3  %3 numbers
    width=point(k+1)-point(k);
    height=width*h2wratio;
    count_row=zeros(m,1);
    for y=1:m
        for x=point(k):point(k+1)
            count_row(y)=count_row(y)+bw(y,x);
        end
    end
    startp=1;
    while 1
        while count_row(startp)==0 && startp<m
            startp=startp+1;
        end
        if startp==m
            break;
        end
        endp=startp+1;
        while count_row(endp)~=0 && endp<m
            endp=endp+1;
        end
        if endp==m
            break;
        end
        if endp-startp >= 0.8*width
            break;
        end
        startp=endp;
    end
    if startp==m || endp==m
        error('Number recognition failed');
        return;
    end
    num{k}=bw(startp:endp,point(k):point(k+1));
    figure, imshow(num{k});
    [mk nk]=size(num{k});
    for temp=1:ntp(k) %n(k) templates
        filename=sprintf('temp\\%d.bmp',temp-1);
        tp=imread(filename,'bmp');
        level = graythresh(tp);
        tp = im2bw(tp,level);  
        tp=imresize(tp,[mk,nk]);
        compare=xor(num{k},tp);
        difference(temp)=sum(sum(compare)')/sum(sum(tp)');
    end
    [min_diff bestmatch(k)]=min(difference);
    bestmatch(k)=bestmatch(k)-1;
end
result=sprintf('The number is: %d%d%d',bestmatch(1),bestmatch(2),bestmatch(3));
msgbox(result,'Recognition resut');