【问题标题】:If image has shape( 28,28,3,1) how do I convert it to shape (28,28,3)?如果图像具有形状(28,28,3,1),我如何将其转换为形状(28,28,3)?
【发布时间】:2020-04-11 15:40:36
【问题描述】:

如果图像具有(28, 28, 3, 1) 形状,我如何将其转换为(28, 28, 3) 形状?

我猜在我的例子中最后一个1 是批量大小。

【问题讨论】:

  • 看看 NumPy 的squeeze 方法。
  • 你能告诉我如何使用它吗?
  • img = np.squeeze(img)

标签: python image opencv computer-vision cv2


【解决方案1】:

正如评论中所建议的那样,np.squeeze 是最有原则的方法。添加一些细节。

import numpy as np

image = np.ones(shape=(28, 28, 3, 1))
print(image.shape)  # (28, 28, 3, 1)

image = np.squeeze(image, axis=-1)
print(image.shape)  # (28, 28, 3)

我还强烈建议始终使用axis 参数明确指定要挤压的轴,以避免错误地删除其他单轴。实际上,np.squeeze 默认会删除所有单维条目。如果您加载例如,这可能会出现问题。一张灰度图。

gray = np.ones(shape=(28, 28, 1, 1))
print(gray.shape)  # (28, 28, 1, 1)

gray = np.squeeze(gray)
print(gray.shape)  # (28, 28) may not be what you want

编辑:让我再补充一句关于在这种情况下使用np.reshape 的注意事项。

np.reshape 确实有效。但是,值得注意的是,即使在不应该的情况下,它也能正常工作,这可能会导致令人讨厌的错误。示例:

# Due to a bug, you have an image whose shape is different from
#  the one you expect, which is (28, 28, 3, 1)
image = np.ones(shape=(56, 14, 3, 1))

# Reshape will still work, since (56 * 13 * 3) == (28 * 28 * 3)
#  so you won't notice - yet the reshaped image will be nonsense!
reshaped = np.reshape(image, (28, 28, 3))
print(reshaped.shape)  # (28, 28, 3)

您也可以根据个人喜好简单地将索引用于相同目的。

image = np.ones(shape=(28, 28, 3, 1))
image = image[..., 0]  # same as: image[:, :, :, 0]
print(image.shape)  # (28, 28, 3)

【讨论】:

    【解决方案2】:

    你可以使用numpy的reshape函数。

    import numpy as np
    reshaped = np.reshape(image,shape=(28,28,3))
    

    【讨论】:

      猜你喜欢
      • 2020-08-16
      • 2020-01-07
      • 2020-05-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      相关资源
      最近更新 更多