我有一个大小为 55 x 10 x 10 的 numpy 数组,它代表 55 个 10 x 10 灰度图像。我试图通过将 10 x 10 图像复制 3 次来将它们设为 RGB。
根据我的理解,我首先需要添加一个新维度来容纳重复的数据。我已经使用以下方法完成了此操作:
array_4d = np.expand_dims(array_3d, 1)
,
所以我现在有一个 55 x 1 x 10 x 10 的数组。现在如何复制 10 x 10 图像并将它们添加回此数组?
快速编辑:最后我想要一个 55 x 3 x 10 x 10 的数组
最佳答案
让我们首先创建一个大小为 55x10x10 的 3d 数组
from matplotlib import pyplot as plt
import numpy as np
original_array = np.random.randint(10,255, (55,10,10))
print(original_array.shape)
>>>(55, 10, 10)
数组中第一张图像的视觉效果:
first_img = original_array[0,:,:]
print(first_img.shape)
plt.imshow(first_img, cmap='gray')
>>>(10, 10)
现在您只需一步即可获得所需的阵列。
stacked_img = np.stack(3*(original_array,), axis=1)
print(stacked_img.shape)
>>>(55, 3, 10, 10)
如果您希望 channel 最后,请使用axis=-1
现在让我们通过从此数组中提取第一张图像并取 3 个 channel 的平均值来验证该值是否正确:
new_img = stacked_img[0,:,:,:]
print(new_img.shape)
>>> (3, 10, 10)
new_img_mean = new_img.mean(axis=0)
print(new_img_mean.shape)
>>> (10, 10)
np.allclose(new_img_mean, first_img) # If this is True then the two arrays are same
>>> True
对于视觉验证,您必须将 channel 移至最后,因为这是 matplotlib
所需要的。这是一个 3 channel 图像,因此我们此处不使用 cmap='gray'
print(np.moveaxis(new_img, 0, -1).shape)
plt.imshow(np.moveaxis(new_img, 0, -1))
>>> (10, 10, 3)
关于python - 将数据添加到 numpy 数组的新维度中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70042114/