2
# The Python Imaging Library.
5
# the Image class wrapper
7
# partial release history:
8
# 1995-09-09 fl Created
9
# 1996-03-11 fl PIL release 0.0 (proof of concept)
10
# 1996-04-30 fl PIL release 0.1b1
11
# 1999-07-28 fl PIL release 1.0 final
12
# 2000-06-07 fl PIL release 1.1
13
# 2000-10-20 fl PIL release 1.1.1
14
# 2001-05-07 fl PIL release 1.1.2
15
# 2002-03-15 fl PIL release 1.1.3
16
# 2003-05-10 fl PIL release 1.1.4
17
# 2005-03-28 fl PIL release 1.1.5
18
# 2006-12-02 fl PIL release 1.1.6
19
# 2009-11-15 fl PIL release 1.1.7
21
# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
22
# Copyright (c) 1995-2009 by Fredrik Lundh.
24
# See the README file for information on usage and redistribution.
34
class _imaging_not_installed:
36
def __getattr__(self, id):
37
raise ImportError("The _imaging C module is not installed")
40
# give Tk a chance to set up the environment, in case we're
41
# using an _imaging module linked against libtcl/libtk (use
42
# __import__ to hide this from naive packagers; we don't really
43
# depend on Tk unless ImageTk is used, and that module already
50
# If the _imaging C module is not present, you can still use
51
# the "open" function to identify files, but you cannot load
52
# them. Note that other modules should not refer to _imaging
53
# directly; import Image and use the Image.core variable instead.
54
import _imaging as core
55
except ImportError, v:
56
core = _imaging_not_installed()
57
if str(v)[:20] == "Module use of python" and warnings:
58
# The _imaging C module is present, but not compiled for
59
# the right version (windows only). Print a warning, if
62
"The _imaging extension was built for another version "
63
"of Python; most PIL functions will be disabled",
70
import os, string, sys
73
from types import IntType, StringType, TupleType
76
UnicodeStringType = type(unicode(""))
78
# (Internal) Checks if an object is a string. If the current
79
# Python version supports Unicode, this checks for both 8-bit
80
# and Unicode strings.
82
return isinstance(t, StringType) or isinstance(t, UnicodeStringType)
85
return isinstance(t, StringType)
88
# (Internal) Checks if an object is a tuple.
91
return isinstance(t, TupleType)
94
# (Internal) Checks if an object is an image object.
97
return hasattr(t, "im")
100
# (Internal) Checks if an object is a string, and that it points to a
104
return isStringType(f) and os.path.isdir(f)
106
from operator import isNumberType, isSequenceType
114
# Constants (also defined in _imagingmodule.c!)
135
ANTIALIAS = 1 # 3-lobed lanczos
136
LINEAR = BILINEAR = 2
142
ORDERED = 1 # Not yet implemented
143
RASTERIZE = 2 # Not yet implemented
144
FLOYDSTEINBERG = 3 # default
146
# palettes/quantizers
155
# --------------------------------------------------------------------
164
# --------------------------------------------------------------------
165
# Modes supported by this version
168
# NOTE: this table will be removed in future versions. use
169
# getmode* functions or ImageMode descriptors instead.
172
"1": ("L", "L", ("1",)),
173
"L": ("L", "L", ("L",)),
174
"I": ("L", "I", ("I",)),
175
"F": ("L", "F", ("F",)),
176
"P": ("RGB", "L", ("P",)),
177
"RGB": ("RGB", "L", ("R", "G", "B")),
178
"RGBX": ("RGB", "L", ("R", "G", "B", "X")),
179
"RGBA": ("RGB", "L", ("R", "G", "B", "A")),
180
"CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
181
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
183
# Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
184
# BGR;24. Use these modes only if you know exactly what you're
190
byteorder = sys.byteorder
191
except AttributeError:
193
if struct.unpack("h", "\0\1")[0] == 1:
198
if byteorder == 'little':
205
"1": ('|b1', None), # broken
207
"I": (_ENDIAN + 'i4', None),
208
"F": (_ENDIAN + 'f4', None),
217
def _conv_type_shape(im):
218
shape = im.size[1], im.size[0]
219
typ, extra = _MODE_CONV[im.mode]
223
return shape+(extra,), typ
226
MODES = _MODEINFO.keys()
229
# raw modes that may be memory mapped. NOTE: if you change this, you
230
# may have to modify the stride calculation in map.c too!
231
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
234
# Gets the "base" mode for given mode. This function returns "L" for
235
# images that contain grayscale data, and "RGB" for images that
236
# contain color data.
238
# @param mode Input mode.
239
# @return "L" or "RGB".
240
# @exception KeyError If the input mode was not a standard mode.
242
def getmodebase(mode):
243
return ImageMode.getmode(mode).basemode
246
# Gets the storage type mode. Given a mode, this function returns a
247
# single-layer mode suitable for storing individual bands.
249
# @param mode Input mode.
250
# @return "L", "I", or "F".
251
# @exception KeyError If the input mode was not a standard mode.
253
def getmodetype(mode):
254
return ImageMode.getmode(mode).basetype
257
# Gets a list of individual band names. Given a mode, this function
258
# returns a tuple containing the names of individual bands (use
259
# {@link #getmodetype} to get the mode used to store each individual
262
# @param mode Input mode.
263
# @return A tuple containing band names. The length of the tuple
264
# gives the number of bands in an image of the given mode.
265
# @exception KeyError If the input mode was not a standard mode.
267
def getmodebandnames(mode):
268
return ImageMode.getmode(mode).bands
271
# Gets the number of individual bands for this mode.
273
# @param mode Input mode.
274
# @return The number of bands in this mode.
275
# @exception KeyError If the input mode was not a standard mode.
277
def getmodebands(mode):
278
return len(ImageMode.getmode(mode).bands)
280
# --------------------------------------------------------------------
286
# Explicitly loads standard file format drivers.
289
"Load standard file format drivers."
292
if _initialized >= 1:
296
import BmpImagePlugin
300
import GifImagePlugin
304
import JpegImagePlugin
308
import PpmImagePlugin
312
import PngImagePlugin
316
# import TiffImagePlugin
317
# except ImportError:
323
# Explicitly initializes the Python Imaging Library. This function
324
# loads all available file format drivers.
327
"Load all file format drivers."
330
if _initialized >= 2:
335
directories = sys.path
338
directories = directories + [os.path.dirname(__file__)]
342
# only check directories (including current, if present in the path)
343
for directory in filter(isDirectory, directories):
344
fullpath = os.path.abspath(directory)
345
if visited.has_key(fullpath):
347
for file in os.listdir(directory):
348
if file[-14:] == "ImagePlugin.py":
349
f, e = os.path.splitext(file)
351
sys.path.insert(0, directory)
353
__import__(f, globals(), locals(), [])
358
print "Image: failed to import",
359
print f, ":", sys.exc_value
360
visited[fullpath] = None
366
# --------------------------------------------------------------------
367
# Codec factories (used by tostring/fromstring and ImageFile.load)
369
def _getdecoder(mode, decoder_name, args, extra=()):
374
elif not isTupleType(args):
379
decoder = getattr(core, decoder_name + "_decoder")
380
# print decoder, (mode,) + args + extra
381
return apply(decoder, (mode,) + args + extra)
382
except AttributeError:
383
raise IOError("decoder %s not available" % decoder_name)
385
def _getencoder(mode, encoder_name, args, extra=()):
390
elif not isTupleType(args):
395
encoder = getattr(core, encoder_name + "_encoder")
396
# print encoder, (mode,) + args + extra
397
return apply(encoder, (mode,) + args + extra)
398
except AttributeError:
399
raise IOError("encoder %s not available" % encoder_name)
402
# --------------------------------------------------------------------
403
# Simple expression analyzer
406
def __init__(self, data): self.data = data
407
def __coerce__(self, other): return self, _E(other)
408
def __add__(self, other): return _E((self.data, "__add__", other.data))
409
def __mul__(self, other): return _E((self.data, "__mul__", other.data))
411
def _getscaleoffset(expr):
413
data = expr(_E(stub)).data
415
(a, b, c) = data # simplified syntax
416
if (a is stub and b == "__mul__" and isNumberType(c)):
418
if (a is stub and b == "__add__" and isNumberType(c)):
420
except TypeError: pass
422
((a, b, c), d, e) = data # full syntax
423
if (a is stub and b == "__mul__" and isNumberType(c) and
424
d == "__add__" and isNumberType(e)):
426
except TypeError: pass
427
raise ValueError("illegal expression")
430
# --------------------------------------------------------------------
431
# Implementation wrapper
434
# This class represents an image object. To create Image objects, use
435
# the appropriate factory functions. There's hardly ever any reason
436
# to call the Image constructor directly.
445
format_description = None
448
# FIXME: take "new" parameters / other image?
449
# FIXME: turn mode and size into delegating properties?
455
self.category = NORMAL
463
new.palette = self.palette
465
new.palette = ImagePalette.ImagePalette()
467
new.info = self.info.copy()
468
except AttributeError:
469
# fallback (pre-1.5.2)
471
for k, v in self.info:
475
_makeself = _new # compatibility
479
self.im = self.im.copy()
482
def _dump(self, file=None, format=None):
485
file = tempfile.mktemp()
487
if not format or format == "PPM":
488
self.im.save_ppm(file)
490
file = file + "." + format
491
self.save(file, format)
495
return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
496
self.__class__.__module__, self.__class__.__name__,
497
self.mode, self.size[0], self.size[1],
501
def __getattr__(self, name):
502
if name == "__array_interface__":
503
# numpy array interface support
505
shape, typestr = _conv_type_shape(self)
507
new['typestr'] = typestr
508
new['data'] = self.tostring()
510
raise AttributeError(name)
513
# Returns a string containing pixel data.
515
# @param encoder_name What encoder to use. The default is to
516
# use the standard "raw" encoder.
517
# @param *args Extra arguments to the encoder.
518
# @return An 8-bit string.
520
def tostring(self, encoder_name="raw", *args):
521
"Return image as a binary string"
523
# may pass tuple instead of argument list
524
if len(args) == 1 and isTupleType(args[0]):
527
if encoder_name == "raw" and args == ():
533
e = _getencoder(self.mode, encoder_name, args)
536
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
540
l, s, d = e.encode(bufsize)
545
raise RuntimeError("encoder error %d in tostring" % s)
547
return string.join(data, "")
550
# Returns the image converted to an X11 bitmap. This method
551
# only works for mode "1" images.
553
# @param name The name prefix to use for the bitmap variables.
554
# @return A string containing an X11 bitmap.
555
# @exception ValueError If the mode is not "1"
557
def tobitmap(self, name="image"):
558
"Return image as an XBM bitmap"
562
raise ValueError("not a bitmap")
563
data = self.tostring("xbm")
564
return string.join(["#define %s_width %d\n" % (name, self.size[0]),
565
"#define %s_height %d\n"% (name, self.size[1]),
566
"static char %s_bits[] = {\n" % name, data, "};"], "")
569
# Loads this image with pixel data from a string.
571
# This method is similar to the {@link #fromstring} function, but
572
# loads data into this image instead of creating a new image
575
def fromstring(self, data, decoder_name="raw", *args):
576
"Load data to image from binary string"
578
# may pass tuple instead of argument list
579
if len(args) == 1 and isTupleType(args[0]):
583
if decoder_name == "raw" and args == ():
587
d = _getdecoder(self.mode, decoder_name, args)
592
raise ValueError("not enough image data")
594
raise ValueError("cannot decode image data")
597
# Allocates storage for the image and loads the pixel data. In
598
# normal cases, you don't need to call this method, since the
599
# Image class automatically loads an opened image when it is
600
# accessed for the first time.
602
# @return An image access object.
605
"Explicitly load pixel data."
606
if self.im and self.palette and self.palette.dirty:
608
apply(self.im.putpalette, self.palette.getdata())
609
self.palette.dirty = 0
610
self.palette.mode = "RGB"
611
self.palette.rawmode = None
612
if self.info.has_key("transparency"):
613
self.im.putpalettealpha(self.info["transparency"], 0)
614
self.palette.mode = "RGBA"
616
return self.im.pixel_access(self.readonly)
619
# Verifies the contents of a file. For data read from a file, this
620
# method attempts to determine if the file is broken, without
621
# actually decoding the image data. If this method finds any
622
# problems, it raises suitable exceptions. If you need to load
623
# the image after using this method, you must reopen the image
627
"Verify file contents."
631
# Returns a converted copy of this image. For the "P" mode, this
632
# method translates pixels through the palette. If mode is
633
# omitted, a mode is chosen so that all information in the image
634
# and the palette can be represented without a palette.
636
# The current version supports all possible conversions between
637
# "L", "RGB" and "CMYK."
639
# When translating a colour image to black and white (mode "L"),
640
# the library uses the ITU-R 601-2 luma transform:
642
# <b>L = R * 299/1000 + G * 587/1000 + B * 114/1000</b>
644
# When translating a greyscale image into a bilevel image (mode
645
# "1"), all non-zero values are set to 255 (white). To use other
646
# thresholds, use the {@link #Image.point} method.
648
# @def convert(mode, matrix=None, **options)
649
# @param mode The requested mode.
650
# @param matrix An optional conversion matrix. If given, this
651
# should be 4- or 16-tuple containing floating point values.
652
# @param options Additional options, given as keyword arguments.
653
# @keyparam dither Dithering method, used when converting from
655
# Available methods are NONE or FLOYDSTEINBERG (default).
656
# @keyparam palette Palette to use when converting from mode "RGB"
657
# to "P". Available palettes are WEB or ADAPTIVE.
658
# @keyparam colors Number of colors to use for the ADAPTIVE palette.
660
# @return An Image object.
662
def convert(self, mode=None, data=None, dither=None,
663
palette=WEB, colors=256):
664
"Convert to other pixel format"
667
# determine default mode
671
mode = self.palette.mode
681
if mode not in ("L", "RGB"):
682
raise ValueError("illegal conversion")
683
im = self.im.convert_matrix(mode, data)
686
if mode == "P" and palette == ADAPTIVE:
687
im = self.im.quantize(colors)
690
# colourspace conversion
692
dither = FLOYDSTEINBERG
695
im = self.im.convert(mode, dither)
698
# normalize source image and try again
699
im = self.im.convert(getmodebase(self.mode))
700
im = im.convert(mode, dither)
702
raise ValueError("illegal conversion")
706
def quantize(self, colors=256, method=0, kmeans=0, palette=None):
710
# 1 = maximum coverage
712
# NOTE: this functionality will be moved to the extended
713
# quantizer interface in a later version of PIL.
718
# use palette from reference image
720
if palette.mode != "P":
721
raise ValueError("bad mode for palette image")
722
if self.mode != "RGB" and self.mode != "L":
724
"only RGB or L mode images can be quantized to a palette"
726
im = self.im.convert("P", 1, palette.im)
727
return self._makeself(im)
729
im = self.im.quantize(colors, method, kmeans)
733
# Copies this image. Use this method if you wish to paste things
734
# into an image, but still retain the original.
736
# @return An Image object.
746
# Returns a rectangular region from this image. The box is a
747
# 4-tuple defining the left, upper, right, and lower pixel
750
# This is a lazy operation. Changes to the source image may or
751
# may not be reflected in the cropped image. To break the
752
# connection, call the {@link #Image.load} method on the cropped
755
# @param The crop rectangle, as a (left, upper, right, lower)-tuple.
756
# @return An Image object.
758
def crop(self, box=None):
759
"Crop region from image"
766
return _ImageCrop(self, box)
769
# Configures the image file loader so it returns a version of the
770
# image that as closely as possible matches the given mode and
771
# size. For example, you can use this method to convert a colour
772
# JPEG to greyscale while loading it, or to extract a 128x192
773
# version from a PCD file.
775
# Note that this method modifies the Image object in place. If
776
# the image has already been loaded, this method has no effect.
778
# @param mode The requested mode.
779
# @param size The requested size.
781
def draft(self, mode, size):
782
"Configure image decoder"
786
def _expand(self, xmargin, ymargin=None):
790
return self._new(self.im.expand(xmargin, ymargin, 0))
793
# Filters this image using the given filter. For a list of
794
# available filters, see the <b>ImageFilter</b> module.
796
# @param filter Filter kernel.
797
# @return An Image object.
800
def filter(self, filter):
801
"Apply environment filter to image"
807
if not hasattr(filter, "filter"):
808
raise TypeError("filter argument should be ImageFilter.Filter instance or class")
810
if self.im.bands == 1:
811
return self._new(filter.filter(self.im))
812
# fix to handle multiband images since _imaging doesn't
814
for c in range(self.im.bands):
815
ims.append(self._new(filter.filter(self.im.getband(c))))
816
return merge(self.mode, ims)
819
# Returns a tuple containing the name of each band in this image.
820
# For example, <b>getbands</b> on an RGB image returns ("R", "G", "B").
822
# @return A tuple containing band names.
827
return ImageMode.getmode(self.mode).bands
830
# Calculates the bounding box of the non-zero regions in the
833
# @return The bounding box is returned as a 4-tuple defining the
834
# left, upper, right, and lower pixel coordinate. If the image
835
# is completely empty, this method returns None.
838
"Get bounding box of actual data (non-zero pixels) in image"
841
return self.im.getbbox()
844
# Returns a list of colors used in this image.
846
# @param maxcolors Maximum number of colors. If this number is
847
# exceeded, this method returns None. The default limit is
849
# @return An unsorted list of (count, pixel) values.
851
def getcolors(self, maxcolors=256):
852
"Get colors from image, up to given limit"
855
if self.mode in ("1", "L", "P"):
856
h = self.im.histogram()
860
out.append((h[i], i))
861
if len(out) > maxcolors:
864
return self.im.getcolors(maxcolors)
867
# Returns the contents of this image as a sequence object
868
# containing pixel values. The sequence object is flattened, so
869
# that values for line one follow directly after the values of
870
# line zero, and so on.
872
# Note that the sequence object returned by this method is an
873
# internal PIL data type, which only supports certain sequence
874
# operations. To convert it to an ordinary sequence (e.g. for
875
# printing), use <b>list(im.getdata())</b>.
877
# @param band What band to return. The default is to return
878
# all bands. To return a single band, pass in the index
879
# value (e.g. 0 to get the "R" band from an "RGB" image).
880
# @return A sequence-like object.
882
def getdata(self, band = None):
883
"Get image data as sequence object."
887
return self.im.getband(band)
888
return self.im # could be abused
891
# Gets the the minimum and maximum pixel values for each band in
894
# @return For a single-band image, a 2-tuple containing the
895
# minimum and maximum pixel value. For a multi-band image,
896
# a tuple containing one 2-tuple for each band.
898
def getextrema(self):
902
if self.im.bands > 1:
904
for i in range(self.im.bands):
905
extrema.append(self.im.getband(i).getextrema())
906
return tuple(extrema)
907
return self.im.getextrema()
910
# Returns a PyCObject that points to the internal image memory.
912
# @return A PyCObject object.
915
"Get PyCObject pointer to internal image memory"
922
# Returns the image palette as a list.
924
# @return A list of color values [r, g, b, ...], or None if the
925
# image has no palette.
927
def getpalette(self):
928
"Get palette contents."
932
return map(ord, self.im.getpalette())
934
return None # no palette
938
# Returns the pixel value at a given position.
940
# @param xy The coordinate, given as (x, y).
941
# @return The pixel value. If the image is a multi-layer image,
942
# this method returns a tuple.
944
def getpixel(self, xy):
948
return self.im.getpixel(xy)
951
# Returns the horizontal and vertical projection.
953
# @return Two sequences, indicating where there are non-zero
954
# pixels along the X-axis and the Y-axis, respectively.
956
def getprojection(self):
957
"Get projection to x and y axes"
960
x, y = self.im.getprojection()
961
return map(ord, x), map(ord, y)
964
# Returns a histogram for the image. The histogram is returned as
965
# a list of pixel counts, one for each pixel value in the source
966
# image. If the image has more than one band, the histograms for
967
# all bands are concatenated (for example, the histogram for an
968
# "RGB" image contains 768 values).
970
# A bilevel image (mode "1") is treated as a greyscale ("L") image
973
# If a mask is provided, the method returns a histogram for those
974
# parts of the image where the mask image is non-zero. The mask
975
# image must have the same size as the image, and be either a
976
# bi-level image (mode "1") or a greyscale image ("L").
978
# @def histogram(mask=None)
979
# @param mask An optional mask.
980
# @return A list containing pixel counts.
982
def histogram(self, mask=None, extrema=None):
983
"Take histogram of image"
988
return self.im.histogram((0, 0), mask.im)
989
if self.mode in ("I", "F"):
991
extrema = self.getextrema()
992
return self.im.histogram(extrema)
993
return self.im.histogram()
996
# (Deprecated) Returns a copy of the image where the data has been
997
# offset by the given distances. Data wraps around the edges. If
998
# yoffset is omitted, it is assumed to be equal to xoffset.
1000
# This method is deprecated. New code should use the <b>offset</b>
1001
# function in the <b>ImageChops</b> module.
1003
# @param xoffset The horizontal distance.
1004
# @param yoffset The vertical distance. If omitted, both
1005
# distances are set to the same value.
1006
# @return An Image object.
1008
def offset(self, xoffset, yoffset=None):
1009
"(deprecated) Offset image in horizontal and/or vertical direction"
1012
"'offset' is deprecated; use 'ImageChops.offset' instead",
1013
DeprecationWarning, stacklevel=2
1016
return ImageChops.offset(self, xoffset, yoffset)
1019
# Pastes another image into this image. The box argument is either
1020
# a 2-tuple giving the upper left corner, a 4-tuple defining the
1021
# left, upper, right, and lower pixel coordinate, or None (same as
1022
# (0, 0)). If a 4-tuple is given, the size of the pasted image
1023
# must match the size of the region.
1025
# If the modes don't match, the pasted image is converted to the
1026
# mode of this image (see the {@link #Image.convert} method for
1029
# Instead of an image, the source can be a integer or tuple
1030
# containing pixel values. The method then fills the region
1031
# with the given colour. When creating RGB images, you can
1032
# also use colour strings as supported by the ImageColor module.
1034
# If a mask is given, this method updates only the regions
1035
# indicated by the mask. You can use either "1", "L" or "RGBA"
1036
# images (in the latter case, the alpha band is used as mask).
1037
# Where the mask is 255, the given image is copied as is. Where
1038
# the mask is 0, the current value is preserved. Intermediate
1039
# values can be used for transparency effects.
1041
# Note that if you paste an "RGBA" image, the alpha band is
1042
# ignored. You can work around this by using the same image as
1043
# both source image and mask.
1045
# @param im Source image or pixel value (integer or tuple).
1046
# @param box An optional 4-tuple giving the region to paste into.
1047
# If a 2-tuple is used instead, it's treated as the upper left
1048
# corner. If omitted or None, the source is pasted into the
1049
# upper left corner.
1051
# If an image is given as the second argument and there is no
1052
# third, the box defaults to (0, 0), and the second argument
1053
# is interpreted as a mask image.
1054
# @param mask An optional mask image.
1055
# @return An Image object.
1057
def paste(self, im, box=None, mask=None):
1058
"Paste other image into region"
1060
if isImageType(box) and mask is None:
1061
# abbreviated paste(im, mask) syntax
1062
mask = box; box = None
1066
box = (0, 0) + self.size
1069
# lower left corner given; get size from image or mask
1072
elif isImageType(mask):
1075
# FIXME: use self.size here?
1077
"cannot determine region size; use 4-item box"
1079
box = box + (box[0]+size[0], box[1]+size[1])
1081
if isStringType(im):
1083
im = ImageColor.getcolor(im, self.mode)
1085
elif isImageType(im):
1087
if self.mode != im.mode:
1088
if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
1089
# should use an adapter for this!
1090
im = im.convert(self.mode)
1099
self.im.paste(im, box, mask.im)
1101
self.im.paste(im, box)
1104
# Maps this image through a lookup table or function.
1106
# @param lut A lookup table, containing 256 values per band in the
1107
# image. A function can be used instead, it should take a single
1108
# argument. The function is called once for each possible pixel
1109
# value, and the resulting table is applied to all bands of the
1111
# @param mode Output mode (default is same as input). In the
1112
# current version, this can only be used if the source image
1113
# has mode "L" or "P", and the output has mode "1".
1114
# @return An Image object.
1116
def point(self, lut, mode=None):
1117
"Map image through lookup table"
1121
if isinstance(lut, ImagePointHandler):
1122
return lut.point(self)
1124
if not isSequenceType(lut):
1125
# if it isn't a list, it should be a function
1126
if self.mode in ("I", "I;16", "F"):
1127
# check if the function can be used with point_transform
1128
scale, offset = _getscaleoffset(lut)
1129
return self._new(self.im.point_transform(scale, offset))
1130
# for other modes, convert the function to a table
1131
lut = map(lut, range(256)) * self.im.bands
1133
if self.mode == "F":
1134
# FIXME: _imaging returns a confusing error message for this case
1135
raise ValueError("point operation not supported for this mode")
1137
return self._new(self.im.point(lut, mode))
1140
# Adds or replaces the alpha layer in this image. If the image
1141
# does not have an alpha layer, it's converted to "LA" or "RGBA".
1142
# The new layer must be either "L" or "1".
1144
# @param im The new alpha layer. This can either be an "L" or "1"
1145
# image having the same size as this image, or an integer or
1146
# other color value.
1148
def putalpha(self, alpha):
1155
if self.mode not in ("LA", "RGBA"):
1156
# attempt to promote self to a matching alpha mode
1158
mode = getmodebase(self.mode) + "A"
1160
self.im.setmode(mode)
1161
except (AttributeError, ValueError):
1162
# do things the hard way
1163
im = self.im.convert(mode)
1164
if im.mode not in ("LA", "RGBA"):
1165
raise ValueError # sanity check
1167
self.mode = self.im.mode
1168
except (KeyError, ValueError):
1169
raise ValueError("illegal image mode")
1171
if self.mode == "LA":
1176
if isImageType(alpha):
1178
if alpha.mode not in ("1", "L"):
1179
raise ValueError("illegal image mode")
1181
if alpha.mode == "1":
1182
alpha = alpha.convert("L")
1186
self.im.fillband(band, alpha)
1187
except (AttributeError, ValueError):
1188
# do things the hard way
1189
alpha = new("L", self.size, alpha)
1193
self.im.putband(alpha.im, band)
1196
# Copies pixel data to this image. This method copies data from a
1197
# sequence object into the image, starting at the upper left
1198
# corner (0, 0), and continuing until either the image or the
1199
# sequence ends. The scale and offset values are used to adjust
1200
# the sequence values: <b>pixel = value*scale + offset</b>.
1202
# @param data A sequence object.
1203
# @param scale An optional scale value. The default is 1.0.
1204
# @param offset An optional offset value. The default is 0.0.
1206
def putdata(self, data, scale=1.0, offset=0.0):
1207
"Put data from a sequence object into an image."
1213
self.im.putdata(data, scale, offset)
1216
# Attaches a palette to this image. The image must be a "P" or
1217
# "L" image, and the palette sequence must contain 768 integer
1218
# values, where each group of three values represent the red,
1219
# green, and blue values for the corresponding pixel
1220
# index. Instead of an integer sequence, you can use an 8-bit
1223
# @def putpalette(data)
1224
# @param data A palette sequence (either a list or a string).
1226
def putpalette(self, data, rawmode="RGB"):
1227
"Put palette data into an image."
1229
if self.mode not in ("L", "P"):
1230
raise ValueError("illegal image mode")
1232
if isinstance(data, ImagePalette.ImagePalette):
1233
palette = ImagePalette.raw(data.rawmode, data.palette)
1235
if not isStringType(data):
1236
data = string.join(map(chr, data), "")
1237
palette = ImagePalette.raw(rawmode, data)
1239
self.palette = palette
1240
self.palette.mode = "RGB"
1241
self.load() # install new palette
1244
# Modifies the pixel at the given position. The colour is given as
1245
# a single numerical value for single-band images, and a tuple for
1246
# multi-band images.
1248
# Note that this method is relatively slow. For more extensive
1249
# changes, use {@link #Image.paste} or the <b>ImageDraw</b> module
1252
# @param xy The pixel coordinate, given as (x, y).
1253
# @param value The pixel value.
1255
# @see #Image.putdata
1258
def putpixel(self, xy, value):
1265
return self.im.putpixel(xy, value)
1268
# Returns a resized copy of this image.
1270
# @def resize(size, filter=NEAREST)
1271
# @param size The requested size in pixels, as a 2-tuple:
1273
# @param filter An optional resampling filter. This can be
1274
# one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
1275
# (linear interpolation in a 2x2 environment), <b>BICUBIC</b>
1276
# (cubic spline interpolation in a 4x4 environment), or
1277
# <b>ANTIALIAS</b> (a high-quality downsampling filter).
1278
# If omitted, or if the image has mode "1" or "P", it is
1279
# set <b>NEAREST</b>.
1280
# @return An Image object.
1282
def resize(self, size, resample=NEAREST):
1285
if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
1286
raise ValueError("unknown resampling filter")
1290
if self.mode in ("1", "P"):
1293
if resample == ANTIALIAS:
1294
# requires stretch support (imToolkit & PIL 1.1.3)
1296
im = self.im.stretch(size, resample)
1297
except AttributeError:
1298
raise ValueError("unsupported resampling filter")
1300
im = self.im.resize(size, resample)
1302
return self._new(im)
1305
# Returns a rotated copy of this image. This method returns a
1306
# copy of this image, rotated the given number of degrees counter
1307
# clockwise around its centre.
1309
# @def rotate(angle, filter=NEAREST)
1310
# @param angle In degrees counter clockwise.
1311
# @param filter An optional resampling filter. This can be
1312
# one of <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
1313
# (linear interpolation in a 2x2 environment), or <b>BICUBIC</b>
1314
# (cubic spline interpolation in a 4x4 environment).
1315
# If omitted, or if the image has mode "1" or "P", it is
1316
# set <b>NEAREST</b>.
1317
# @param expand Optional expansion flag. If true, expands the output
1318
# image to make it large enough to hold the entire rotated image.
1319
# If false or omitted, make the output image the same size as the
1321
# @return An Image object.
1323
def rotate(self, angle, resample=NEAREST, expand=0):
1324
"Rotate image. Angle given as degrees counter-clockwise."
1328
angle = -angle * math.pi / 180
1330
math.cos(angle), math.sin(angle), 0.0,
1331
-math.sin(angle), math.cos(angle), 0.0
1333
def transform(x, y, (a, b, c, d, e, f)=matrix):
1334
return a*x + b*y + c, d*x + e*y + f
1336
# calculate output size
1340
for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
1341
x, y = transform(x, y)
1344
w = int(math.ceil(max(xx)) - math.floor(min(xx)))
1345
h = int(math.ceil(max(yy)) - math.floor(min(yy)))
1348
x, y = transform(w / 2.0, h / 2.0)
1349
matrix[2] = self.size[0] / 2.0 - x
1350
matrix[5] = self.size[1] / 2.0 - y
1352
return self.transform((w, h), AFFINE, matrix, resample)
1354
if resample not in (NEAREST, BILINEAR, BICUBIC):
1355
raise ValueError("unknown resampling filter")
1359
if self.mode in ("1", "P"):
1362
return self._new(self.im.rotate(angle, resample))
1365
# Saves this image under the given filename. If no format is
1366
# specified, the format to use is determined from the filename
1367
# extension, if possible.
1369
# Keyword options can be used to provide additional instructions
1370
# to the writer. If a writer doesn't recognise an option, it is
1371
# silently ignored. The available options are described later in
1374
# You can use a file object instead of a filename. In this case,
1375
# you must always specify the format. The file object must
1376
# implement the <b>seek</b>, <b>tell</b>, and <b>write</b>
1377
# methods, and be opened in binary mode.
1379
# @def save(file, format=None, **options)
1380
# @param file File name or file object.
1381
# @param format Optional format override. If omitted, the
1382
# format to use is determined from the filename extension.
1383
# If a file object was used instead of a filename, this
1384
# parameter should always be used.
1385
# @param **options Extra parameters to the image writer.
1387
# @exception KeyError If the output format could not be determined
1388
# from the file name. Use the format option to solve this.
1389
# @exception IOError If the file could not be written. The file
1390
# may have been created, and may contain partial data.
1392
def save(self, fp, format=None, **params):
1393
"Save image to file or stream"
1395
if isStringType(fp):
1398
if hasattr(fp, "name") and isStringType(fp.name):
1406
self.encoderinfo = params
1407
self.encoderconfig = ()
1411
ext = string.lower(os.path.splitext(filename)[1])
1415
format = EXTENSION[ext]
1419
format = EXTENSION[ext]
1421
raise KeyError(ext) # unknown extension
1424
save_handler = SAVE[string.upper(format)]
1427
save_handler = SAVE[string.upper(format)] # unknown format
1429
if isStringType(fp):
1431
fp = __builtin__.open(fp, "wb")
1437
save_handler(self, fp, filename)
1439
# do what we can to clean up
1444
# Seeks to the given frame in this sequence file. If you seek
1445
# beyond the end of the sequence, the method raises an
1446
# <b>EOFError</b> exception. When a sequence file is opened, the
1447
# library automatically seeks to frame 0.
1449
# Note that in the current version of the library, most sequence
1450
# formats only allows you to seek to the next frame.
1452
# @param frame Frame number, starting at 0.
1453
# @exception EOFError If the call attempts to seek beyond the end
1457
def seek(self, frame):
1458
"Seek to given frame in sequence file"
1460
# overridden by file handlers
1465
# Displays this image. This method is mainly intended for
1466
# debugging purposes.
1468
# On Unix platforms, this method saves the image to a temporary
1469
# PPM file, and calls the <b>xv</b> utility.
1471
# On Windows, it saves the image to a temporary BMP file, and uses
1472
# the standard BMP display utility to show it (usually Paint).
1474
# @def show(title=None)
1475
# @param title Optional title to use for the image window,
1478
def show(self, title=None, command=None):
1479
"Display image (for debug purposes only)"
1481
_show(self, title=title, command=command)
1484
# Split this image into individual bands. This method returns a
1485
# tuple of individual image bands from an image. For example,
1486
# splitting an "RGB" image creates three new images each
1487
# containing a copy of one of the original bands (red, green,
1490
# @return A tuple containing bands.
1493
"Split image into bands"
1496
if self.im.bands == 1:
1500
for i in range(self.im.bands):
1501
ims.append(self._new(self.im.getband(i)))
1505
# Returns the current frame number.
1507
# @return Frame number, starting with 0.
1511
"Return current frame number"
1516
# Make this image into a thumbnail. This method modifies the
1517
# image to contain a thumbnail version of itself, no larger than
1518
# the given size. This method calculates an appropriate thumbnail
1519
# size to preserve the aspect of the image, calls the {@link
1520
# #Image.draft} method to configure the file reader (where
1521
# applicable), and finally resizes the image.
1523
# Note that the bilinear and bicubic filters in the current
1524
# version of PIL are not well-suited for thumbnail generation.
1525
# You should use <b>ANTIALIAS</b> unless speed is much more
1526
# important than quality.
1528
# Also note that this function modifies the Image object in place.
1529
# If you need to use the full resolution image as well, apply this
1530
# method to a {@link #Image.copy} of the original image.
1532
# @param size Requested size.
1533
# @param resample Optional resampling filter. This can be one
1534
# of <b>NEAREST</b>, <b>BILINEAR</b>, <b>BICUBIC</b>, or
1535
# <b>ANTIALIAS</b> (best quality). If omitted, it defaults
1536
# to <b>NEAREST</b> (this will be changed to ANTIALIAS in a
1540
def thumbnail(self, size, resample=NEAREST):
1541
"Create thumbnail representation (modifies image in place)"
1543
# FIXME: the default resampling filter will be changed
1544
# to ANTIALIAS in future versions
1546
# preserve aspect ratio
1548
if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0])
1549
if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1])
1552
if size == self.size:
1555
self.draft(None, size)
1560
im = self.resize(size, resample)
1562
if resample != ANTIALIAS:
1564
im = self.resize(size, NEAREST) # fallback
1572
# FIXME: the different tranform methods need further explanation
1573
# instead of bloating the method docs, add a separate chapter.
1576
# Transforms this image. This method creates a new image with the
1577
# given size, and the same mode as the original, and copies data
1578
# to the new image using the given transform.
1580
# @def transform(size, method, data, resample=NEAREST)
1581
# @param size The output size.
1582
# @param method The transformation method. This is one of
1583
# <b>EXTENT</b> (cut out a rectangular subregion), <b>AFFINE</b>
1584
# (affine transform), <b>PERSPECTIVE</b> (perspective
1585
# transform), <b>QUAD</b> (map a quadrilateral to a
1586
# rectangle), or <b>MESH</b> (map a number of source quadrilaterals
1587
# in one operation).
1588
# @param data Extra data to the transformation method.
1589
# @param resample Optional resampling filter. It can be one of
1590
# <b>NEAREST</b> (use nearest neighbour), <b>BILINEAR</b>
1591
# (linear interpolation in a 2x2 environment), or
1592
# <b>BICUBIC</b> (cubic spline interpolation in a 4x4
1593
# environment). If omitted, or if the image has mode
1594
# "1" or "P", it is set to <b>NEAREST</b>.
1595
# @return An Image object.
1597
def transform(self, size, method, data=None, resample=NEAREST, fill=1):
1600
if isinstance(method, ImageTransformHandler):
1601
return method.transform(size, self, resample=resample, fill=fill)
1602
if hasattr(method, "getdata"):
1603
# compatibility w. old-style transform objects
1604
method, data = method.getdata()
1606
raise ValueError("missing method data")
1607
im = new(self.mode, size, None)
1610
for box, quad in data:
1611
im.__transformer(box, self, QUAD, quad, resample, fill)
1613
im.__transformer((0, 0)+size, self, method, data, resample, fill)
1617
def __transformer(self, box, image, method, data,
1618
resample=NEAREST, fill=1):
1620
# FIXME: this should be turned into a lazy operation (?)
1625
if method == AFFINE:
1626
# change argument order to match implementation
1627
data = (data[2], data[0], data[1],
1628
data[5], data[3], data[4])
1629
elif method == EXTENT:
1630
# convert extent to an affine transform
1631
x0, y0, x1, y1 = data
1632
xs = float(x1 - x0) / w
1633
ys = float(y1 - y0) / h
1635
data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
1636
elif method == PERSPECTIVE:
1637
# change argument order to match implementation
1638
data = (data[2], data[0], data[1],
1639
data[5], data[3], data[4],
1641
elif method == QUAD:
1642
# quadrilateral warp. data specifies the four corners
1643
# given as NW, SW, SE, and NE.
1644
nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
1645
x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
1646
data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
1647
(se[0]-sw[0]-ne[0]+x0)*As*At,
1648
y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
1649
(se[1]-sw[1]-ne[1]+y0)*As*At)
1651
raise ValueError("unknown transformation method")
1653
if resample not in (NEAREST, BILINEAR, BICUBIC):
1654
raise ValueError("unknown resampling filter")
1660
if image.mode in ("1", "P"):
1663
self.im.transform2(box, image.im, method, data, resample, fill)
1666
# Returns a flipped or rotated copy of this image.
1668
# @param method One of <b>FLIP_LEFT_RIGHT</b>, <b>FLIP_TOP_BOTTOM</b>,
1669
# <b>ROTATE_90</b>, <b>ROTATE_180</b>, or <b>ROTATE_270</b>.
1671
def transpose(self, method):
1672
"Transpose image (flip or rotate in 90 degree steps)"
1675
im = self.im.transpose(method)
1676
return self._new(im)
1678
# --------------------------------------------------------------------
1681
class _ImageCrop(Image):
1683
def __init__(self, im, box):
1685
Image.__init__(self)
1687
x0, y0, x1, y1 = box
1694
self.size = x1-x0, y1-y0
1696
self.__crop = x0, y0, x1, y1
1704
self.im = self.im.crop(self.__crop)
1708
return self.im.pixel_access(self.readonly)
1710
# FIXME: future versions should optimize crop/paste
1713
# --------------------------------------------------------------------
1714
# Abstract handlers.
1716
class ImagePointHandler:
1717
# used as a mixin by point transforms (for use with im.point)
1720
class ImageTransformHandler:
1721
# used as a mixin by geometry transforms (for use with im.transform)
1724
# --------------------------------------------------------------------
1731
"Create greyscale wedge (for debugging only)"
1733
return Image()._new(core.wedge("L"))
1736
# Creates a new image with the given mode and size.
1738
# @param mode The mode to use for the new image.
1739
# @param size A 2-tuple, containing (width, height) in pixels.
1740
# @param color What colour to use for the image. Default is black.
1741
# If given, this should be a single integer or floating point value
1742
# for single-band modes, and a tuple for multi-band modes (one value
1743
# per band). When creating RGB images, you can also use colour
1744
# strings as supported by the ImageColor module. If the colour is
1745
# None, the image is not initialised.
1746
# @return An Image object.
1748
def new(mode, size, color=0):
1749
"Create a new image"
1753
return Image()._new(core.new(mode, size))
1755
if isStringType(color):
1756
# css3-style specifier
1759
color = ImageColor.getcolor(color, mode)
1761
return Image()._new(core.fill(mode, size, color))
1764
# Creates an image memory from pixel data in a string.
1766
# In its simplest form, this function takes three arguments
1767
# (mode, size, and unpacked pixel data).
1769
# You can also use any pixel decoder supported by PIL. For more
1770
# information on available decoders, see the section <a
1771
# href="pil-decoder.htm"><i>Writing Your Own File Decoder</i></a>.
1773
# Note that this function decodes pixel data only, not entire images.
1774
# If you have an entire image in a string, wrap it in a
1775
# <b>StringIO</b> object, and use {@link #open} to load it.
1777
# @param mode The image mode.
1778
# @param size The image size.
1779
# @param data An 8-bit string containing raw data for the given mode.
1780
# @param decoder_name What decoder to use.
1781
# @param *args Additional parameters for the given decoder.
1782
# @return An Image object.
1784
def fromstring(mode, size, data, decoder_name="raw", *args):
1785
"Load image from string"
1787
# may pass tuple instead of argument list
1788
if len(args) == 1 and isTupleType(args[0]):
1791
if decoder_name == "raw" and args == ():
1794
im = new(mode, size)
1795
im.fromstring(data, decoder_name, args)
1799
# (New in 1.1.4) Creates an image memory from pixel data in a string
1802
# This function is similar to {@link #fromstring}, but uses data in
1803
# the byte buffer, where possible. This means that changes to the
1804
# original buffer object are reflected in this image). Not all modes
1805
# can share memory; supported modes include "L", "RGBX", "RGBA", and
1808
# Note that this function decodes pixel data only, not entire images.
1809
# If you have an entire image file in a string, wrap it in a
1810
# <b>StringIO</b> object, and use {@link #open} to load it.
1812
# In the current version, the default parameters used for the "raw"
1813
# decoder differs from that used for {@link fromstring}. This is a
1814
# bug, and will probably be fixed in a future release. The current
1815
# release issues a warning if you do this; to disable the warning,
1816
# you should provide the full set of parameters. See below for
1819
# @param mode The image mode.
1820
# @param size The image size.
1821
# @param data An 8-bit string or other buffer object containing raw
1822
# data for the given mode.
1823
# @param decoder_name What decoder to use.
1824
# @param *args Additional parameters for the given decoder. For the
1825
# default encoder ("raw"), it's recommended that you provide the
1826
# full set of parameters:
1827
# <b>frombuffer(mode, size, data, "raw", mode, 0, 1)</b>.
1828
# @return An Image object.
1831
def frombuffer(mode, size, data, decoder_name="raw", *args):
1832
"Load image from string or buffer"
1834
# may pass tuple instead of argument list
1835
if len(args) == 1 and isTupleType(args[0]):
1838
if decoder_name == "raw":
1842
"the frombuffer defaults may change in a future release; "
1843
"for portability, change the call to read:\n"
1844
" frombuffer(mode, size, data, 'raw', mode, 0, 1)",
1845
RuntimeWarning, stacklevel=2
1847
args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6
1848
if args[0] in _MAPMODES:
1849
im = new(mode, (1,1))
1851
core.map_buffer(data, size, decoder_name, None, 0, args)
1856
return fromstring(mode, size, data, decoder_name, args)
1860
# (New in 1.1.6) Creates an image memory from an object exporting
1861
# the array interface (using the buffer protocol).
1863
# If obj is not contiguous, then the tostring method is called
1864
# and {@link frombuffer} is used.
1866
# @param obj Object with array interface
1867
# @param mode Mode to use (will be determined from type if None)
1868
# @return An image memory.
1870
def fromarray(obj, mode=None):
1871
arr = obj.__array_interface__
1872
shape = arr['shape']
1875
strides = arr['strides']
1880
typekey = (1, 1) + shape[2:], arr['typestr']
1881
mode, rawmode = _fromarray_typemap[typekey]
1884
raise TypeError("Cannot handle this data type")
1887
if mode in ["1", "L", "I", "P", "F"]:
1894
raise ValueError("Too many dimensions.")
1896
size = shape[1], shape[0]
1897
if strides is not None:
1898
obj = obj.tostring()
1900
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
1902
_fromarray_typemap = {
1903
# (shape, typestr) => mode, rawmode
1904
# first two members of shape are set to one
1905
# ((1, 1), "|b1"): ("1", "1"), # broken
1906
((1, 1), "|u1"): ("L", "L"),
1907
((1, 1), "|i1"): ("I", "I;8"),
1908
((1, 1), "<i2"): ("I", "I;16"),
1909
((1, 1), ">i2"): ("I", "I;16B"),
1910
((1, 1), "<i4"): ("I", "I;32"),
1911
((1, 1), ">i4"): ("I", "I;32B"),
1912
((1, 1), "<f4"): ("F", "F;32F"),
1913
((1, 1), ">f4"): ("F", "F;32BF"),
1914
((1, 1), "<f8"): ("F", "F;64F"),
1915
((1, 1), ">f8"): ("F", "F;64BF"),
1916
((1, 1, 3), "|u1"): ("RGB", "RGB"),
1917
((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
1921
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
1922
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")
1925
# Opens and identifies the given image file.
1927
# This is a lazy operation; this function identifies the file, but the
1928
# actual image data is not read from the file until you try to process
1929
# the data (or call the {@link #Image.load} method).
1931
# @def open(file, mode="r")
1932
# @param file A filename (string) or a file object. The file object
1933
# must implement <b>read</b>, <b>seek</b>, and <b>tell</b> methods,
1934
# and be opened in binary mode.
1935
# @param mode The mode. If given, this argument must be "r".
1936
# @return An Image object.
1937
# @exception IOError If the file cannot be found, or the image cannot be
1938
# opened and identified.
1941
def open(fp, mode="r"):
1942
"Open an image file, without loading the raster data"
1945
raise ValueError("bad mode")
1947
if isStringType(fp):
1950
fp = __builtin__.open(fp, "rb")
1954
prefix = fp.read(16)
1960
factory, accept = OPEN[i]
1961
if not accept or accept(prefix):
1963
return factory(fp, filename)
1964
except (SyntaxError, IndexError, TypeError):
1971
factory, accept = OPEN[i]
1972
if not accept or accept(prefix):
1974
return factory(fp, filename)
1975
except (SyntaxError, IndexError, TypeError):
1978
raise IOError("cannot identify image file")
1984
# Creates a new image by interpolating between two input images, using
1988
# out = image1 * (1.0 - alpha) + image2 * alpha
1991
# @param im1 The first image.
1992
# @param im2 The second image. Must have the same mode and size as
1994
# @param alpha The interpolation alpha factor. If alpha is 0.0, a
1995
# copy of the first image is returned. If alpha is 1.0, a copy of
1996
# the second image is returned. There are no restrictions on the
1997
# alpha value. If necessary, the result is clipped to fit into
1998
# the allowed output range.
1999
# @return An Image object.
2001
def blend(im1, im2, alpha):
2002
"Interpolate between images."
2006
return im1._new(core.blend(im1.im, im2.im, alpha))
2009
# Creates a new image by interpolating between two input images,
2010
# using the mask as alpha.
2012
# @param image1 The first image.
2013
# @param image2 The second image. Must have the same mode and
2014
# size as the first image.
2015
# @param mask A mask image. This image can can have mode
2016
# "1", "L", or "RGBA", and must have the same size as the
2019
def composite(image1, image2, mask):
2020
"Create composite image by blending images using a transparency mask"
2022
image = image2.copy()
2023
image.paste(image1, None, mask)
2027
# Applies the function (which should take one argument) to each pixel
2028
# in the given image. If the image has more than one band, the same
2029
# function is applied to each band. Note that the function is
2030
# evaluated once for each possible pixel value, so you cannot use
2031
# random components or other generators.
2033
# @def eval(image, function)
2034
# @param image The input image.
2035
# @param function A function object, taking one integer argument.
2036
# @return An Image object.
2038
def eval(image, *args):
2039
"Evaluate image expression"
2041
return image.point(args[0])
2044
# Creates a new image from a number of single-band images.
2046
# @param mode The mode to use for the output image.
2047
# @param bands A sequence containing one single-band image for
2048
# each band in the output image. All bands must have the
2050
# @return An Image object.
2052
def merge(mode, bands):
2053
"Merge a set of single band images into a new multiband image."
2055
if getmodebands(mode) != len(bands) or "*" in mode:
2056
raise ValueError("wrong number of bands")
2057
for im in bands[1:]:
2058
if im.mode != getmodetype(mode):
2059
raise ValueError("mode mismatch")
2060
if im.size != bands[0].size:
2061
raise ValueError("size mismatch")
2062
im = core.new(mode, bands[0].size)
2063
for i in range(getmodebands(mode)):
2065
im.putband(bands[i].im, i)
2066
return bands[0]._new(im)
2068
# --------------------------------------------------------------------
2072
# Register an image file plugin. This function should not be used
2073
# in application code.
2075
# @param id An image format identifier.
2076
# @param factory An image file factory method.
2077
# @param accept An optional function that can be used to quickly
2078
# reject images having another format.
2080
def register_open(id, factory, accept=None):
2081
id = string.upper(id)
2083
OPEN[id] = factory, accept
2086
# Registers an image MIME type. This function should not be used
2087
# in application code.
2089
# @param id An image format identifier.
2090
# @param mimetype The image MIME type for this format.
2092
def register_mime(id, mimetype):
2093
MIME[string.upper(id)] = mimetype
2096
# Registers an image save function. This function should not be
2097
# used in application code.
2099
# @param id An image format identifier.
2100
# @param driver A function to save images in this format.
2102
def register_save(id, driver):
2103
SAVE[string.upper(id)] = driver
2106
# Registers an image extension. This function should not be
2107
# used in application code.
2109
# @param id An image format identifier.
2110
# @param extension An extension used for this format.
2112
def register_extension(id, extension):
2113
EXTENSION[string.lower(extension)] = string.upper(id)
2116
# --------------------------------------------------------------------
2117
# Simple display support. User code may override this.
2119
def _show(image, **options):
2120
# override me, as necessary
2121
apply(_showxv, (image,), options)
2123
def _showxv(image, title=None, **options):
2125
apply(ImageShow.show, (image, title), options)