有一个形状为A
的nd数组[100,255,255,3]
,对应于100个255 * 255个图像。我想迭代这个多维数组,每次迭代我得到一个图像。这就是我所做的,A1 = A[i,:,:,:]
生成的A1
具有形状[255,255,3]
。但是,我想强制它具有[1,255,255,3]
形状。我该怎么办?
答案 0 :(得分:2)
np.reshape(A1, (1, 255, 255, 3))
应该做的伎俩
答案 1 :(得分:0)
在结果数组上使用np.newaxis
。
二维数组上非常简单的例子:
x = np.array([[0, 1], [2, 3]])
x.shape
#: (2, 2)
x[np.newaxis]
#: array([[[0, 1],
#: [2, 3]]])
x[np.newaxis].shape
#: (1, 2, 2)
答案 2 :(得分:0)
当然,没问题。使用'重塑'。假设A1是一个numpy数组
A1 = A1.reshape([1,255,255,3])
这会重塑你的矩阵。
如果A1不是numpy数组,那么使用
A1 = numpy.array(A1).reshape([1,255,255,3])
答案 3 :(得分:0)
答案是......这是一个例子,请注意你必须仔细看托架以辨别a和b是否因尺寸不同而
>>> a = np.arange(2*2*2*2).reshape(2,2,2,2)
>>> a.ndim
4
>>> b = a.reshape((1,)+a.shape)
>>> b.ndim
5
>>> a
array([[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]]],
[[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]]])
>>> b
array([[[[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]]],
[[[ 8, 9],
[10, 11]],
[[12, 13],
[14, 15]]]]])
答案 4 :(得分:0)
如果使用:
for a in A: # iteration on the first dimension
a = a[None,...] # add the dim back
# or a.reshape(...)
但如果使用
for i in range(A.shape[0]):
a = A[[i]] # preserve the 1st dim
# or a = A[None,i,...]
但我喜欢使用enumerate
所以:
for i, a in enumerate(A):
a = a[None,...]
但我鼓励你思考为什么你需要这个初始的1维。也许你甚至不需要迭代?