pythonnumpypython-imaging-library

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')

Solution

  • 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.