繁体   English   中英

Numpy:在另一个numpy数组中创建一批numpy数组(重新整形)

[英]Numpy: creating batch of numpy arrays within another numpy array (reshaping)

我有一个numpy的阵列batch形状的(32,5) 批处理的每个元素都包含一个numpy数组batch_elem = [s,_,_,_,_] ,其中s = [img,val1,val2]是一个三维numpy数组, _只是标量值。 img是一个尺寸为(84,84,3)的图像(numpy数组(84,84,3)

我想创建一个具有形状(32,84,84,3)的numpy数组。 基本上我想在每个batch提取图像信息并将其转换为4维数组。

我尝试了以下方法:

b = np.vstack(batch[:,0]) #this yields a b with shape (32,3), type: <class 'numpy.ndarray'>

现在我想访问图像(第二维中的第一个索引)

img_batch = b[:,0] # this returns an array of shape (32,), type: <class 'numpy.ndarray'>

如何最好地访问图像数据并获得形状(32,84,84,3)

注意:

 s = b[0] #first s of the 32 in batch: shape (3,) , type: <class 'numpy.ndarray'>

编辑:

这应该是一个最小的例子:

img = np.zeros([5,5,3])
s = np.array([img,1,1])
batch_elem = np.array([s,1,1,1,1])
batch = np.array([batch_elem for _ in range(32)])

假设我正确理解了问题,您可以在最后一个轴上堆叠两次。

res = np.stack(np.stack(batch[:,0])[...,0])

import numpy as np

# fabricate some data
batch = np.array((32, 1), dtype=object)
for i in range(len(batch)):
    batch[i] = [np.random.rand(84, 84, 3), None, None]

# select images
result = np.array([img for img, _, _ in batch])

# double check!
for i in range(len(batch)):
    assert np.all(result[i, :, :, :] == batch[i][0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM