【问题标题】:Converting two PNG-Images into numpy arrays results in two different shapes将两个 PNG 图像转换为 numpy 数组会产生两种不同的形状
【发布时间】:2021-01-17 13:53:07
【问题描述】:

在将 PNG 文件转换为 numpy 数组时,我注意到转换有时会导致不同的数组形状。而the first image 具有三维阵列形状(与大多数图像一样)the second one 具有二维。图像均为屏幕截图,未经更改。不幸的是,数组形状对于我的预期用途确实很重要。

我使用下面的代码进行图像转换。

import numpy as np
import PIL.Image

img_path = ''  # Put the image path here

img_pil = PIL.Image.open(img_path)
img_array = np.asarray(img_pil)

print(img_array.shape)

我的问题是是否有办法对齐图像的形状。

【问题讨论】:

    标签: python arrays numpy image-processing python-imaging-library


    【解决方案1】:

    如果您的图像都不是彩色的,您不妨节省内存并在灰度下工作,这样您就可以确保:

    im = Image.open(FILENAME).convert('L')
    

    或者您可以随时使用:

    im = Image.open(FILENAME).convert('RGB')
    

    【讨论】:

      【解决方案2】:

      从我在这里看到的:Image processing with numpy,灰度图像(就像第二张图像的情况一样)有时只存储在二维中,因为不需要保存三种不同的颜色对于每个像素。这可能取决于图像的创建方式。

      【讨论】:

      • 这似乎合乎逻辑。是否有直接的方法来创建具有匹配形状的图像?
      • 根据我的经验,您自己创建和保存的大部分(如果不是全部)图片都是 rgb(3 维)格式。您可以创建一个函数,将它们从二维数组“转换”为三维数组。
      猜你喜欢
      • 1970-01-01
      • 2019-07-20
      • 2019-09-06
      • 1970-01-01
      • 2020-04-04
      • 2023-03-23
      • 2014-02-15
      • 2022-12-05
      • 1970-01-01
      相关资源
      最近更新 更多