【问题标题】:Python np.asarray does not return the true shapePython np.asarray 不返回真实形状
【发布时间】:2019-09-04 07:06:46
【问题描述】:

我在原始表的两个子表上旋转一个循环。

当我开始循环并检查形状时,我得到 (1008,) 而形状必须是 (1008,168,252,3)。我的循环有问题吗?

train_images2 = []
for i in range(len(train_2)):
  im = process_image(Image.open(train_2['Path'][i]))
  train_images2.append(im)
train_images2 = np.asarray(train_images2)

【问题讨论】:

  • 这是 train_2 还是 train_images2 的形状(1008,)?
  • 数组的dtype是什么?
  • 检查您放入列表中的所有图像是否具有相同的形状。如果不是,那么当train_images2 转换为数组时,它将是一个数据类型为object 的一维数组。
  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: python loops numpy multidimensional-array numpy-ndarray


【解决方案1】:

问题在于您的 process_image() 函数返回的是标量而不是处理后的图像(即形状为 (168,252,3) 的 3D 数组)。所以,变量im 只是一个标量。因此,您将数组train_images2 变为一维数组。下面是一个人为的例子来说明这一点:

In [59]: train_2 = range(1008)
In [65]: train_images2 = []

In [66]: for i in range(len(train_2)):
    ...:     im = np.random.random_sample()
    ...:     train_images2.append(im)
    ...: train_images2 = np.asarray(train_images2)
    ...: 

In [67]: train_images2.shape
Out[67]: (1008,)

因此,解决方法是您应该确保 process_image() 函数返回一个 3D 数组,如下面人为设计的示例所示:

In [58]: train_images2 = []
In [59]: train_2 = range(1008)

In [60]: for i in range(len(train_2)):
    ...:     im = np.random.random_sample((168,252,3))
    ...:     train_images2.append(im)
    ...: train_images2 = np.asarray(train_images2)
    ...: 

# indeed a 4D array as you expected
In [61]: train_images2.shape
Out[61]: (1008, 168, 252, 3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    相关资源
    最近更新 更多