MATLAB: I have a matrix A=[1 0 1 1;0 0 1 0; 0 0 1 0; 0 0 0 0] and I wanted to count the neighbor with value one of each pixel with value one. So I need to reach this result: result=[0 0 2 2;0 0 2 0;0 0 1 0;0 0 0 0]. I will be appreciated for your help.

digital image processingimage processingretinal image precessing

I know that function 'conv2' can count the neighbors with value one but it counts the neighbors of all pixel. I need only count the neighbors of pixel which is included 1!

Best Answer

You can extract the info using logical index
u = [1 1 1;1 0 1;1 1 1];
result = conv2(A,u,'same').*(A==1)
HTH