PIL-object to NumPy

Edward C. Jones edcjones at erols.com
Mon May 3 06:47:50 EDT 1999


Mads Andresen wrote:

> Hi,
>
> I'm using Python Image Library (PIL) and NumPy.
>
> I would like to open a image and make som imageprocessing on it. I would
> like to do the imageprocessing i NumPy, but I can't find out how to open af
> Image in NumPy??
>
> Q1: How do I open a image so I can use it with NumPy??
>
> Q2: If not(Q1) then: How do I convert a PIL-object to a NymPy-array???
>
> Mads Andresen, Odense, Denmark

I use the attached piece of code.

Ed Jones

-------------- next part --------------
#! /usr/bin/python

import Numeric, Image

# NumPy thinks in terms of matrices (r,c) starting at the upper left hand
# corner.
def printarray(array, width=4):
	rows, cols = array.shape
	print width * ' ',
	for c in range(cols):
		print '%*d' % (width, c),
	print
	for r in range(rows):
		print '%*d' % (width, r),
		for c in range(cols):
			print '%*d' % (width, array[r][c]),
		print
	print

# PIL thinks in terms of television rasters (x,y) starting at the upper left
# hand corner.
def printim(im, width=4):
	xsize, ysize = im.size
	print width * ' ',
	for x in range(xsize):
		print '%*d' % (width, x),
	print
	for y in range(ysize):
		print '%*d' % (width, y),
		for x in range(xsize):
			print '%*d' % (width, im.getpixel( (x, y) )),
		print
	print

def pil2numpy(im, typecode='b'):
	# tostring does something funny with '1' images (packs em tight).
        # For 'P' images, the image data is not pased through the palette.
	if im.mode != 'L' and im.mode != 'P':
		print 'im.mode must be "L" or "P"'
		raise 'terminate'
	xsize = im.size[0]
	ysize = im.size[1]
	m = im.tostring()
	t = Numeric.fromstring(m, 'b')
        tt = Numeric.asarray(t, typecode)
	# Note that ysize is first:
	return Numeric.reshape(tt, (ysize, xsize))

# Convert a 2-d array with typecode 'b' to an image with mode 'L'
def numpy2pil(arr):
	rows = arr.shape[0]
	cols = arr.shape[1]
	m = arr.tostring()
	out = Image.new('L', (cols, rows) )
	out.fromstring(m)
	return out


More information about the Python-list mailing list