C-based Python objects have a so-called buffer interface. Python objects can expose their data for direct access without the need to copy it. The buffer protocol enables us to communicate with other pieces of Python software such as the Python Imaging Library (PIL).
We will see an example of saving a PIL image from a NumPy array.
Install PIL and SciPy if necessary. Check out the See also section of this recipe for instructions.
The complete code for this recipe is in the buffer.py
file in this book's code bundle:
import numpy as np import Image #from PIL import Image (Python 3) import scipy.misc lena = scipy.misc.lena() data = np.zeros((lena.shape[0], lena.shape[1], 4), dtype=np.int8) data[:,:,3] = lena.copy() img = Image.frombuffer("RGBA", lena.shape, data, 'raw', "RGBA", 0, 1) img.save('lena_frombuffer.png') data[:,:,3] = 255 data[:,:,0] = 222 img.save('lena_modified.png')
First we need a NumPy array to play with:
In previous chapters...