【问题标题】:Adding data into new dimension of numpy array将数据添加到 numpy 数组的新维度
【发布时间】:2021-12-30 15:46:29
【问题描述】:

我有一个大小为 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 的数组

【问题讨论】:

  • 简单地创建一个形状为 55x3x10x10 的新空数组并将切片设置为每个变量(例如array_4d[:,0,:,:] = img0)怎么样?
  • 您确定不想要 55x10x10x3 的形状而不是 55x3x10x10 的形状吗?从 PIL.Image 创建 numpy 数组时,RGB 值总是最后的。当然,如果您打算稍后将 RGB 层单独用作蒙版,则将它们完全分开是有目的的。
  • @DavidTriphon 我很确定我需要它作为 55x3x10x10,我想将数组作为训练数据输入到 torchvision 的预写图像分类网络之一

标签: python arrays numpy image-processing


【解决方案1】:

让我们首先创建一个大小为 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)

如果你想最后一个频道,请使用axis=-1

现在让我们通过从该数组中提取第一张图像并取 3 个通道的平均值来验证该值是否正确:

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

对于视觉验证,您必须将频道移到最后,因为这是matplotlib 需要的。这是一个 3 通道图像,所以我们这里没有使用cmap='gray'

print(np.moveaxis(new_img, 0, -1).shape)
plt.imshow(np.moveaxis(new_img, 0, -1))
>>> (10, 10, 3)

【讨论】:

    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 2017-06-10
    • 2019-06-18
    • 2020-07-06
    • 2019-11-21
    相关资源
    最近更新 更多