如何在 python 中重塑图像的尺寸

How to reshape the dimension of image in python

假设我有训练图像 X_train.shape = (32,32,3,1000)。这意味着有 1000 张图像,每张图像的大小为 32x32,具有 3 个颜色通道。它是列表形式的列表。我想让它有一个形状(1000、32、32、3)。我知道我可以使用 for 循环手动将其更改为我想要的形状,但我想知道 numpytensorflow 中是否有任何功能可以快速轻松地完成?

您可以使用 np.moveaxis.

import numpy as np

X_train = np.random.rand(32, 32, 3, 1000)
print(X_train.shape)

X_train_new = np.moveaxis(X_train, 3, 0)
print(X_train_new.shape)

此处 3 - 源索引,0 - 目标索引。

输出

(32, 32, 3, 1000)
(1000, 32, 32, 3)

如果它是列表的列表,首先将其转换为 numpy 数组或张量:

使用 numpy:

X_train = np.array(X_train)
X_train = np.reshape(X_train, (1000, 32, 32, 3))

使用 TensorFlow:

X_train = tf.cast(X_train, dtype=tf.float32)
X_train = tf.reshape(X_train, shape=(1000, 32, 32, 3))

你可以使用 np.einsum.

>>> X_train_new = np.einsum('ijkl->lijk',X_train)
>>> X_train.shape
(32, 32, 3, 1000)
>>> X_train_new.shape
(1000, 32, 32, 3)