[Numpy-discussion] Images and numpy

Robert Kern robert.kern@gmail....
Sat Oct 18 23:23:13 CDT 2008


On Sat, Oct 18, 2008 at 23:07, Lane Brooks <lbrooks@mit.edu> wrote:
> What are the preferred ways to get images, like jpgs and pngs, from disk
> into a numpy array and from a numpy array to disk?
>
> I did some google searches and found a PEP thread where Travis was
> proposing an extended buffer protocol that would make for easier
> interoperability with libraries such as PIL.  Did that materialize?

Yes. There are two protocols, a Python level one, and a C level one.
Python 2.6 is the first release where the C one is standard. Recent
PILs support the Python level one.


In [9]: import Image

In [10]: img = Image.open('icon.png')

In [11]: import numpy

In [12]: numpy.asarray(img)
Out[12]:
array([[[  0,   0,   0,   0],
        [  0,   0,   0,   0],
        [  0,   0,   0,   0],
        ...,
        [  0,   0,   0,   0],
        [  0,   0,   0,   0],
        [  0,   0,   0,   0]],
...

In [14]: img2 = Image.fromarray(Out[12])

In [15]: img2
Out[15]: <Image.Image instance at 0x1c0baa8>

In [16]: img2.size
Out[16]: (48, 48)


You may also want to look at scipy's scipy.misc.pilutil module. It
doesn't use these newer APIs, but it does have extra functionality
like scaling float arrays to [0..255] to write out to PNGs and such.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the Numpy-discussion mailing list