python - numpy 中二维数组上的矢量化移动窗口

标签 python numpy vectorization

我正在对二维数组中大小不变的移动窗口应用操作。是否有一种有效的类似矢量化的操作,我可以实现它而无需在 Python 中循环?我当前的结构看起来像这样

 for i in range(1,xmax-1):
     for j in range(1,ymax-1):
        out[i][j] = f(in[i][j],in[i+1][j],in[i-1][j],in[i][j+1],in[i][j-1],...)

eat 在这个问题中留下的评论暗示了将此操作向量化的可能性,但没有进一步的细节 vectorized indexing/slicing in numpy/scipy?

最佳答案

您可以按照说明使用滚动窗口技术 here , herehere , 但对于二维数组。

NumPy 二维滚动窗口源码:

# Rolling window for 2D arrays in NumPy
import numpy as np

def rolling_window(a, shape):  # rolling window for 2D array
    s = (a.shape[0] - shape[0] + 1,) + (a.shape[1] - shape[1] + 1,) + shape
    strides = a.strides + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=s, strides=strides)

a = np.array([[0,  1,  2,  3,  4,  5],
              [6,  7,  8,  9, 10,  11],
              [12, 13, 14, 15, 7,   8],
              [18, 19, 20, 21, 13, 14],
              [24, 25, 26, 27, 19, 20],
              [30, 31, 32, 33, 34, 35]], dtype=np.int)
b = np.arange(36, dtype=np.float).reshape(6,6)
present = np.array([[7,8],[13,14],[19,20]], dtype=np.int)
absent  = np.array([[7,8],[42,14],[19,20]], dtype=np.int)

found = np.all(np.all(rolling_window(a, present.shape) == present, axis=2), axis=2)
print(np.transpose(found.nonzero()))
found = np.all(np.all(rolling_window(b, present.shape) == present, axis=2), axis=2)
print(np.transpose(found.nonzero()))
found = np.all(np.all(rolling_window(a, absent.shape) == absent, axis=2), axis=2)
print(np.transpose(found.nonzero()))

数组present 在数组a 中出现了两次[1,1] 和[2,4]。

我的 CoLab 笔记本中有更多示例 "Rolling window on NumPy arrays without for loops" .

关于python - numpy 中二维数组上的矢量化移动窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174467/

相关文章:

python - OpenCV 线段检测器

python - 如何从 numpy 数组中快速获取特定索引?

gcc - 使用 GCC 进行循环版本控制

python : Cannot retrieve shape of numpy matrix in dict

x86 - 如何用SSE3实现符号功能?

fortran - 英特尔 Fortran 中结构内的数据对齐

python - 读取文件函数仅在应用 try/except 后返回文件中的第一行,但程序在没有它的情况下按预期工作

python - 使用 basemap 和 Pandas 创建Choropleth map

python - 有没有一种有效的方法可以将一个字符串拆分为两个字符串?

python - 在 Python 中创建一个带有变量定义的字符串(nympy.arange 对象)