9

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?

Mr. T
  • 11,960
  • 10
  • 32
  • 54
Avyukth
  • 101
  • 1
  • 1
  • 4
  • Possible dupliate of [how to convert an RGB image to numpy array?](https://stackoverflow.com/questions/7762948/how-to-convert-an-rgb-image-to-numpy-array) – Daniel F Mar 14 '18 at 09:39
  • Please show us a bit of your code. – offeltoffel Mar 14 '18 at 09: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. – Avyukth Mar 14 '18 at 11:55

1 Answers1

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
physicalattraction
  • 6,485
  • 10
  • 63
  • 122