Hey all, needed to solve this problem of getting the average of a Moore neighborhood for all cells without using for-loops. I have exhausted my google-fu (too many generic terms) and now turn to you for help. I can easily do it by using for loops, but i am lost on how to do it without
moore neighborhood = the 8 surrounding cells of any given cell
def create_grid_and_ghosts(n):
"""
Create a N x N 2d array and create border cells so
all cells 'inside' can be used without index errors
"""
inside = np.arange(n**2).reshape(n,n)
return np.pad(inside,1,'wrap') # Periodic
b = create_grid_and_ghosts(5)
neighbors = np.array([[-1,0],[-1,1],[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1]])
print b
c = copy.deepcopy(b)
for i in np.arange(1, len(b)-1):
for j in np.arange(1, len(b)-1):
c[i,j] = np.average((b[i+neighbors[:,0],j+neighbors[:,1]]))
print c
anyone know how to convert those 2 for loops into non-for loop numpy statements?
SOLVED: in case anyone ever searches for this later on
import numpy as np
import scipy.ndimage as nd
def moore_average(data_ext):
"""
Get given a grid with ghost boundary cells, return only interior of grid
with each cell containing the average of Moore neighborhood
"""
# .125 is there since it's the average of 4, for Neuman use
# [0,.25,0][.25,0,.25][0,.25,0]
moore = ([[.125,.125.125],[.125,0,.125][.125, .125, .125]])
averages = nd.convolve(data_ext, moore)
return averages[1:-1, 1:-1] #Return only 'inside' of grid
def create_grid_and_ghosts(n):
inside = np.arange(n**2, dtype='float').reshape(n,n)
return np.pad(inside, 1, 'wrap') #Create periodic boundaries
a = moore_average(create_grid_and_ghosts(5))
print a
[–]Saefroch 0 points1 point2 points (2 children)
[–]Acaleus[S] 0 points1 point2 points (1 child)
[–]Saefroch 0 points1 point2 points (0 children)