Getting number of neighbours for a 3d numpy arrays

Heli hemla21 at gmail.com
Tue Jul 12 05:18:21 EDT 2016


Hi, 

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)

n2 with inidices [i+1,j,k] if i<a.
n3 with indices [i,j-1,k] if j>0
n4 with inidces [i,j+1,k] if j<b. 
n5 with inidces [i,j,k-1] if k>0
n6 with indices [i,j,k+1] if k<c. 

I am now looping over whole numpy array. 
for i in range(x_size):
            for j in range(y_size):
                for k in range(z_size):
                    
                    n_neigh=0
                    
                    if i>0 :
                        n1=myarray[i-1,j,k]
                        if n1== True:
                            n_neigh+=1
                            
                    if i<248:
                        n2=grains_3d[i+1,j,k]
                        if n2== True:
                            n_neigh_grains+=1
                            
                    if j>0:
                        n3=myarray[i,j-1,k]
                        if n3== True:
                            n_neigh+=1
                            
                    if j<1247:
                        n4=myarray[i,j+1,k]
                        if n4== True:
                            n_neigh+=1

                    if k>0 :
                        n5=myarray[i,j,k-1]
                        if n5== True:
                            n_neigh+=1

                    if k<169:
                        n6=myarray[i,j,k+1]
                        if n6== True:
                            n_neigh+=1

Is there anyway I can get an array containg all n1 neighbour, a second array containing all n2 neighbours and so on and then add n1 to n6 arrays element-wise to get all neighbours that meet certain conditions for a cell. 

Thanks in Advance for your help, 



More information about the Python-list mailing list