O'Reilly logo

NumPy Cookbook - Second Edition by Ivan Idris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the buffer protocol

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.

Getting ready

Install PIL and SciPy if necessary. Check out the See also section of this recipe for instructions.

How to do it...

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required