Counting number of same neighbourhood pixels between two matrices.

Asked by Stewart Tan

Stewart Tan (view profile)

on 10 Sep 2019
Latest activity Commented on by Shunichi Kusano

Shunichi Kusano (view profile)

on 10 Sep 2019
Accepted Answer by Shunichi Kusano

Shunichi Kusano (view profile)

So i have two made up matrices, which represents an image block.
p1 = [4 7 1 2;
4 5 3 1;
8 9 1 10;
8 19 2 1];
p2 = [4 7 1 2;
4 5 3 2;
5 1 0 11;
8 19 2 0]
and what i want to do is to count how many neighbourhood pixels are similar between both matrices above. To do so, i first locate the centre pixel in each matrices:
centre_pix = floor(([4 4]+1)/2)
p1_centre = p1(2,2) %2,2 is the output of centre pix
p2_centre = p2(2,2)
Hence the number 5 in row 2, column 2 in each matrix is the centre pixel.
What I'm trying to do now is to count the number of neighbourhood pixel of the centre pixel that are similar between the two matrices.
Which would be 4,7,1,4,3 therefore the count is 5.

Products

Answer by Shunichi Kusano

Shunichi Kusano (view profile)

on 10 Sep 2019
Edited by Shunichi Kusano

Shunichi Kusano (view profile)

on 10 Sep 2019

Hi Tan,
If "similar" means "exactly the same" or "the difference is zero", it is not difficult to implement. What the following codes do is to take the difference between the two matrices, then to count the number of neighbourhood pixels whose value is zero.
dif_p = double(p1) - double(p2);
indSame = dif_p == 0; %
fun = @(x) nnz(x) - uint8(x(2,2));
result = nlfilter(indSame, [3 3], fun)
hope this helps.

Answer by Bruno Luong

Bruno Luong (view profile)

on 10 Sep 2019
Edited by Bruno Luong

Bruno Luong (view profile)

on 10 Sep 2019

This command counts the number of 3x3 neigbouring pixels that exactly match
conv2(p1==p2,ones(3),'same')

Shunichi Kusano

Shunichi Kusano (view profile)

on 10 Sep 2019
very simple! I like this better!