Image.fromarray cannot be used with array.array
I'm using Python 3.6 and Pillow 4.0.0 I'm trying to make a PIL image of an array of values, see the simplified code below, I get the following error:. AttributeError: 'array.array' object has no attribute '__array_interface__'
When calling the function Image.fromarray()
.
Why is this happening? When the PIL documentation says: Creates an image memory from an object exporting an array interface (using the buffer protocol). and the array.array documentation says: Array objects also implement the buffer interface and can be used wherever byte-like objects are supported ...
from PIL import Image
from array import array
arr = array('B', [100, 150, 200, 250])
im = Image.fromarray(arr)
im.show()
source to share
You should be using array interface
( using a buffer protocol ) try this:
from PIL import Image
import numpy as np
w, h = 512, 512
data = np.zeros((h, w, 4), dtype=np.uint8)
for i in range(w):
for j in range(h):
data[i][j] = [100, 150, 200, 250]
img = Image.fromarray(data, 'RGB')
img.show()
You can read Introduction to the Python Buffer Protocol
source to share