Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 1D Numpy Array into a 1D image using PIL

PIL returns IndexError: tuple index out of range when converting a 1D numpy array into an PIL image object.

I am trying to covert a 1D Numpy Array of length 2048 having value between 0 and 255 into an image using PIL. I think this is an issue with my array being 1D. I have also tried converting a random 1D array integer to an image and I get the same error.

Random integer example:

from PIL import Image
import numpy as np

arr = np.random.randint(255, size=(2048))
arr = arr.astype('uint8')
img = Image.fromarray(arr, 'L')
img.show()

I would expect the code to show an image of a singe line of pixels having varying shades of gray.

like image 834
user12274714 Avatar asked Nov 18 '25 03:11

user12274714


2 Answers

When I tried to run your code, the problem was just that your array was a 1D array. So try:

arr2d = arr.reshape(-1,1)
Image.fromarray(arr2d,'L').show()
like image 144
imochoa Avatar answered Nov 19 '25 16:11

imochoa


The input array has to be 2D, even if one dimension is 1. You just need to decide if you want the image to be a horizontal or vertical row of pixels, and add a dimension when creating your array.

arr = np.random.randint(255, size=(2048, 1))  # vertical image

arr = np.random.randint(255, size=(2048, 1))  # horizontal image
like image 42
aganders3 Avatar answered Nov 19 '25 16:11

aganders3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!