[Numpy-discussion] Quicker image transfer, tobuffer?

Travis Oliphant oliphant.travis at ieee.org
Tue Jul 11 14:37:15 CDT 2006


Here is a simple approach to allowing the PIL to export the array 
interface.

This allows NumPy to create a suitable array from a PIL image very easily:


At the top of Image.py add the following

if sys.byteorder == 'little':
     _ENDIAN = '<'
else:
     _ENDIAN = '>'

_MODE_CONV = {

     # official modes
     "1": ('|b1', None),
     "L": ('|u1', None),
     "I": ('%si4' % _ENDIAN, None),
     "F": ('%sf4' % _ENDIAN, None),
     "P": ('|u1', None),
     "RGB": ('|u1', 3),
     "RGBX": ('|u1', 4),
     "RGBA": ('|u1', 4),
     "CMYK": ('|u1', 4),
     "YCbCr": ('|u1', 4),

     # Experimental modes include I;16, I;16B, RGBa, BGR;15,
     # and BGR;24.  Use these modes only if you know exactly
     # what you're doing...

}

def _conv_type_shape(im):
     shape = im.size
     typ, extra = _MODE_CONV[im.mode]
     if extra is None:
         return shape, typ
     shape += (extra,)
     return shape, typ



In the Image class structure add

     def __get_array_interface__(self):
         new = {}
         shape, typestr = _conv_type_shape(self)
         new['shape'] = shape
         new['typestr'] = typestr
         new['data'] = self.tostring()
         return new

     __array_interface__ = property(__get_array_interface__, None,
doc="array interface")



With this addition you can then do

import Image, numpy

im = Image.open('lena.jpg')
a = numpy.asarray(im)

and you will get a suitable read-only array pointing to the string 
produced by tostring.


This would be a nice thing to add to the PIL.

-Travis Oliphant






More information about the Numpy-discussion mailing list