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 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 the See Also section of this recipe for instructions.

How to do it...

First, we need a NumPy array with which to play.

  1. Create an array from image data.

    In previous chapters, we saw how to load the "Lena" sample image of Lena Soderberg. We will create an array filled with zeroes, and populate the alpha channel with the image data:

    lena = scipy.misc.lena()
    data = numpy.zeros((lena.shape[0], lena.shape[1], 4), dtype=numpy.int8)
    data[:,:,3] = lena.copy()
  2. Save the data as a PIL image.

    Now, we will use the PIL API to save the data as a RGBA image:

    img = Image.frombuffer("RGBA", lena.shape, data)
    img.save('lena_frombuffer.png')
  3. Modify the data array and save the image.

    Modify the data array by getting rid of the image data and making the image red. Save the image with the PIL API:

    data[:,:,3] = 255 
    data[:,:,0] = 222 
    img.save('lena_modified.png')

The following is the before image:

How to do it...

The data of the PIL image object has changed by the magic of the "buffer interface", and therefore, we see the following image:

How to do it...

The complete code for this recipe is as follows:

import numpy
import Image
import scipy.misc

lena = scipy.misc.lena()
data = numpy.zeros((lena.shape[0], lena.shape[1], 4), dtype=numpy.int8)
data[:,:,3] = lena.copy()
img = Image.frombuffer("RGBA", lena.shape, data)
img.save('lena_frombuffer.png')

data[:,:,3] = 255 
data[:,:,0] = 222 
img.save('lena_modified.png')

How it works...

We created a PIL image from a buffer—a NumPy array. After changing the buffer, we saw the changes being reflected in the image object. This was done without copying the PIL image object; instead, we directly accessed and modified its data to make a red image out of the picture of the model.

See also

  • The Installing PIL recipe in Chapter 2, Advanced Indexing and Array Concepts
  • The Installing SciPy recipe in Chapter 2, Advanced Indexing and Array Concepts
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset