""" pil2array ------------------------------------------------------------------- This module provides a link between Numeric arrays and PIL, 'Python Imaging Library', images. Its functions perform image file I/O (in formats supported by PIL) and displaying of images represented as Numeric arrays. The layout of these Numeric arrays follows the rules of the 'adimage' toolbox images. ------------------------------------------------------------------- readimage() -- Read an image from a file to a Numeric array. pil2array() -- Convert a PIL image to a Numeric array. """ # ===================================================================== # pil2array # ===================================================================== def pil2array(pil): """ - Purpose Convert a PIL image to a Numeric array. The array representing a RGB(A) image is formed by images stored sequencially: R-image, G-image, B-image and, optionally, Alpha-image. - Synopsis arr = pil2array(pil) - Input pil: The PIL image to convert. - Output arr: Numeric array representing the PIL image. """ import Numeric w, h = pil.size binary = 0 if pil.mode == '1': binary = 1 pil = pil.convert('L') if pil.mode == 'L': d = 1 ; shape = (h,w) elif pil.mode == 'P': if len(pil.palette.data) == 2*len(pil.palette.rawmode): binary = 1 pil = pil.convert('L') d = 1 ; shape = (h,w) else: pil = pil.convert('RGB') d = 3 ; shape = (h,w,d) elif pil.mode in ('RGB','YCbCr'): d = 3 ; shape = (h,w,d) elif pil.mode in ('RGBA','CMYK'): d = 4 ; shape = (h,w,d) else: raise TypeError, "Invalid or unimplemented PIL image mode '%s'" % pil.mode arr = Numeric.reshape(Numeric.fromstring(pil.tostring(), 'b', w*h*d), shape) if d > 1: arr = Numeric.swapaxes(Numeric.swapaxes(arr, 0, 2), 1, 2) if binary: arr = (arr > 0).astype('1') return arr # ===================================================================== # findImageFile # ===================================================================== def findImageFile(filename): import sys, os.path if not os.path.isfile(filename) and not os.path.isabs(filename): for a in sys.path: if os.path.isfile(os.path.join(a, filename)): filename = os.path.join(a, filename) break return filename # ===================================================================== # imageread # ===================================================================== def readimage(imagefile): import Image img = findImageFile(imagefile) arr = pil2array(Image.open(img)) return arr