[Image-SIG] Inter-converting images and Numeric arrays
Charles G Waldman
cgw@pgt.com
Sat, 4 Jul 1998 11:42:31 -0400 (EDT)
I'm working on some image analysis software. For what I'm doing it's
much more efficient to have the pixel data in a Numeric array, rather
than a PIL Image, to avoid the overhead of lots of getpixel/setpixel
calls.
I've found it's pretty straightforward to inter-convert images and
arrays using fromstring/tostring.... but I have a few questions:
1: Shouldn't PIL support conversion directly to/from arrays? Using
the intermediate string works, but seems like a hack...
2: Seems that if I start with an Array, make an Image, then convert
back, the y-axis is inverted. Is this a feature or a bug?
Example program:
#!/usr/local/bin/python
import Image,ImagePalette
from Numeric import *
a = zeros((4,4),'b')
for y in range(0,4):
for x in range(0,4):
a[x,y]=x*10+y
print "before:"
print a
i1 = Image.fromstring("P",(4,4),a.tostring())
a1 = fromstring(i1.tostring(),'b')
a1.shape=(4,4)
print "after:"
print a1
And its output
>>>
before:
[[ 0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]]
after:
[[30 31 32 33]
[20 21 22 23]
[10 11 12 13]
[ 0 1 2 3]]
>>>