我有一个非常大的数组,我希望使用重叠来平铺。例如,如果数组看起来像
a b c d e
f g h i j
k l m n o
p q r s t
u v w x y
我想把它分解成3x3块,每块瓷砖与它的邻居重叠1块:
a b c c d e
f g h h i j
k l m m n o
k l m m n o
p q r r s t
u v w w x y
“重塑和转置技巧”(在https://www.kaggle.com/c/hubmap-kidney-segmentation/discussion/202171中描述)是一种在Python (和其他语言)中平铺一个大数组的方法,它允许提取和表示与相邻的(而不是重叠)块,而不必复制底层数据数组。
我想知道的是:如果我们想要重叠,是否可以使用这个技巧,如上面所示?如果是这样的话,是怎么做的?
发布于 2021-01-15 21:09:20
我不认为仅通过整形就可以做到这一点,但是可以使用更低级别的numpy.lib.stride_tricks.as_strided
函数来完成,仔细设置shape
和strides
参数:
>>> x = np.arange(25).reshape(5, 5)
>>> x
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> y = np.lib.stride_tricks.as_strided(x, shape=(2, 2, 3, 3),
... strides=(80, 16, 40, 8))
>>> y
array([[[[ 0, 1, 2],
[ 5, 6, 7],
[10, 11, 12]],
[[ 2, 3, 4],
[ 7, 8, 9],
[12, 13, 14]]],
[[[10, 11, 12],
[15, 16, 17],
[20, 21, 22]],
[[12, 13, 14],
[17, 18, 19],
[22, 23, 24]]]])
第二个数组被分割成重叠的块,您可以确认这两个数组共享相同的内存:
>>> np.byte_bounds(x) == np.byte_bounds(y)
True
https://stackoverflow.com/questions/65746478
复制相似问题