【问题标题】:Convert numpy array to rgb image将numpy数组转换为rgb图像
【发布时间】:2018-08-22 15:19:24
【问题描述】:

我有一个 numpy 数组,其值范围为 0-255。我想将其转换为 3 通道 RGB 图像。我使用PIL Image.convert() 函数,但它会将其转换为灰度图像。

我正在使用 Python PIL 库将 numpy 数组转换为具有以下代码的图像:

imge_out = Image.fromarray(img_as_np.astype('uint8'))
img_as_img = imge_out.convert("RGB")

输出将图像转换为 3 个通道,但显示为黑白(灰度)图像。如果我使用以下代码

img_as_img = imge_out.convert("R")

它显示

error conversion from L to R not supported

如何正确地将 numpy 数组转换为 RGB 图片?

【问题讨论】:

  • 请给我们看一些你的代码。
  • @DanielF 不,它没有解决我的问题,因为它以图像作为输入,而我的数据已经是 csv 格式,而以图像作为输入,默认情况下你得到 3 个通道,而我的是 1 个通道数据。

标签: python image numpy python-imaging-library


【解决方案1】:

您需要一个大小合适的 numpy 数组,即包含整数的 HxWx3 数组。我使用以下代码和输入对其进行了测试,似乎按预期工作。

import os.path
import numpy as np
from PIL import Image


def pil2numpy(img: Image = None) -> np.ndarray:
    """
    Convert an HxW pixels RGB Image into an HxWx3 numpy ndarray
    """

    if img is None:
        img = Image.open('amsterdam_190x150.jpg'))

    np_array = np.asarray(img)
    return np_array


def numpy2pil(np_array: np.ndarray) -> Image:
    """
    Convert an HxWx3 numpy array into an RGB Image
    """

    assert_msg = 'Input shall be a HxWx3 ndarray'
    assert isinstance(np_array, np.ndarray), assert_msg
    assert len(np_array.shape) == 3, assert_msg
    assert np_array.shape[2] == 3, assert_msg

    img = Image.fromarray(np_array, 'RGB')
    return img


if __name__ == '__main__':
    data = pil2numpy()
    img = numpy2pil(data)
    img.show()

我正在使用:

  • Python 3.6.3
  • numpy 1.14.2
  • 枕头 4.3.0

【讨论】:

  • 感谢您的回复,因为您指出 RGB 图像必须有 3 个通道,我正在使用灰度和单通道的时尚数据集
  • @Avyukth 这种方法似乎会扭曲图像...stackoverflow.com/questions/62293077/…
  • 如果你将它与 OpenCV 功能结合起来,它只会扭曲图像,但这里没有使用。
猜你喜欢
  • 2011-12-07
  • 1970-01-01
  • 2021-04-02
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-12-28
  • 2018-04-19
相关资源
最近更新 更多