Getting number of neighbours for a 3d numpy arrays

Peter Otten __peter__ at web.de
Tue Jul 12 08:47:40 EDT 2016


Heli wrote:

> I have a 3d numpy array containing true/false values for each i,j,k. The
> size of the array is a*b*c.
> 
> for each cell with indices i,j,k; I will need to check all its neighbours
> and calculate the number of neighbour cells with true values.
> 
> A cell with index i,j,k has the following neighbours :
> 
> n1 with indices [i-1,j,k] if i>0 ; cell with i=0 does not have any n1
> neighbour. (left neighbour)

I'm not a numpy expert, so the following may be less elegant than and not as 
efficient as possible; it may also be outright wrong ;)

With that caveat:

$ cat neighbours.py   
import numpy
from collections import deque


def print_int(a):
    print(numpy.array(a, dtype=int))

# generate sample data

numpy.random.seed(42)

SHAPE = (3, 3, 3)
DIMENSIONS = len(SHAPE)  # dimensions

a = numpy.random.random(SHAPE) < .5
b = numpy.zeros(SHAPE, dtype=int)

print("input data:")
print_int(a)
print("")


# actual calculation
full = slice(None, None, None)
left = slice(None, -1, None)
right = slice(1, None, None)

ileft = deque([left] + [full] * (DIMENSIONS-1))
iright = deque([right] + [full] * (DIMENSIONS-1))
for i in range(DIMENSIONS):
    b[ileft] += a[iright]
    b[iright] += a[ileft]
    ileft.rotate()
    iright.rotate()

print("number of neighbours:")
print(b)
$ python neighbours.py
input data:
[[[1 0 0]
  [0 1 1]
  [1 0 0]]

 [[0 1 0]
  [0 1 1]
  [1 1 0]]

 [[1 1 0]
  [1 1 1]
  [1 0 1]]]

number of neighbours:
[[[0 3 1]
  [3 2 2]
  [1 3 1]]

 [[3 2 2]
  [3 5 3]
  [3 2 3]]

 [[2 3 2]
  [3 4 3]
  [2 4 1]]]





More information about the Python-list mailing list