[Numpy-discussion] Interfacing with PIL?

Christopher Barker Chris.Barker at noaa.gov
Wed Aug 30 15:15:15 EDT 2006


Tim Hochberg wrote:
> Johannes Loehnert wrote:
>>> I'm somewhat new to both libraries...is there any way to create a 2D
>>> array of pixel values from an image object from the Python Image
>>> Library? I'd like to do some arithmetic on the values.

the latest version of PIL (maybe not released yet) supports the array 
interface, so you may be able to do something like:

A = numpy.asarray(PIL_image)

see the PIL page:

http://effbot.org/zone/pil-changes-116.htm

where it says:

Changes from release 1.1.5 to 1.1.6
Added "fromarray" function, which takes an object implementing the NumPy 
array interface and creates a PIL Image from it. (from Travis Oliphant).

Added NumPy array interface support (__array_interface__) to the Image 
class (based on code by Travis Oliphant). This allows you to easily 
convert between PIL image memories and NumPy arrays:
import numpy, Image

i = Image.open('lena.jpg')
a = numpy.asarray(i) # a is readonly
i = Image.fromarray(a)

> On a related note, does anyone have a good recipe for converting a PIL 
> image to a wxPython image?

Does a PIL image support the buffer protocol? There will be a:

wx.ImageFromBuffer()

soon, and there is now;

wx.Image.SetDataBuffer()

if not, I think this will work:

I = wx.EmptyImage(width, height)
DataString = PIL_image.tostring()
I.SetDataBuffer(DataString)

This will only work if the PIL image is an 24 bit RGB image, of course. 
Just make sure to keep DataString around, so that the data buffer 
doesn't get deleted. wx.ImageFromBuffer() will do that foryou, but it's 
not available until 2.7 comes out.

Ideally, both PIL and wx will support the array interface, and we can 
just do:

I = wx.ImageFromArray(PIL_Image)

and not get any data copying as well.

Also, Robin has just added some methods to directly manipulate 
wxBitmaps, so you can use a numpy array as the data buffer for a 
wx.Bitmap. This can help prevent a lot of data copies. see a test here:

http://cvs.wxwidgets.org/viewcvs.cgi/wxWidgets/wxPython/demo/RawBitmapAccess.py?rev=1.3&content-type=text/vnd.viewcvs-markup

-Chris

-- 
Christopher Barker, Ph.D.
Oceanographer
                                     		
NOAA/OR&R/HAZMAT         (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov




More information about the NumPy-Discussion mailing list