【问题标题】:Image reshape is not working in Pillow for grey image?图像重塑在 Pillow 中不适用于灰色图像?
【发布时间】:2020-04-16 09:56:54
【问题描述】:

我正在使用下面的代码来重塑我的形象。它适用于RGB图像。但是,它不适用于灰度图像。

from PIL import Image
import numpy as np
def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return np.array(image).reshape((im_height, im_width, 3)).astype(np.uint8)

image_path="color.jpg"
image = Image.open(image_path)
image_np = load_image_into_numpy_array(image)
image.close()

这是工作图像color.jpg

这不是工作图像grey.jpg

两个图像的形状都是一样的。

image.size

(714, 714)

当我打印图像时,我发现了不同之处。

工作图像print(image)

 <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=714x714 at 0x7F95DB4D4BA8>

图片无效print(image)

 <PIL.JpegImagePlugin.JpegImageFile image mode=L size=714x714 at 0x7F32B5430BA8>
  1. 如何解决这个问题?
  2. 这是因为模式更改吗?

任何帮助都将不胜感激。

错误:

Traceback (most recent call last):
  File "checker.py", line 11, in <module>
    image_np = load_image_into_numpy_array(image)
  File "checker.py", line 5, in load_image_into_numpy_array
    return np.array(image).reshape((im_height, im_width, 3)).astype(np.uint8)
ValueError: cannot reshape array of size 509796 into shape (714,714,3)

【问题讨论】:

    标签: python python-3.x image numpy python-imaging-library


    【解决方案1】:

    您不需要任何重塑。如果您想要 Numpy 数组中的 3 通道图像,只需执行以下操作:

    import numpy as np
    from PIL import Image
    
    # Open image as PIL Image and ensure 3-channel RGB
    im = Image.open('input.jpg').convert('RGB')
    
    # Make into Numpy array
    na = np.array(im)
    

    您可能会发现this 回答有关调色板图像也很有帮助。

    【讨论】:

      【解决方案2】:

      该功能不适用于灰度图像,您需要将最后一维的通道数编辑为(IM_HEIGHT, IM_WIDTH, 1)。这是因为您不再使用 RGB 颜色通道。

      试试这个:

      def load_image_into_numpy_array(image):
          (im_width, im_height) = image.size
          return np.array(image).reshape((im_height, im_width, 1)).astype(np.uint8)
      

      【讨论】:

      • 感谢您的回复。无论如何我可以将灰色图像添加或转换为彩色图像吗?因为对于我的应用程序,我无法将 3 修改为 1。
      • @MohamedThasinah 是的,请在下面查看我的回答。
      【解决方案3】:

      另一个简单的想法是将 grayscale 图像沿通道维度(即轴 2)连接三次,如果传入图像的形状元组长度为 2,如您的情况:

      def load_image_into_numpy_array(image):
          if len(image.shape) == 2:
              image = image[:, :, np.newaxis]
              image = np.concatenate([image]*3, axis=2)
          return np.array(image).astype(np.uint8)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-02-14
        • 1970-01-01
        • 2020-10-28
        • 2014-04-21
        • 2019-02-20
        • 2018-02-21
        相关资源
        最近更新 更多