如果图像具有形状(28, 28, 3, 1)
,如何将其转换为形状(28, 28, 3)
?
我想我的形状的最后一个1
是批量大小。
如注释np.squeeze
中所建议,是最原则的方法。添加一些细节。
import numpy as np
image = np.ones(shape=(28, 28, 3, 1))
print(image.shape) # (28, 28, 3, 1)
image = np.squeeze(image, axis=-1)
print(image.shape) # (28, 28, 3)
我也强烈建议您始终明确指定要使用axis
参数挤压的轴,以避免错误地删除其他单轴。实际上,默认情况下,np.squeeze
会删除所有一维条目。如果您加载例如灰度图像。
gray = np.ones(shape=(28, 28, 1, 1))
print(gray.shape) # (28, 28, 1, 1)
gray = np.squeeze(gray)
print(gray.shape) # (28, 28) may not be what you want
您还可以根据自己的喜好将索引用于相同的目的。
image = np.ones(shape=(28, 28, 3, 1))
image = image[..., 0] # same as: image[:, :, :, 0]
print(image.shape) # (28, 28, 3)