10

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?

3
  • Possible dupliate of how to convert an RGB image to numpy array? Commented Mar 14, 2018 at 9:39
  • Please show us a bit of your code. Commented Mar 14, 2018 at 9:49
  • @DanielF No it's not solve My problem as it is taking Image as input while my data already in csv format while taking image as input you get 3 channels by default,while mine is 1 channel data. Commented Mar 14, 2018 at 11:55

1 Answer 1

10

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
Sign up to request clarification or add additional context in comments.

5 Comments

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
@Avyukth this method seems to distort images... stackoverflow.com/questions/62293077/…
It only distorts images if you combine it with OpenCV functionality, but that is not being used here.
@physicalattraction do you have any clue how to stop it from distorting images, even when using with opencv?
I have never used OpenCV, so I don't know anything about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.