Using the array interface

The array interface is a yet another mechanism to communicate with other Python applications. This protocol, as its name suggests, is only applicable to array-like objects. A demonstration is in order. Let's use PIL again, but without saving files.

Getting ready

We will be reusing part of the code from the previous recipe, so the prerequisites are similar. We will skip the first step of the previous step here, and assume it is already known.

How to do it...

The following steps will let us explore the array interface:

  1. The PIL image array interface attribute.

    The PIL image object has a __array_interface__ attribute. Let's inspect its contents. The value of this attribute is a dictionary:

    array_interface = img.__array_interface__
    print "Keys", array_interface.keys() 
    print "Shape", array_interface['shape'] 
    print "Typestr", array_interface['typestr']

    This code prints the following information:

    Keys ['shape', 'data', 'typestr']
    Shape (512, 512, 4)
    Typestr |u1
    
  2. The NumPy array interface attributes.

    The NumPy ndarray module has a __array_interface__ attribute as well. We can convert the PIL image to a NumPy array with the asarray function:

    numpy_array = numpy.asarray(img)
    print "Shape", numpy_array.shape
    print "Data type", numpy_array.dtype

    The shape and data type of the array:

    Shape (512, 512, 4)
    Data type uint8
    

As you can see, the shape has not changed. The 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)
array_interface = img.__array_interface__
print "Keys", array_interface.keys() 
print "Shape", array_interface['shape'] 
print "Typestr", array_interface['typestr']

numpy_array = numpy.asarray(img)
print "Shape", numpy_array.shape
print "Data type", numpy_array.dtype

How it works...

The array interface or protocol lets us share data between array-like Python objects. Both NumPy and PIL provide such an interface.

See also

  • Using the buffer protocol in this chapter
..................Content has been hidden....................

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