【问题标题】:How to convert 4D array to another 4D with switched dimentions in Python如何在 Python 中将 4D 数组转换为具有切换维度的另一个 4D
【发布时间】:2016-07-25 12:34:05
【问题描述】:

我正在尝试从 TensorFlow 中的卷积层获取图像数据。 我有一个像这样的数组:

data = [N, Width, Height, Channel]

其中N为图片编号,Width和Height为图片尺寸,Channel为channel索引。

我需要的是另一个 4D 数组,例如:

[N, Channel, Width, Height]

原因是循环通过 N 和 Channel 并为每个图像的 ech 通道获取 2D 字节数组。

img = Image.fromarray(data[N][Channel], 'L')
img.save('my.png')

【问题讨论】:

  • 我的问题解决了。谢谢大家的快速解答!

标签: python arrays image numpy tensorflow


【解决方案1】:

使用转置函数重新排列维度。

https://www.tensorflow.org/versions/r0.9/api_docs/python/array_ops.html#transpose

你会在 tensorflow 代码中做这样的事情。

image = tf.transpose(image, perm = [0, 3, 1, 2])

在 perm 参数中,您可以指定所需的新维度顺序。在这种情况下,您将通道维度 (3) 移动到第二个位置。

如果您想在将其输入到 tensorflow 模型之前执行此操作,您可以使用 np.transpose 以相同的方式。

【讨论】:

    【解决方案2】:

    只需使用np.transpose:

    x = np.zeros((32, 10, 10, 3))  # image with 3 channels, size 10x10
    res = np.tranpose(x, (0, 3, 1, 2))
    print res.shape  # prints (32, 3, 10, 10)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 2022-01-20
      • 2022-10-02
      相关资源
      最近更新 更多