[Image-SIG] Image to matrix
Brian Blais
bblais at bryant.edu
Tue Jun 5 12:34:01 CEST 2007
Alex Torquato S. Carneiro wrote:
> I'm doing a project in Python. It's a capture and process a image, I'm
> using PIL for images and scipy (together numpy) for processing, about
> fft, filter, etc..
> I'm needing to convert a image in a matrix type, can anyone help me?
>
> Thanks.
> Alex.
>
This is what I've used. I started with:
http://effbot.org/zone/pil-numpy.htm
which uses the old numeric package, and modified it slightly for numpy, so it looks like:
import numpy, Image
def image2array(im):
if im.mode not in ("L", "F"):
raise ValueError, "can only convert single-layer images"
if im.mode == "L":
a = numpy.fromstring(im.tostring(), numpy.UInt8)
else:
a = numpy.fromstring(im.tostring(), numpy.Float32)
a.shape = im.size[1], im.size[0]
return a
def array2image(a):
if a.dtype.name == 'uint8':
mode = "L"
elif a.dtype.name == 'float32':
mode = "F"
elif a.dtype.name == 'float64':
a=a.astype('float32')
mode = "F"
else:
raise ValueError, "unsupported image mode %s" % a.dtype.name
return Image.fromstring(mode, (a.shape[1], a.shape[0]), a.tostring())
seems to work!
bb
--
-----------------
bblais at bryant.edu
http://web.bryant.edu/~bblais
More information about the Image-SIG
mailing list