将numpy数组转换为RGB图像

Avy*_*kth 3 python numpy image python-imaging-library

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

我正在使用Python PILnumpy通过以下代码将数组转换为图像:

imge_out = Image.fromarray(img_as_np.astype('uint8'))
img_as_img = imge_out.convert("RGB")
Run Code Online (Sandbox Code Playgroud)

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

img_as_img = imge_out.convert("R")
Run Code Online (Sandbox Code Playgroud)

表明

error conversion from L to R not supported
Run Code Online (Sandbox Code Playgroud)

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

phy*_*ion 5

您需要一个适当大小的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()
Run Code Online (Sandbox Code Playgroud)

amsterdam_190x150.jpg

我在用:

  • Python 3.6.3
  • numpy的1.14.2
  • 枕头4.3.0