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?
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()
I am using:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With