python - 将数据添加到 numpy 数组的新维度中

标签 python arrays numpy image-processing

我有一个大小为 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)

enter image description here

现在您只需一步即可获得所需的阵列。

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)

enter image description here

关于python - 将数据添加到 numpy 数组的新维度中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70042114/

相关文章:

Python hashlib - 列表理解的更新和摘要

python - 使用 sympy 和 numpy 更改数组索引的问题

c - 动态内存分配实践

python - 在 Python 中围绕指定原点旋转二维图像

Python:将方阵提高到负半幂

python - 从 JPG 到 b64encode 再到 cv2.imread()

python - 如何从 Pandas 字典中删除/xa0?

python - 如何将 Python 数组转换为 SymPy 矩阵来计算行列式?

python - 将自纪元以来的时间戳转换为 datetime.datetime

c++ - 找出平均值大于或等于 K 的子数组的数量