0

I have a 3-dimensional numpy array, where the first two dimensions form a grid, and the third dimension (let's call it cell) is a vector of attributes. Here is an example for array x (a 2x3 grid with 4 attributes in each cell):

[[[1 2 3 4][5 6 7 8][9 8 7 6]]
 [[9 8 7 6][5 4 3 2][1 2 3 4]]]

for which I want to get the median of the 8 neighbors of each cell in array x, e.g. for x[i,j,:] it would be the median of all cells with an index combined of i-1, i+1, j-1, j+1. It is clear how to do that, but for the borders the index would get out of range (e.g. if i=0, a general solution where I take x[i-1,j,:] into the calculation wouldn't work).

Now the simple solution would be (simple in the sense of not thought through) to separately treat the 4 corners (e.g. where i=j=0), borders (e.g. where i=0 and j!=0) and the default case for cells in the middle with if statements, but I would hope that there is a more elegant solution for this problem. I thought to extend the n*m grid to a (n+2)*(m+2) grid and fill the border cells on all sides with 0 values, but that would distort the median computation.

I hope I was able to kind of clarify the problem. Thanks in advance for any suggestions for a more elegant way to solve this.

Michael
  • 8,362
  • 6
  • 61
  • 88
  • 1
    Scipy medfilt - https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.medfilt.html? – Divakar Apr 29 '17 at 17:42
  • I don't understand what medians you are looking for. Is it one median per "attribute" so that each value is the median of the eight neighbors, or is it one median per "cell", so that each value is the median of eight neighbors times the attribute per cell? – JohanL Apr 29 '17 at 18:49
  • Have you tried [this](http://stackoverflow.com/questions/21204206/faster-way-to-simultaneously-iterate-over-rolling-window-of-two-or-more-numpy-ar)? Or even better, [this](http://stackoverflow.com/questions/39202636/numpy-rolling-window-over-2d-array-as-a-1d-array-with-nested-array-as-data-valu)? They seem to contain exactly the answers you're seeing. – Gene Burinsky Apr 29 '17 at 20:53

0 Answers0