gpt4 book ai didi

python - 如何创建 numpy View 数组?

转载 作者:行者123 更新时间:2023-11-30 22:58:21 25 4
gpt4 key购买 nike

我的图像位于形状(3,高度,宽度)的 numpy 数组中,我想创建一个子 ImageView 。我确切地知道我将拥有多少个子图像,并且可以循环创建每个子图像。我就是这样做的:

result_array = np.empty(
shape=(
int((res_img.shape[WIDTH] - SUB_IMG_WIDTH + 1) / step * (
res_img.shape[HEIGHT] - SUB_IMG_HEIGHT + 1) / step),
SUB_IMG_LAYERS, SUB_IMG_HEIGHT, SUB_IMG_WIDTH),
dtype=np.dtype(float))

for i in range(0, img.shape[WIDTH] - sub_img_shape[WIDTH], step):
for ii in range(0, img.shape[HEIGHT] - sub_img_shape[HEIGHT], step):
result_array[index] = img[:, i:i + sub_img_shape[WIDTH], ii:ii + sub_img_shape[HEIGHT]]

但是我得到的不是 View 数组,而是副本数组。这本身不是问题,我不需要修改它们,只需在 GPU 上同时使用它们即可,但它会消耗大量内存:我的图像大小约为 1000x600,并且大约有 100 000 个子图像。所以我的子图像数组消耗了 3-4 GB 的 RAM。我尝试将 View 存储在 python 列表中,如下所示:

for i in range(0, img.shape[WIDTH] - sub_img_shape[WIDTH], step):
for ii in range(0, img.shape[HEIGHT] - sub_img_shape[HEIGHT], step):
result_array.append(img[:, i:i + sub_img_shape[WIDTH], ii:ii + sub_img_shape[HEIGHT]])

它确实有效,但我怀疑这是一个好方法。我可以用 numpy 数组而不是 python 列表来做到这一点吗?

最佳答案

您可以使用 as_strided 来完成此操作功能:

import numpy as np
from numpy.lib.stride_tricks import as_strided
N=10
L=4*N
H=3*N
step=5
a=(np.arange(3*H*L)%256).reshape(3,H,L)
(k,j,i)=a.strides
b=as_strided (a,shape=(H/step,L/step,3,step,step),strides=(j*step,i*step,k,j,i))

b 然后对每个 block 进行寻址,无需复制。

In [29]: np.all(b[1,2]==a[:,5:10,10:15])
Out[29]: True

In [30]: a[:,5,10]=0 # modification of a

In [31]: np.all(b[1,2]==a[:,5:10,10:15])
Out[31]: True # b also modified

关于python - 如何创建 numpy View 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36216102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com