wfgeo
wfgeo

Reputation: 3118

Need to grab a 3x3 neighbourhood of an input cell from a 2d numpy array

I am trying to define a function that will return the 3x3 neighbourhood of an input cell. Right now I have:

def queen_neighbourhood(in_forest, in_row, in_col):

    neighbourhood = in_forest[in_row-1:in_row+1, in_col-1:in_col+1]

    return neighbourhood

(in_forest is the input array).

When I run this, it only seems to return a 2x2 matrix, instead of a 3x3. Why is this? It seems to me that I am inputting a row and column reference, and then slicing out a square that starts one row behind the input row, and ends one row ahead of it, and then the same for columns.

So for example, given an input array as such:

[ 01, 02, 03, 04, 05
  06, 07, 08, 09, 10
  11, 12, 13, 14, 15
  16, 17, 18, 19, 20
  21, 22, 23, 24, 25 ]

And then using row 2, col 3, I want to return a matrix as such:

[ 02, 03, 04
  07, 08, 09
  12, 13, 14 ]

Upvotes: 4

Views: 928

Answers (1)

Jashaszun
Jashaszun

Reputation: 9270

When you say in_forest[in_row-1:in_row+1, in_col-1:in_col+2] you are saying "give me a square from in_row-1 inclusive to in_row+1 exclusive, and from in_col-1 inclusive to in_col+2 exclusive. It slices up to, but not including the second index.

Simply use in_row-1:in_row+2 and in_col-1:in_col+2 instead to slice including the "+1"s.

Upvotes: 5

Related Questions