3
votes

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.

2

2 Answers

1
votes

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()
1
votes

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