如何在 Python 中重塑 Numpy 数组
How To ReShape a Numpy Array in Python
我有 numpy array
个形状为 (5879,)
的图像。在 numpy 数组的每个索引中,我都有形状为 (640,640,3)
的图像像素。
我想重塑整个数组,使 numpy 数组的形状变为 (5879,640,640,3)
.
您想沿第一个轴将图像堆叠到 4D 阵列中。但是,您的图像都是 3D 的。
所以,首先你需要add a leading singleton dimension to all images, and then to concatenate他们沿着这个轴:
imgs = [i_[None, ...] for i_ in orig_images] # add singleton dim to all images
x = np.concatenate(imgs, axis=0) # stack along the first axis
编辑:
基于 , it seems like using np.stack
在这里更合适:np.stack
负责为您添加领先的单例维度:
x = np.stack(orig_images, axis=0)
请检查以下代码是否适合您
import numpy as np
b = np.array([5879])
b.shape
output (1,)
a = np.array([[640],[640],[3]])
a = a.reshape((a.shape[0], 1))
a.shape
output (3, 1)
c = np.concatenate((a,b[:,None]),axis=0)
c.shape
Output:
(4, 1)
np.concatenate((a,b[:,None]),axis=0)
output
array([[ 640],
[ 640],
[ 3],
[5879]])
我有 numpy array
个形状为 (5879,)
的图像。在 numpy 数组的每个索引中,我都有形状为 (640,640,3)
的图像像素。
我想重塑整个数组,使 numpy 数组的形状变为 (5879,640,640,3)
.
您想沿第一个轴将图像堆叠到 4D 阵列中。但是,您的图像都是 3D 的。 所以,首先你需要add a leading singleton dimension to all images, and then to concatenate他们沿着这个轴:
imgs = [i_[None, ...] for i_ in orig_images] # add singleton dim to all images
x = np.concatenate(imgs, axis=0) # stack along the first axis
编辑:
基于 np.stack
在这里更合适:np.stack
负责为您添加领先的单例维度:
x = np.stack(orig_images, axis=0)
请检查以下代码是否适合您
import numpy as np
b = np.array([5879])
b.shape
output (1,)
a = np.array([[640],[640],[3]])
a = a.reshape((a.shape[0], 1))
a.shape
output (3, 1)
c = np.concatenate((a,b[:,None]),axis=0)
c.shape
Output:
(4, 1)
np.concatenate((a,b[:,None]),axis=0)
output
array([[ 640],
[ 640],
[ 3],
[5879]])