PIL-object to NumPy
Roger Burnham
roger.burnham at gte.net
Tue May 4 09:59:50 EDT 1999
On Tue, 4 May 1999 07:52:31 +0200, "Mads Andresen" <laura at post.cybercity.dk>
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
>
>
Mads,
Heres a little demo I put together for a co-worker with the same questions:
import Image
import Numeric
def imageToArray(img, type=Numeric.UnsignedInt8):
'''Given an 8bit Image object, return an Array object.
'''
arr = Numeric.array(img.tostring('raw', img.mode, 0, -1)).astype(type)
arr.shape = img.size[1], img.size[0]
return arr
def arrayToImage(arr, type='L'):
'''Given an Array object, return an 8bit Image object.
'''
height, width = arr.shape
img = Image.new(type, (width, height))
img.fromstring(arr.tostring(), 'raw', type, 0, -1)
return img
if __name__ == '__main__':
import os
import ImageChops
os.chdir('C:/CRI/Bin/Test')
# 8bit gray-scale
# test img->arr->img
img = Image.open('test_8bit.bmp')
arr = imageToArray(img)
testImg = arrayToImage(arr, 'L')
diffImg = ImageChops.difference(img, testImg)
for i in range(diffImg.size[0]):
for j in range(diffImg.size[1]):
val = diffImg.getpixel((i,j))
if val:
raise ValueError('Pixel %d,%d = %d, should be zero!'
% (i,j,val))
# test arr->img->arr
def func(i,j):
return (i*j + i + j) % 256
arr = Numeric.fromfunction(func, (128, 256)).astype(Numeric.UnsignedInt8)
img = arrayToImage(arr, 'L')
testArr = imageToArray(img)
diffArr = arr - testArr
for i in range(diffArr.shape[0]):
for j in range(diffArr.shape[1]):
if diffArr[i,j]:
raise ValueError('Element %d,%d = %d, should be zero!'
% (i,j,diffArr[i,j]))
Cheers,
Roger Burnham
Cambridge Research & Instrumentation
rburnham at cri-inc.com
http://www.cri-inc.com/
http://starship.python.net/crew/roger/
PGP Key: http://www.nai.com/default_pgp.asp
PGP Fingerprint: 5372 729A 9557 5F36 177F 084A 6C64 BE27 0BC4 CF2D
More information about the Python-list
mailing list