Skip to content Skip to sidebar Skip to footer

Convert Numpy Array To Rgb Image

I have a numpy array with value range from 0-255. I want to convert it into a 3 channel RGB image. I use the PIL Image.convert() function, but it converts it to a grayscale image.

Solution 1:

You need a properly sized numpy array, meaning a HxWx3 array with integers. I tested it with the following code and input, seems to work as expected.

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'assertisinstance(np_array, np.ndarray), assert_msg
    assertlen(np_array.shape) == 3, assert_msg
    assert np_array.shape[2] == 3, assert_msgimg= Image.fromarray(np_array, 'RGB')
    return img


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

amsterdam_190x150.jpg

I am using:

  • Python 3.6.3
  • numpy 1.14.2
  • Pillow 4.3.0

Post a Comment for "Convert Numpy Array To Rgb Image"