需要从2d numpy数组中获取输入单元的3x3邻域

wfg*_*geo 3 python arrays numpy

我试图定义一个函数,它将返回输入单元格的3x3邻域.现在我有:

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
Run Code Online (Sandbox Code Playgroud)

(in_forest是输入数组).

当我运行它时,它似乎只返回2x2矩阵,而不是3x3.为什么是这样?在我看来,我正在输入行和列引用,然后切出一个在输入行后面开始一行的正方形,并在它之前结束一行,然后对于列进行相同的处理.

例如,给定一个输入数组:

[ 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 ]
Run Code Online (Sandbox Code Playgroud)

然后使用第2行第3列,我想返回一个矩阵:

[ 02, 03, 04
  07, 08, 09
  12, 13, 14 ]
Run Code Online (Sandbox Code Playgroud)

Jas*_*zun 5

当你说in_forest[in_row-1:in_row+1, in_col-1:in_col+2]你说"给我从广场in_row-1包容in_row+1 独家,从in_col-1包容in_col+2 专属,它切片了,但包括第二个索引.

只需使用in_row-1:in_row+2in_col-1:in_col+2不是切片包括"+1".