Counting adjacent cells in a numpy array

It's past midnight, and maybe someone has an idea how to solve my problem. I want to count the number of neighboring cells (which means the number of fields in the array with other values, for example, zeros in the neighborhood of the array values) as the sum for each valid value! .

Example:

import numpy, scipy s = ndimage.generate_binary_structure(2,2) # Structure can vary a = numpy.zeros((6,6), dtype=numpy.int) # Example array a[2:4, 2:4] = 1;a[2,4] = 1 # with example value structure print a >[[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 1 1 1 0] [0 0 1 1 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0]] # The value at position [2,4] is surrounded by 6 zeros, while the one at # position [2,2] has 5 zeros in the vicinity if 's' is the assumed binary structure. # Total sum of surrounding zeroes is therefore sum(5+4+6+4+5) == 24 

How can I count the number of zeros this way if the structure of my values โ€‹โ€‹changes? For some reason, I believe that I should use the SciPy binary_dilation function, which can increase the structure of values, but a simple calculation of overlaps cannot lead me to the correct amount or do it?

 print ndimage.binary_dilation(a,s).astype(a.dtype) [[0 0 0 0 0 0] [0 1 1 1 1 1] [0 1 1 1 1 1] [0 1 1 1 1 1] [0 1 1 1 1 0] [0 0 0 0 0 0]] 
+4
source share
2 answers

Use convolution to count neighbors:

 import numpy import scipy.signal a = numpy.zeros((6,6), dtype=numpy.int) # Example array a[2:4, 2:4] = 1;a[2,4] = 1 # with example value structure b = 1-a c = scipy.signal.convolve2d(b, numpy.ones((3,3)), mode='same') print numpy.sum(c * a) 

b = 1-a allows you to count every zero, ignoring them.

We are collapsed with the allxs 3x3 kernel, which sets each element to the sum of it and its 8 neighboring values โ€‹โ€‹(other kernels are possible, such as the kernel + only for orthogonally adjacent values). Using these summed values, we mask the zeros in the original input (since we don't care about our neighbors) and sum over the entire array.

+6
source

I think you already got it. after dilatation, the number 1 is 19, minus 5 of the original shape, you have 14. which is the number of zeros surrounding your figure. Your total of 24 has overlapping.

+1
source

Source: https://habr.com/ru/post/1436500/


All Articles