Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting of adjacent cells in a numpy array

Past midnight and maybe someone has an idea how to tackle a problem of mine. I want to count the number of adjacent cells (which means the number of array fields with other values eg. zeroes in the vicinity of array values) as 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 zeroes in such way if the structure of my values vary? I somehow believe to must take use of the binary_dilation function of SciPy, which is able to enlarge the value structure, but simple counting of overlaps can't lead me to the correct sum or does 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]]
like image 293
Curlew Avatar asked Feb 19 '23 01:02

Curlew


1 Answers

Use a convolution to count neighbours:

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 us to count each zero while ignoring the ones.

We convolve with a 3x3 all-ones kernel, which sets each element to the sum of it and its 8 neighbouring values (other kernels are possible, such as the + kernel for only orthogonally adjacent values). With these summed values, we mask off the zeros in the original input (since we don't care about their neighbours), and sum over the whole array.

like image 187
nneonneo Avatar answered Feb 28 '23 04:02

nneonneo