Mohamed Witti Adou
Mohamed Witti Adou

Reputation: 439

Create image with PIL `Image.fromarray` results in AttributeError: 'list' object has no attribute '__array_interface__'

I wanted to display an image from a NumPy array, but I got this error:

Traceback (most recent call last):
  File "E:/wittos/python/SVM/witti svm/arraytoimage.py", line 14, in <module>
   image = Image.fromarray(arry)
  File "C:\Users\MOHAMED-WITTI-ADOU\AppData\Local\Programs\Python\Python35\lib\site-packages\PIL\Image.py", line 2483, in fromarray
    arr = obj.__array_interface__
AttributeError: 'list' object has no attribute '__array_interface__'

I would like that you help me to solve this error.

import numpy as np
from PIL import Image

# Create a NumPy array
arry = np.array([3,3])
arry= [[25,25,25],[0,0,0],[0,0,0]]

# Create a PIL image from the NumPy array
image = Image.fromarray(arry)

# Save the image
image.save('image.jpg')

Upvotes: 5

Views: 13641

Answers (3)

Emile
Emile

Reputation: 1

You can add the function that verify is data is None like:

# Create a PIL image from the NumPy array
image = Image.fromarray(arry)

if image is None:
    pass

Upvotes: 0

Anidhya Bhatnagar
Anidhya Bhatnagar

Reputation: 646

Your way of creating the numpy array is wrong. You should rather create it as:

arry = np.array([[25,25,25],[0,0,0],[0,0,0]])

Then it will work. Since, you are overwriting the empty numpy array created with normal array.

import numpy as np
from PIL import Image

# Create a NumPy array
arry = np.array([[25,25,25],[0,0,0],[0,0,0]])

# Create a PIL image from the NumPy array
image = Image.fromarray(arry.astype('uint8'))

# Save the image
image.save('image.jpg')

This will work.

Upvotes: 5

Dani Mesejo
Dani Mesejo

Reputation: 61910

The problem is that you are not creating a numpy array:

# Create a NumPy array
arry = np.array([3,3])
arry= [[25,25,25],[0,0,0],[0,0,0]]

when you do that arry becomes a list of lists, hence the error:

AttributeError: 'list' object has no attribute 'array_interface'

You should do this instead:

import numpy as np
from PIL import Image

# Create a NumPy array
arry = np.array([[25, 25, 25], [0, 0, 0], [0, 0, 0]], dtype=np.uint8)

# Create a PIL image from the NumPy array
image = Image.fromarray(arry)

# Save the image
image.save('image.jpg')

Note that the above specifies the dtype of arry to be np.uint8.

Upvotes: 2

Related Questions