假设我有一个非常大的2D矩阵:
import numpy as np
X = np.random.random((8000, 8000))
我有四个非常大的数组(大约500万个元素),它们都有相同的形状,它们是from_row
,to_row
,from_col
,to_col
。这四个数组,顾名思义,代表我想从X
矩阵中裁剪的矩形的坐标。生成的矩形保证都有相同的大小。
基本上,我想以更有效的方式做这样的事情:
n_rects = len(from_row) # The four arrays have the same shape
crops = np.zeros((n_rects, rect_height, rect_width), dtype=X.dtype)
for i in range(n_rects):
crop[i] = X[from_row[i]:to_row[i], from_col[i]:to_col[i]]
有没有可能更有效地做这样的事情?
1条答案
按热度按时间pprl5pva1#
编辑:另一种更简单的方法是索引数组的滑动窗口视图:
为了方便起见,您可以利用numpy的高级索引规则与广播相结合,以矢量化的方式实现这一点。请注意,为了使其工作,每个矩形都需要具有相同的大小,因此使用
start
和size
而不是start
和end
可能更自然。下面是一个示例:结果: