Module PIL.Image
Module Summary:
#1594
def blend
(im1, im2, alpha)
Creates a new image by interpolating between the given images, using
a constant alpha.
#1612
def composite
(image1, image2, mask)
Creates a new image by interpolating between the given images,
using the mask as alpha.
#1631
def eval
(image, function)
Applies the function (which should take one argument) to each pixel
in the given image.
#1497
def frombuffer
(mode, size, data, decoder_name='raw', *args)
Creates an image memory from pixel data in a string or byte buffer.
#1464
def fromstring
(mode, size, data, decoder_name='raw', *args)
Creates an image memory from pixel data in a string.
#193
def getmodebase
(mode)
Get "base" mode.
#205
def getmodetype
(mode)
Get storage type mode.
#252
def init
()
Explicitly load all available file format drivers.
#1645
def merge
(mode, bands)
Creates a new image from a number of single-band images.
#1428
def new
(mode, size, color=0)
Creates a new image with the given mode and size.
#1534
def open
(file, mode="r")
Opens and identifies the given image file.
#234
def preinit
()
Explicitly load standard file format drivers.
#1705
def register_extension
(id, extension)
Register an image extension.
#1685
def register_mime
(id, mimetype)
Register an image MIME type.
#1673
def register_open
(id, factory, accept=None)
Register an image file plugin.
#1695
def register_save
(id, driver)
Register an image save function.
#368
class Image
:
def __init__(self)
This class represents an image object.
Functions
blend
blend(im1, im2, alpha)
Creates a new image by interpolating between the given images, using
a constant alpha.
out = image1 * (1.0 - alpha) + image2 * alpha
Parameters:
im1
-- The first image.
im2
-- The second image.  Must have the same mode and size as
the first image.
alpha
-- The interpolation alpha factor.  If alpha is 0.0, a
copy of the first image is returned. If alpha is 1.0, a copy of
the second image is returned. There are no restrictions on the
alpha value. If necessary, the result is clipped to fit into
the allowed output range.
Returns:
An Image object.
composite
composite(image1, image2, mask)
Creates a new image by interpolating between the given images,
using the mask as alpha.
Parameters:
image1
-- The first image.
image2
-- The second image.  Must have the same mode and
size as the first image.
mask
-- A mask image.  This image can can have mode
"1", "L", or "RGBA", and most have the same size as the
other two images.
eval
eval(image, function)
Applies the function (which should take one argument) to each pixel
in the given image. If the image has more than one band, the same
function is applied to each band. Note that the function is
evaluated once for each possible pixel value, so you cannot use
random components or other generators.
Parameters:
image
-- The input image.
function
-- A function object, taking one integer argument.
Returns:
An Image object.
frombuffer
frombuffer(mode, size, data, decoder_name='raw', *args)
Creates an image memory from pixel data in a string or byte buffer.
This function is similar to
fromstring
, but it data in
the byte buffer, where possible.  Images created by this function
are usually marked as readonly.
Note that this function decodes pixel data only, not entire images.
If you have an entire image in a string, wrap it in a
StringIO
object, and use
open
to load it.
Parameters:
mode
-- The image mode.
size
-- The image size.
data
-- An 8-bit string or other buffer object containing raw
data for the given mode.
decoder_name
-- What decoder to use.
*args
-- Additional parameters for the given decoder.
Returns:
An Image object.
fromstring
fromstring(mode, size, data, decoder_name='raw', *args)
Creates an image memory from pixel data in a string.
In its simplest form, this function takes three arguments
(mode, size, and unpacked pixel data).
You can also use any pixel decoder supported by PIL.  For more
information on available decoders, see the section
decoder
Writing Your Own File Decoder
.
Note that this function decodes pixel data only, not entire images.
If you have an entire image in a string, wrap it in a
StringIO
object, and use
open
to load it.
Parameters:
mode
-- The image mode.
size
-- The image size.
data
-- An 8-bit string containing raw data for the given mode.
decoder_name
-- What decoder to use.
*args
-- Additional parameters for the given decoder.
Returns:
An Image object.
getmodebase
getmodebase(mode)
Get "base" mode.  Given a mode, this function returns "L" for
images that contain grayscale data, and "RGB" for images that
contain color data.
Parameters:
mode
-- Input mode.
Returns:
"L" or "RGB".
Exceptions:
KeyError
-- The input mode was not a standard mode.
getmodetype
getmodetype(mode)
Get storage type mode.  Given a mode, this function returns a
single-layer mode suitable for storing individual bands.
Parameters:
mode
-- Input mode.
Returns:
"L", "I", or "F".
Exceptions:
KeyError
-- The input mode was not a standard mode.
init
init()
Explicitly load all available file format drivers.
merge
merge(mode, bands)
Creates a new image from a number of single-band images.
Parameters:
mode
-- The mode to use for the output image.
bands
-- A sequence containing one single-band image for
each band in the output image.  All bands must have the
same size.
Returns:
An Image object.
new
new(mode, size, color=0)
Creates a new image with the given mode and size.
Parameters:
mode
-- The mode to use for the new image.
size
-- A 2-tuple, containing (width, height)
color
-- What colour to use for the image.  Default is black.
If given, this should be a single integer or floating point value
for single-band modes, and a tuple for multi-band modes (one value
per band).  When creating RGB images, you can also use colour
strings as supported by the ImageColor module.  If the colour is
None, the image is not initialised.
Returns:
An Image object.
open
open(file, mode="r")
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the
actual image data is not read from the file until you try to process
the data (or call the
load
method).
Parameters:
file
-- A filename (string) or a file object.  The file object
must implement
read
,
seek
, and
tell
methods,
and be opened in binary mode.
mode
-- The mode.  If given, this argument must be "r".
Returns:
An Image object.
Exceptions:
IOError
-- If the file cannot be found, or the image cannot be
opened and identified.
preinit
preinit()
Explicitly load standard file format drivers.
register_extension
register_extension(id, extension)
Register an image extension.  This function should not be
used in application code.
Parameters:
id
-- An image format identifier.
extension
-- An extension used for this format.
register_mime
register_mime(id, mimetype)
Register an image MIME type.  This function should not be used
in application code.
Parameters:
id
-- An image format identifier.
mimetype
-- The image MIME type for this format.
register_open
register_open(id, factory, accept=None)
Register an image file plugin.  This function should not be used
in application code.
Parameters:
id
-- An image format identifier.
factory
-- An image file factory method.
accept
-- An optional function that can be used to quickly
reject images having another format.
register_save
register_save(id, driver)
Register an image save function.  This function should not be
used in application code.
Parameters:
id
-- An image format identifier.
driver
-- A function to save images in this format.
Classes
The Image Class
Image()
This class represents an image object.  To create Image objects, use
the appropriate factory functions.  There's hardly ever any reason
to call the Image constructor directly.
Method Summary:
#551
convert(mode, matrix=None)
Returns a converted copy of an image.
#627
copy()
Copies the image.
#645
crop(box=None)
Returns a rectangular region from the current image.
#668
draft(mode, size)
Configures the image file loader so it returns a version of the
image that as closely as possible matches the given mode and
size.
#681
filter(filter)
Filter image by the given filter.
#476
fromstring(data, decoder_name='raw', *args)
Same as the fromstring function, but loads data
into the current image.
#704
getbands()
Returns a tuple containing the name of each band.
#716
getbbox()
Calculates the bounding box of the non-zero regions in the
image.
#738
getdata(band=None)
Returns the contents of an image as a sequence object containing
pixel values.
#754
getextrema()
Get the the minimum and maximum pixel values for each band in
the image.
#772
getpixel(xy)
Returns the pixel value at a given position.
#804
histogram(mask=None)
Returns a histogram for the image.
#503
load()
Allocates storage for the image and loads the pixel data.
#830
offset(xoffset, yoffset=None)
(Deprecated) Returns a copy of the image where the data has been
offset by the given distances.
#869
paste(im, box=None, mask=None)
Pastes another image into this image.
#919
point(lut, mode=None)
Map image through lookup table or function.
#943
putalpha(im)
Replace the alpha layer in the current image.
#968
putdata(data, scale=1.0, offset=0.0)
Copy pixel data to this image.
#984
putpalette(data)
Attach a palette to a "P" or "L" image.
#1012
putpixel(xy, value)
Modifies the pixel at the given position.
#1033
resize(size, filter=NEAREST)
Returns a resized copy of an image.
#1070
rotate(angle, filter=NEAREST)
Returns a rotated image.
#1107
save(file, format=None, **options)
Saves the image under the given filename.
#1163
seek(frame)
Seeks to the given frame in a sequence file.
#1184
show(title=None)
Displays an image.
#1202
split()
Split image into individual bands.
#1217
tell()
Returns the current frame number.
#1247
thumbnail(size, resample=0)
Make thumbnail.
#461
tobitmap(name='image')
Returns the image converted to an X11 bitmap.
#426
tostring(encoder_name='raw', *args)
Returns a string containing pixel data.
#1303
transform(size, method, data, resample=NEAREST)
Transform image.
#1371
transpose(method)
Returns a flipped or rotated copy of an image.
#522
verify()
Verify file contents.
convert
convert(mode, matrix=None)
Returns a converted copy of an image. For the "P" mode, this
translates pixels through the palette. If mode is omitted, a
mode is chosen so that all information in the image and the
palette can be represented without a palette.
The current version supports all possible conversions between
"L", "RGB" and "CMYK."
When translating a colour image to black and white (mode "L"),
the library uses the ITU-R 601-2 luma transform:
L = R * 299/1000 + G * 587/1000 + B * 114/1000
When translating a greyscale image into a bilevel image (mode
"1"), all non-zero values are set to 255 (white). To use other
thresholds, use the
point
method.
Parameters:
mode
-- The requested mode.
matrix
-- An optional conversion matrix.  If given, this
should be 4- or 16-tuple containing floating point values.
Returns:
An Image object.
copy
copy()
Copies the image. Use this method if you wish to paste things
into an image, but still retain the original.
Returns:
An Image object.
crop
crop(box=None)
Returns a rectangular region from the current image. The box is
a 4-tuple defining the left, upper, right, and lower pixel
coordinate.
This is a lazy operation.  Changes to the source image may or
may not be reflected in the cropped image.  To break the
connection, call the
load
method on the cropped copy.
Returns:
An Image object.
draft
draft(mode, size)
Configures the image file loader so it returns a version of the
image that as closely as possible matches the given mode and
size.  For example, you can use this method to convert a colour
JPEG to greyscale while loading it, or to extract a 128x192
version from a PCD file.
Note that this method modifies the Image object in place.  If
the image has already been loaded, this method has no effect.
Parameters:
mode
-- The requested mode.
size
-- The requested size.
filter
filter(filter)
Filter image by the given filter.  For a list of available
filters, see the
ImageFilter
module.
Parameters:
filter
-- Filter kernel.
Returns:
An Image object.
fromstring
fromstring(data, decoder_name='raw', *args)
Same as the
fromstring
function, but loads data
into the current image.
getbands
getbands()
Returns a tuple containing the name of each band. For example,
getbands
on an RGB image returns ("R", "G", "B").
Returns:
A tuple containing band names.
getbbox
getbbox()
Calculates the bounding box of the non-zero regions in the
image.
Returns:
The bounding box is returned as a 4-tuple defining the
left, upper, right, and lower pixel coordinate. If the image
is completely empty, this method returns None.
getdata
getdata(band=None)
Returns the contents of an image as a sequence object containing
pixel values.  The sequence object is flattened, so that values
for line one follow directly after the values of line zero, and
so on.
Note that the sequence object returned by this method is an
internal PIL data type, which only supports certain sequence
operations.  To convert it to an ordinary sequence (e.g. for
printing), use
list(im.getdata())
.
Parameters:
band
-- What band to return.  The default is to return
all bands.  To return a single band, pass in the index
value (e.g. 0 to get the "R" band from an "RGB" image).
Returns:
A sequence-like object.
getextrema
getextrema()
Get the the minimum and maximum pixel values for each band in
the image.
Returns:
For a single-band image, a 2-tuple containing the
minimum and maximum pixel value.  For a multi-band image,
a tuple containing one 2-tuple for each band.
getpixel
getpixel(xy)
Returns the pixel value at a given position.
Parameters:
xy
-- The coordinate, given as (x, y).
Returns:
The pixel value.  If the image is a multi-layer image,
this method returns a tuple.
histogram
histogram(mask=None)
Returns a histogram for the image. The histogram is returned as
a list of pixel counts, one for each pixel value in the source
image. If the image has more than one band, the histograms for
all bands are concatenated (for example, the histogram for an
"RGB" image contains 768 values).
A bilevel image (mode "1") is treated as a greyscale ("L") image
by this method.
If a mask is provided, the method returns a histogram for those
parts of the image where the mask image is non-zero. The mask
image must have the same size as the image, and be either a
bi-level image (mode "1") or a greyscale image ("L").
Parameters:
mask
-- An optional mask.
Returns:
A list containing pixel counts.
load
load()
Allocates storage for the image and loads the pixel data.  In
normal cases, you don't need to call this method, since the
Image class automatically loads an opened image when it is
accessed for the first time.
offset
offset(xoffset, yoffset=None)
(Deprecated) Returns a copy of the image where the data has been
offset by the given distances. Data wraps around the edges. If
yoffset is omitted, it is assumed to be equal to xoffset.
This method is deprecated. New code should use the
offset
function in the
ImageChops
module.
Parameters:
xoffset
-- The horizontal distance.
yoffset
-- The vertical distance.  If omitted, both
distances are set to the same value.
Returns:
An Image object.
paste
paste(im, box=None, mask=None)
Pastes another image into this image. The box argument is either
a 2-tuple giving the upper left corner, a 4-tuple defining the
left, upper, right, and lower pixel coordinate, or None (same as
(0, 0)).  If a 4-tuple is given, the size of the pasted image
must match the size of the region.
If the modes don't match, the pasted image is converted to the
mode of this image (see the
convert
method for details).
Instead of an image, the source can be a integer or tuple
containing pixel values.  The method then fills the region
with the given colour.  When creating RGB images, you can
also use colour strings as supported by the ImageColor module.
If a mask is given, this method updates only the regions
indicated by the mask.  You can use either "1", "L" or "RGBA"
images (in the latter case, the alpha band is used as mask).
Where the mask is 255, the given image is copied as is.  Where
the mask is 0, the current value is preserved.  Intermediate
values can be used for transparency effects.
Note that if you paste an "RGBA" image, the alpha band is
ignored.  You can work around this by using the same image as
both source image and mask.
Parameters:
im
-- Source image or pixel value (integer or tuple).
box
-- A 4-tuple giving the region to paste into.  If a
2-tuple is used instead, it's treated as the upper left
corner.  If None is used instead, the source is pasted
into the upper left corner.
mask
-- An optional mask image.
Returns:
An Image object.
point
point(lut, mode=None)
Map image through lookup table or function.
Parameters:
lut
-- A lookup table, containing 256 values per band in the
image. A function can be used instead, it should take a single
argument. The function is called once for each possible pixel
value, and the resulting table is applied to all bands of the
image.
mode
-- Output mode (default is same as input).  In the
current version, this can only be used if the source image
has mode "L" or "P", and the output has mode "1".
Returns:
An Image object.
putalpha
putalpha(im)
Replace the alpha layer in the current image.  The image must be
an "RGBA" image, and the band must be either "L" or "1".
Parameters:
im
-- The new alpha layer.
putdata
putdata(data, scale=1.0, offset=0.0)
Copy pixel data to this image.  This method copies data from a
sequence object into the image, starting at the upper left
corner (0, 0), and continuing until either the image or the
sequence ends.  The scale and offset values are used to adjust
the sequence values:
pixel = value*scale + offset
.
Parameters:
data
-- A sequence object.
scale
-- An optional scale value.  The default is 1.0.
offset
-- An optional offset value.  The default is 0.0.
putpalette
putpalette(data)
Attach a palette to a "P" or "L" image. The palette sequence
should contain 768 integer values, where each group of three
values represent the red, green, and blue values for the
corresponding pixel index. Instead of an integer sequence, you
can use an 8-bit string.
Parameters:
data
-- A palette sequence.
putpixel
putpixel(xy, value)
Modifies the pixel at the given position. The colour is given as
a single numerical value for single-band images, and a tuple for
multi-band images.
Note that this method is relatively slow.  For more extensive
changes, use
paste
or the
ImageDraw
module
instead.
Parameters:
xy
-- The pixel coordinate, given as (x, y).
value
-- The pixel value.
resize
resize(size, filter=NEAREST)
Returns a resized copy of an image.
Parameters:
size
-- The requested size in pixels, as a 2-tuple:
(width, height).
filter
-- An optional resampling filter.  This can be
one of
NEAREST
(use nearest neighbour),
BILINEAR
(linear interpolation in a 2x2 environment),
BICUBIC
(cubic spline interpolation in a 4x4 environment), or
ANTIALIAS
(a high-quality downsampling filter).
If omitted, or if the image has mode "1" or "P", it is
set
NEAREST
.
Returns:
An Image object.
rotate
rotate(angle, filter=NEAREST)
Returns a rotated image.  This method returns a copy of an
image, rotated the given number of degrees counter clockwise
around its centre.
Parameters:
angle
-- In degrees counter clockwise.
filter
-- An optional resampling filter.  This can be
one of
NEAREST
(use nearest neighbour),
BILINEAR
(linear interpolation in a 2x2 environment), or
BICUBIC
(cubic spline interpolation in a 4x4 environment).
If omitted, or if the image has mode "1" or "P", it is
set
NEAREST
.
Returns:
An Image object.
save
save(file, format=None, **options)
Saves the image under the given filename.  If no format is
specified, the format to use is determined from the filename
extension, if possible.
Keyword options can be used to provide additional instructions
to the writer. If a writer doesn't recognise an option, it is
silently ignored. The available options are described later in
this handbook.
You can use a file object instead of a filename. In this case,
you must always specify the format. The file object must
implement the
seek
,
tell
, and
write
methods, and be opened in binary mode.
Parameters:
file
-- File name or file object.
format
-- Optional format override.  If omitted, the
format to use is determined from the filename extension.
If a file object was used instead of a filename, this
parameter should always be used.
**options
-- Extra parameters to the image writer.
Returns:
None
seek
seek(frame)
Seeks to the given frame in a sequence file. If you seek beyond
the end of the sequence, the method raises an
EOFError
exception. When a sequence file is opened, the library
automatically seeks to frame 0.
Note that in the current version of the library, most sequence
formats only allows you to seek to the next frame.
Parameters:
frame
-- Frame number, starting at 0.
Exceptions:
EOFError
-- Attempt to seek beyond the end of the sequence.
show
show(title=None)
Displays an image. This method is mainly intended for
debugging purposes.
On Unix platforms, this method saves the image to a temporary
PPM file, and calls the
xv
utility.
On Windows, it saves the image to a temporary BMP file, and uses
the standard BMP display utility to show it (usually Paint).
Parameters:
title
-- Optional title to use for the image window,
where possible.
split
split()
Split image into individual bands. This methods returns a tuple
of individual image bands from an image. For example, splitting
an "RGB" image creates three new images each containing a copy
of one of the original bands (red, green, blue).
Returns:
A tuple containing bands.
tell
tell()
Returns the current frame number.
Returns:
Frame number, starting with 0.
thumbnail
thumbnail(size, resample=0)
Make thumbnail.  This method modifies the image to contain a
thumbnail version of itself, no larger than the given size.
This method calculates an appropriate thumbnail size to preserve
the aspect of the image, calls the
draft
method to
configure the file reader (where applicable), and finally
resizes the image.
Note that the bilinear and bicubic filters in the current
version of PIL are not well-suited for thumbnail generation.
You should use
ANTIALIAS
unless speed is much more
important than quality.
Also note that this function modifies the Image object in place.
If you need to use the full resolution image as well, apply this
method to a
copy
of the original image.
Parameters:
size
-- Requested size.
resample
-- Optional resampling filter.  This can be one
of
NEAREST
,
BILINEAR
,
BICUBIC
, or
ANTIALIAS
(best quality).  If omitted, it defaults
to
NEAREST
(this will be changed to ANTIALIAS in
future versions).
Returns:
None
tobitmap
tobitmap(name='image')
Returns the image converted to an X11 bitmap.  This method
only works for mode "1" images.
Parameters:
name
-- The name prefix to use for the bitmap variables.
Returns:
A string containing an X11 bitmap.
Exceptions:
ValueError
-- If the mode is not "1"
tostring
tostring(encoder_name='raw', *args)
Returns a string containing pixel data.
Parameters:
encoder_name
-- What encoder to use.  The default is to
use the standard "raw" encoder.
*args
-- Extra arguments to the encoder.
Returns:
An 8-bit string.
transform
transform(size, method, data, resample=NEAREST)
Transform image.  This method creates a new image with the
given size, and the same mode as the original, and copies
data to the new image using the given transform.
Parameters:
size
-- The output size.
method
-- The transformation method.  This is one of
EXTENT
(cut out a rectangular subregion),
AFFINE
(affine transform),
QUAD
(map a quadrilateral to a
rectangle), or
MESH
(map a number of source quadrilaterals
in one operation).
data
-- Extra data to the transformation method.
resample
-- Optional resampling filter.  It can be one of
NEAREST
(use nearest neighbour),
BILINEAR
(linear interpolation in a 2x2 environment), or
BICUBIC
(cubic spline interpolation in a 4x4
environment). If omitted, or if the image has mode
"1" or "P", it is set to
NEAREST
.
Returns:
An Image object.
transpose
transpose(method)
Returns a flipped or rotated copy of an image.
Parameters:
method
-- One of
FLIP_LEFT_RIGHT
,
FLIP_TOP_BOTTOM
,
ROTATE_90
,
ROTATE_180
, or
ROTATE_270
.
verify
verify()
Verify file contents. For data read from a file, this method
attempts to determine if the file is broken, without actually
decoding the image data.  If this method finds any problems, it
raises suitable exceptions.  If you need to load the image after
using this method, you must reopen the image file.
