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

标签 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

(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 ]

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

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

最佳答案

当你说 in_forest[in_row-1:in_row+1, in_col-1:in_col+2] 时,你是在说“给我一个来自 in_row-1 的正方形包含到 in_row+1 exclusive,从 in_col-1 包含到 in_col+2 exclusive。它切片到,但包括第二个索引。

只需使用 in_row-1:in_row+2in_col-1:in_col+2 来切片,包括“+1”。

关于python - 需要从 2d numpy 数组中获取输入单元格的 3x3 邻域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947537/

相关文章:

python - 避免 OSError : [Errno 22] Invalid argument when read()ing large file

C 程序的函数似乎总是返回 true,但我不明白为什么

Python 在滚动窗口中对多个数据数组进行操作

python - 无替换样本的 np.random.choice 与 np.random.shuffle 的比较

python - 使用不同长度的数组列表索引一维数组

python - 计算 1d 内单个粒子的均方位移

python - 使用Python Flask在我的html中显示.txt文件

c# - 内联组合数组 - LINQ

python - 比较 numpy 数组中的多个值

python - 赋予灰度图像颜色