Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum pattern across array

I'm having trouble finding the proper way to do something I think should be trivial using numpy. I have an array (1000x1000) and I want to calculate the sum of a specific pattern across the array.

For example:

If I have this array and want to calculate the sum of a two-cell-right diagonal I would expect [7,12,11,8,12,6,11,7] (a total of 8 sums).

enter image description here

How can I do this?

like image 282
John Avatar asked Sep 09 '18 17:09

John


1 Answers

This operation is called a 2-dimensional convolution:

>>> import numpy as np
>>> from scipy.signal import convolve2d
>>> kernel = np.eye(2, dtype=int)
>>> a = np.array([[5,3,7,1,2],[3,2,9,4,7],[8,9,4,2,3]])
>>> convolve2d(a, kernel, mode='valid')
array([[ 7, 12, 11,  8],
       [12,  6, 11,  7]])

Should you want to generalize it to arbitrary dimensions, there is also scipy.ndimage.convolve available. It will also work for this 2d case, but does not offer the mode='valid' convenience.

like image 178
wim Avatar answered Oct 21 '22 08:10

wim