MATLAB: How to find diagonal projection of an handwritten character image (binary matrix)

image processingmatrix algebra character recognitionocr

My project is on handwritten character recoginition using neural network. i want to find horizontal, vertical, left diagonal and right diagonal projection profile for a character's binary image(square matrix with 0 and 1 entries). Horizontal projection means the row wise sum of black pixels for each row.
For horizontal projection i used:
I=imread('c:\4.bmp');
imshow(I);
Img=im2bw(I,0.6);
figure,imshow(Img);
M = IMRESIZE(Img,[16 16]);
figure,imshow(M);
h_proj=zeros;
for i = 1:16
sum=0;
for j=1:16
if M(i,j)==0 %black pixel found
sum=sum+1;
end
end
h_proj(i)=sum;
end
figure,plot(h_proj);
and for Vertical Projection, i used:
I=imread('c:\4.bmp');
imshow(I);
Img=im2bw(I,0.6);
figure,imshow(Img);
M = IMRESIZE(Img,[16 16]);
figure,imshow(M);
v_proj=zeros;
for i = 1:16
sum=0;
for j=1:16
if M(j,i)==0 %black pixel found
%take M(j,i)or find transpose of M and then take M(i,j)
sum=sum+1;
end
end
v_proj(i)=sum;
end
%a
figure,plot(v_proj);
Now how can i find the left and right diagonal projection?
for example in the square matrix M:
M=[1 2 3 4; 5 6 7 8; 9 0 1 2; 3 4 5 6]
% M= 1 2 3 4
% 5 6 7 8
% 9 0 1 2
% 3 4 5 6
i want to find a left diagonal projection vector (LD) with 1,5+2,9+6+3,3+0+7+4,4+1+8,5+2,6 as output i.e
LD=[1 7 18 14 13 7 6]
and also i want to find the right diagonal projection vector (RD)with output as [4,3+8,2+7+2,1+6+1+6,5+0+5,9+4,3] i.e
RD=[4 11 11 14 10 13 3]
Please help me…
Alternative method to find horizontal and vertical projection i found is:
I=imread('c:\4.bmp');
imshow(I);
Img=im2bw(I,0.6);
figure,imshow(Img);
M = IMRESIZE(Img,[16 16]);
figure,imshow(M);
h_projection = sum(~M, 2);
v_projection = sum(~M, 1);
cat_projection = cat(1, h_projection, v_projection(:));
What to do with diagonal direction?

Best Answer

M =[1 2 3 4; 5 6 7 8; 9 0 1 2; 3 4 5 6]
LD = sum(spdiags(M(end:-1:1,:),1-size(M,1):size(M,2)-1))
RD = sum(spdiags(M',1-size(M,2):size(M,1)-1))
variant 2 without spdiags
M =[1 2 3 4; 5 6 7 8; 9 0 1 2; 3 4 5 6]
[m n] = size(M);
Mi = cumsum([1:n*2-1;(m-1)*ones(m-1,n*2-1)]);
LM = triu(true(size(Mi)));
LM = LM&LM(end:-1:1,end:-1:1);
M1 = M(Mi);
LD = sum(M1.*LM);
M2 = M(:,end:-1:1);
M2 = M2(Mi);
RD = sum(M2.*LM);
variant 3 with bsxfun
m = size(M,1);
idx = bsxfun(@plus,[1:m-1, m:m:numel(M)],(0:m-1:(m-1)^2)');
L = triu(true(size(idx)));
L1 = L&L(:,end:-1:1);
idx(~L1) = 1;
LD = sum(M(idx).*L1);
M1 = M(:,end:-1:1);
RD = sum(M1(idx).*L1);
variant 4 with convmtx from Signal Processing Toolbox
[m n]= size(M);
L = logical(convmtx(ones(n,1),m));
idx = ones(size(L));
idx(L) = 1:m*n;
LD = sum((M(idx).*L)');
M1 = M(:,end:-1:1);
RD = sum((M1(idx).*L)');