Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of 8 neighbors in 2d array

I need to find the sum of all the neighboring elements of a cell, say getsumofneighbors(matrix, i, j):

'M*N matrix'
[[0 1 0]
 [2 0 1]
 [0 4 0]
 [0 0 0]]

sum of nearest elements of cell [0][0] is 3

at [1][0] is 5

and at [1][1] is 8

Is there a python lib to find the sum of all the elements next to the given cell?

like image 326
Sanjeeth Nayak Avatar asked May 01 '16 08:05

Sanjeeth Nayak


2 Answers

If you don't mind the dependency on scipy, you can use scipy.ndimage.convolve, as follows:

In [475]: a
Out[475]: 
array([[0, 1, 0],
       [2, 0, 1],
       [0, 4, 0],
       [0, 0, 0]])

In [476]: kernel
Out[476]: 
array([[1, 1, 1],
       [1, 0, 1],
       [1, 1, 1]])

In [477]: from scipy.ndimage import convolve

In [478]: c = convolve(a, kernel, mode='constant')

In [479]: c
Out[479]: 
array([[3, 3, 2],
       [5, 8, 5],
       [6, 3, 5],
       [4, 4, 4]])
like image 152
Warren Weckesser Avatar answered Nov 18 '22 19:11

Warren Weckesser


You can use slicing and np.sum to calculate the sum of a particular region:

def getsumofneighbors(matrix, i, j):
    region = matrix[max(0, i-1) : i+2,
                    max(0, j-1) : j+2]
    return np.sum(region) - matrix[i, j] # Sum the region and subtract center

Notice that the max is there because negative starting indexes trigger different slicing.

like image 5
MSeifert Avatar answered Nov 18 '22 19:11

MSeifert