[Image-SIG] Low level access

Aureli Soria Frisch aureli@ipk.fhg.de
Fri, 12 Jul 2002 10:42:26 +0200


Hi,

Also in my opinion the way through Numeric is the most appropriate. 
However with fromstring and tostring methods you will encounter some 
problems.

These functions (I got from the list and modify a bit) can facilitate the work:

import Numeric
import Image

def image2array(im,outputDim=3):

     if im.mode == "L":
         a = Numeric.fromstring(im.tostring(), Numeric.UnsignedInt8)
	bands=1
     elif im.mode == "F":
         a = Numeric.fromstring(im.tostring(), Numeric.Float32)
	bands=1
     elif (im.mode=='RGB')|(im.mode=='YCbCr'):
	a = Numeric.fromstring(im.tostring(), Numeric.UnsignedInt8)
	bands=3
     elif (im.mode=='RGBA')|(im.mode=='CMYK'):
	a = Numeric.fromstring(im.tostring(), Numeric.UnsignedInt8)
	bands=4
     else:
	 raise ValueError, im.mode+" mode not considered"
     #print "array now"
     #print a
     if outputDim==3:		#bands as vector in the third dimension
	    a.shape=(im.size[1],im.size[0],bands)
     elif outputDim==2:		#for images with 1 band (2D arrays)
	    a=Numeric.reshape(a,(im.size[1],im.size[0]))
     elif outputDim==1:		#for images with 1 band as flat array 
(1D arrays)
	    a=Numeric.reshape(a,(im.size[1]*im.size[0],))
     #print "change shape"
     #print a
     return a

def array2image(a):
     #print a.shape
     if len(a.shape)==3:
	b=()
	for i in range(a.shape[2]):
		#print a[:,:,i].shape
		b+=(array2image(a[:,:,i]),)
	#print b[0].size
	if a.shape[2]==3:
		#print "here shape 3",b
		#return b
		return Image.merge("RGB",b)
	elif a.shape[2]==1:
		#print "here shape 1",b
		return b[0]

     elif a.typecode() == Numeric.UnsignedInt8:
         mode = "L"
     elif a.typecode() == Numeric.Float32:
         mode = "F"
     else:
         raise ValueError, "unsupported image mode"
     return Image.fromstring(mode, (a.shape[1], a.shape[0]), 
a.astype(a.typecode()).tostring())

Best regards,
Aureli
-- 
#################################
Aureli Soria Frisch
Fraunhofer IPK
Dept. Pattern Recognition

post: Pascalstr. 8-9, 10587 Berlin, Germany
e-mail: aureli@ipk.fhg.de
fon: +49 30 39006-143
fax: +49 30 3917517
web: http://vision.fhg.de/~aureli/web-aureli_en.html
#################################