MATLAB: How to count the ones on the edges, not the whole window,

edge counting

%Count how many 1's are in each 5×5 window.
kernel = ones(5,5);
% Note: must cast your binary image to dingle or double.
countImage = conv2(single(originalImage), kernel, 'same');
I just want get the 1's on the edge of window which count =4,ignore the middle part how to do it?
example:
1 0 1 0 0
0 1 0 1 1
1 0 1 1 0
0 1 1 1 0
0 0 0 0 0

Best Answer

Try this:
m = [...
1 0 1 0 0
0 1 0 1 1
1 0 1 1 0
0 1 1 1 0
0 0 0 0 0]
% Zero out non-edge pixels:
m(2:end-1, 2:end-1) = 0
% Count 1's:
edgeCount = nnz(m)