Convert numpy array to rgb image

23,863

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'
    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()

amsterdam_190x150.jpg

I am using:

  • Python 3.6.3
  • numpy 1.14.2
  • Pillow 4.3.0
Share:
23,863
Avyukth
Author by

Avyukth

Updated on March 18, 2020

Comments

  • Avyukth
    Avyukth about 4 years

    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.

    I am using Python PIL library to convert a numpy array to an image with the following code:

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

    The output converts the image into 3 channels, but it's shown as a black and white (grayscale) image. If I use the following code

    img_as_img = imge_out.convert("R")
    

    it shows

    error conversion from L to R not supported
    

    How do I properly convert numpy arrays to RGB pictures?

  • Avyukth
    Avyukth about 6 years
    thanks for your reply as you pointed out there must be 3 channel for RGB image , I am working with fashion dataset which is grayscale and single channel
  • Ludovico Verniani
    Ludovico Verniani almost 4 years
    @Avyukth this method seems to distort images... stackoverflow.com/questions/62293077/…
  • physicalattraction
    physicalattraction almost 4 years
    It only distorts images if you combine it with OpenCV functionality, but that is not being used here.
  • Mika C.
    Mika C. about 2 years
    @physicalattraction do you have any clue how to stop it from distorting images, even when using with opencv?
  • physicalattraction
    physicalattraction about 2 years
    I have never used OpenCV, so I don't know anything about it.