The Image module provides a class with the same name which is
used to represent a PIL image. The module also provides a number of factory
functions, including functions to load images from files, and to create new
images.
Examples
Open, rotate, and display an image (using the default viewer)
The following script loads an image, rotates it 45 degrees, and displays it
using an external viewer (usually xv on Unix, and the Paint program on
Windows).
This is a lazy operation; this function identifies the file, but
the file remains open and the actual image data is not read from
the file until you try to process the data (or call the
load() method). See
new(). See File handling in Pillow.
Parameters:
fp – A filename (string), os.PathLike object or a file object.
The file object must implement file.read,
file.seek, and file.tell methods,
and be opened in binary mode. The file object will also seek to zero
before reading.
mode – The mode. If given, this argument must be “r”.
formats – A list or tuple of formats to attempt to load the file in.
This can be used to restrict the set of formats checked.
Pass to try all supported formats. You can print the set of
available formats by running or using
the function.
Explicitly initializes the Python Imaging Library. This function
loads all available file format drivers.
It is called when opening or saving images if is
insufficient, and by .
The Image class
classPIL.Image.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.
An instance of the Image class has the following
methods. Unless otherwise stated, all methods return a new instance of the
Image class, holding the resulting image.
If a P mode image has a “transparency” key in the info dictionary,
remove the key and instead apply the transparency to the palette.
Otherwise, the image is unchanged.
This crops the input image with the provided coordinates:
fromPILimportImagewithImage.open("hopper.jpg")asim:# The crop method from the Image module takes four coordinates as input.# The right can also be represented as (left+width)# and lower can be represented as (upper+height).(left,upper,right,lower)=(20,20,100,100)# Here the image "im" is cropped and assigned to new variable im_crop
Filters this image using the given filter. For a list of
available filters, see the ImageFilter module.
Parameters
This blurs the input image using a filter from the ImageFilter module:
fromPILimportImage,ImageFilterwithImage.open("hopper.jpg")asim:# Blur the input image using the filter ImageFilter.BLURim_blurred=im.filter(filter=ImageFilter.BLUR)
Returns the contents of this 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()).
Adds or replaces the alpha layer in this image. If the image
does not have an alpha layer, it’s converted to “LA” or “RGBA”.
The new layer must be either “L” or “1”.
Parameters:
alpha – The new alpha layer. This can either be an “L” or “1”
image having the same size as this image, or an integer.
This resizes the given image from (width,height) to (width/2,height/2):
fromPILimportImagewithImage.open("hopper.jpg")asim:# Provide the target width and height of the image(width,height)=(im.width//2,im.height//2)im_resized=im.resize
This rotates the input image by theta degrees counterclockwise:
fromPILimportImagewithImage.open("hopper.jpg")asim:# Rotate the image by 60 degrees counterclockwisetheta=60# Angle is in degrees counterclockwiseim_rotated=im.rotate(angle=theta)
Seeks to the given frame in this 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.
Split this image into individual bands. This method 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).
If you need only one band, getchannel()
method can be more convenient and faster.
fromPILimportImagewithImage.open("hopper.jpg")asim:# Flip the image from left to rightim_flipped=im.transpose(method=Image.Transpose.FLIP_LEFT_RIGHT)# To flip the image from top to bottom,# use the method "Image.Transpose.FLIP_TOP_BOTTOM"
Verifies the contents of a file. 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.
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.
If the file associated with the image was opened by Pillow, then this
method will close it. The exception to this is if the image has
multiple frames, in which case the file will be left open for seek
operations. See File handling in Pillow for more information.
This operation will destroy the image core and release its memory.
The image data will be unusable afterward.
This function is required to close images that have multiple frames or
have not had their file read and closed by the
load() method. See File handling in Pillow for
more information.
Image attributes
Instances of the Image class have the following attributes:
The filename or path of the source file. Only images created with the
factory function open have a filename attribute. If the input is a
file-like object, the filename attribute is set to an empty string.
The file format of the source file. For images created by the library
itself (via a factory function, or by running a method on an existing
image), this attribute is set to None.
A dictionary holding data associated with the image. This dictionary is
used by file handlers to pass on various non-image information read from
the file. See documentation for the various file handlers for details.
Most methods ignore the dictionary when returning new images; since the
keys are not standardized, it’s not possible for a method to know if the
operation affects the dictionary. If you need the information later on,
keep a reference to the info dictionary returned from the open method.
Unless noted elsewhere, this dictionary does not affect saving files.
True if this image has more than one frame, or False otherwise.
This attribute is only defined by image plugins that support animated images.
Plugins may leave this attribute undefined if they don’t support loading
animated images, even if the given format supports animated images.
Given that this attribute is not present for all images, use
getattr(image,"is_animated",False) to check if Pillow is aware of multiple
frames in an image regardless of its format.
This attribute is only defined by image plugins that support animated images.
Plugins may leave this attribute undefined if they don’t support loading
animated images, even if the given format supports animated images.
Given that this attribute is not present for all images, use
getattr(image,"n_frames",1) to check the number of frames that Pillow is
aware of in an image regardless of its format.
Image.has_transparency_data
Determine if an image has transparency data, whether in the form of an
alpha channel, a palette with an alpha channel, or a “transparency” key
in the info dictionary.
Note the image might still appear solid, if all of the values shown
within are opaque.
Used with point() for single band images with more than
8 bits, this represents an affine transformation, where the value is multiplied by
scale and offset is added.
classPIL.Image.ImageTransformHandler
Used as a mixin by geometry transforms
(for use with transform())
Creates a new image by interpolating between two input 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.
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.
mode – The mode to use for the new image. See: Modes.
size – A 2-tuple, containing (width, height) in pixels.
color – What color to use for the image. 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 or HSV images, you can
also use color strings as supported by the ImageColor module. See Colors
for more information. The default color is zero, which appears as black in
single band or RGB-based images. None is also treated as zero.
If obj is not contiguous, then the tobytes method is called
and frombuffer() is used.
In the case of NumPy, be aware that Pillow modes do not always correspond
to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels,
32-bit signed integer pixels, and 32-bit floating point pixels.
When converting Pillow images to arrays however, only pixel values are
transferred. This means that P and PA mode images will lose their palette.
Parameters:
obj – Object with array interface
mode –
Optional mode to use when reading obj. Since pixel values do not
contain information about palettes or color spaces, this can be used to place
grayscale L mode data within a P mode image, or read RGB data as YCbCr for
example.
As with array support, when converting Pillow images to arrays,
only pixel values are transferred. This means that P and PA mode
images will lose their palette.
Parameters:
obj – Object with an arrow_c_array interface
mode – Image mode.
size – Image size. This must match the storage of the arrow object.
Returns:
An Image object
Note that according to the Arrow spec, both the producer and the
consumer should consider the exported array to be immutable, as
unsynchronized updates will potentially cause inconsistent data.
Creates a copy of an image memory from pixel data in a buffer.
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
Writing Your Own File Codec.
Note that this function decodes pixel data only, not entire images.
If you have an entire image in a string, wrap it in a
BytesIO object, and use open() to load
it.
Creates an image memory referencing pixel data in a byte buffer.
This function is similar to frombytes(), but uses data
in the byte buffer, where possible. This means that changes to the
original buffer object are reflected in this image). Not all modes can
share memory; supported modes include “L”, “RGBX”, “RGBA”, and “CMYK”.
Note that this function decodes pixel data only, not entire images.
If you have an entire image file in a string, wrap it in a
BytesIO object, and use open() to load it.
The default parameters used for the “raw” decoder differs from that used for
frombytes(). This is a bug, and will probably be fixed in a
future release. The current release issues a warning if you do this; to disable
the warning, you should provide the full set of parameters. See below for details.
Registers an image MIME type by populating Image.MIME. This function
should not be used in application code.
Image.MIME provides a mapping from image format identifiers to mime
formats, but get_format_mimetype() can
provide a different result for specific images.
Registers an image encoder. This function should not be
used in application code.
Parameters:
name – The name of the encoder
encoder – An ImageFile.PyEncoder object
‘In-place’ analog of Image.alpha_composite. Composites an image
onto this image.
Parameters:
im – image to composite over this one
dest – Optional 2 tuple (left, top) specifying the upper
left corner in this (destination) image.
source – Optional 2 (left, top) tuple for the upper left
corner in the overlay source image, or 4 tuple (left, top, right,
bottom) for the bounds of the source rectangle
Performance Note: Not currently implemented in-place in the core layer.
Returns a converted copy of this image. For the “P” mode, this
method 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.
This supports all possible conversions between “L”, “RGB” and “CMYK”. The
matrix argument only supports “L” and “RGB”.
When translating a color image to grayscale (mode “L”),
the library uses the ITU-R 601-2 luma transform:
L=R*299/1000+G*587/1000+B*114/1000
The default method of converting a grayscale (“L”) or “RGB”
image into a bilevel (mode “1”) image uses Floyd-Steinberg
dither to approximate the original image luminosity levels. If
dither is None, all values larger than 127 are set to 255 (white),
all other values to 0 (black). To use other thresholds, use the
point() method.
When converting from “RGBA” to “P” without a matrix argument,
this passes the operation to quantize(),
and dither and palette are ignored.
When converting from “PA”, if an “RGBA” palette is present, the alpha
channel from the image will be used instead of the values from the palette.
matrix – An optional conversion matrix. If given, this
should be 4- or 12-sequence containing floating point values.
dither – Dithering method, used when converting from
mode “RGB” to “P” or from “RGB” or “L” to “1”.
Available methods are Dither.NONE or Dither.FLOYDSTEINBERG
(default). Note that this is not used when matrix is supplied.
palette – Palette to use when converting from mode “RGB”
to “P”. Available palettes are Palette.WEB or
.
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 color
JPEG to grayscale while loading it.
If any changes are made, returns a tuple with the chosen mode and
box with coordinates of the original image within the altered one.
Note that this method modifies the Image object
in place. If the image has already been loaded, this method has no
effect.
Note: This method is not implemented for most images. It is
currently implemented only for JPEG and MPO images.
Parameters:
mode – The requested mode.
size – The requested size in pixels, as a 2-tuple:
(width, height).
A bilevel image (mode “1”) is treated as a grayscale (“L”)
image by this method.
If a mask is provided, the method employs the 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 grayscale image (“L”).
Parameters:
mask – An optional mask.
extrema – An optional tuple of manually-specified extrema.
Calculates the bounding box of the non-zero regions in the
image.
Parameters:
alpha_only – Optional flag, defaulting to True.
If True and the image has an alpha channel, trim transparent pixels.
Otherwise, trim pixels when all channels are zero.
Keyword-only argument.
Returns:
The bounding box is returned as a 4-tuple defining the
left, upper, right, and lower pixel coordinate. See
Coordinate system. If the image is completely empty, this
method returns None.
The colors will be in the image’s mode. For example, an RGB image will
return a tuple of (red, green, blue) color values, and a P image will
return the index of the color in the palette.
Parameters:
maxcolors – Maximum number of colors. If this number is
exceeded, this method returns None. The default limit is
256 colors.
Returns:
An unsorted list of (count, pixel) values.
:
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 the contents of this image as a tuple 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.
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 tuple containing pixel values.
]
,
...
]
Gets 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.
:
rawmode –
The mode in which to return the palette. None will
return the palette in its current mode.
Returns:
A list of color values [r, g, b, …], or None if the
image has no palette.
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. Counts are grouped into 256 bins for each band, even if
the image has more than 8 bits per band. 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 grayscale (“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 grayscale image (“L”).
Parameters:
mask – An optional mask.
extrema – An optional tuple of manually-specified extrema.
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)). See Coordinate system. 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 color. When creating RGB images, you can
also use color strings as supported by the ImageColor module. See
Colors for more information.
If a mask is given, this method updates only the regions
indicated by the mask. You can use either “1”, “L”, “LA”, “RGBA”
or “RGBa” images (if present, 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 will mix the two images together, including their alpha
channels if they have them.
See alpha_composite() if you want to
combine images with respect to their alpha channels.
Parameters:
im – Source image or pixel value (integer, float or tuple).
box –
An optional 4-tuple giving the region to paste into.
If a 2-tuple is used instead, it’s treated as the upper left
corner. If omitted or None, the source is pasted into the
upper left corner.
If an image is given as the second argument and there is no
third, the box defaults to (0, 0), and the second argument
is interpreted as a mask image.
Maps this image through a lookup table or function.
Parameters:
lut –
A lookup table, containing 256 (or 65536 if
self.mode==”I” and mode == “L”) 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.
classExample(Image.ImagePointHandler):defpoint(self,im:Image)->Image:# Return result
mode – Output mode (default is same as input). This can only be used if
the source image has mode “L” or “P”, and the output has mode “1” or the
source image mode is “I” and the output mode is “L”.
Copies pixel data from a flattened sequence object into the image. The
values should start at the upper left corner (0, 0), continue to the
end of the line, followed directly by the first value of the second
line, and so on. Data will be read 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 flattened sequence object. See Colors for more
information about values.
scale – An optional scale value. The default is 1.0.
offset – An optional offset value. The default is 0.0.
None
Attaches a palette to this image. The image must be a “P”, “PA”, “L”
or “LA” image.
The palette sequence must contain at most 256 colors, made up of one
integer value for each channel in the raw mode.
For example, if the raw mode is “RGB”, then it can contain at most 768
values, made up of red, green and blue values for the corresponding pixel
index in the 256 colors.
If the raw mode is “RGBA”, then it can contain at most 1024 values,
containing red, green, blue and alpha values.
Alternatively, an 8-bit string may be used instead of an integer sequence.
Parameters:
data – A palette sequence (either a list or a string).
rawmode – The raw mode of the palette. Either “RGB”, “RGBA”, “CMYK”, or a
mode that can be transformed to one of those modes (e.g. “R”, “RGBA;L”).
Modifies the pixel at the given position. The color is given as
a single numerical value for single-band images, and a tuple for
multi-band images. In addition to this, RGB and RGBA tuples are
accepted for P and PA images. See Colors for more information.
Note that this method is relatively slow. For more extensive changes,
use paste() or the ImageDraw
module instead.
dither – Dithering method, used when converting from
mode “RGB” to “P” or from “RGB” or “L” to “1”.
Available methods are Dither.NONE or Dither.FLOYDSTEINBERG
(default).
Returns a copy of the image reduced factor times.
If the size of the image is not dividable by factor,
the resulting size will be rounded up.
Parameters:
factor – A greater than 0 integer or tuple of two integers
for width and height separately.
box – An optional 4-tuple of ints providing
the source image region to be reduced.
The values must be within (0,0,width,height) rectangle.
If omitted or None, the entire source is used.
Image
Rewrites the image to reorder the palette.
Parameters:
dest_map – A list of indexes into the original palette.
e.g. [1,0] would swap a two item palette, and list(range(256))
is the identity transform.
box – An optional 4-tuple of floats providing
the source image region to be scaled.
The values must be within (0, 0, width, height) rectangle.
If omitted or None, the entire source is used.
reducing_gap – Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using reduce().
Second, resizing using regular resampling. The last step
changes size no less than by reducing_gap times.
reducing_gap may be None (no first step is performed)
or should be greater than 1.0. The bigger reducing_gap,
the closer the result to the fair resampling.
The smaller reducing_gap, the faster resizing.
With reducing_gap greater or equal to 3.0, the result is
indistinguishable from fair resampling in most cases.
The default value is None (no optimization).
Returns a rotated copy of this image. This method returns a
copy of this image, rotated the given number of degrees counter
clockwise around its centre.
Parameters:
angle – In degrees counterclockwise.
resample – An optional resampling filter. This can be
one of Resampling.NEAREST (use nearest neighbour),
Resampling.BILINEAR (linear interpolation in a 2x2
environment), or Resampling.BICUBIC (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image has
mode “1” or “P”, it is set to Resampling.NEAREST.
See Filters.
expand – Optional expansion flag. If true, expands the output
image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the
input image. Note that the expand flag assumes rotation around
the center and no translation.
center – Optional center of rotation (a 2-tuple). Origin is
the upper left corner. Default is the center of the image.
translate – An optional post-rotate translation (a 2-tuple).
fillcolor – An optional color for area outside the rotated image.
Saves this 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 in the
image format documentation for each writer.
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:
fp – A filename (string), os.PathLike object 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.
params –
Extra parameters to the image writer. These can also be
set on the image itself through encoderinfo. This is useful when
saving multiple images:
# Saving XMP data to a single imagefromPILimportImagered=Image.new("RGB",(1,1),"#f00")red.save("out.mpo",xmp=b"test")# Saving XMP data to the second frame of an image
Returns:
None
Raises:
ValueError – If the output format could not be determined
from the file name. Use the format option to solve this.
OSError – If the file could not be written. The file
may have been created, and may contain partial data.
:
frame – Frame number, starting at 0.
Raises:
EOFError – If the call attempts to seek beyond the end
of the sequence.
PIL.ImageShow.register()
The image is first saved to a temporary file. By default, it will be in
PNG format.
On Unix, the image is then opened using the xdg-open, display,
gm, eog or xv utility, depending on which one can be found.
On macOS, the image is opened with the native Preview application.
On Windows, the image is opened with the standard PNG display utility.
Parameters:
title – Optional title to use for the image window, where possible.
Make this image into a 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 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 – The requested size in pixels, as a 2-tuple:
(width, height).
reducing_gap – Apply optimization by resizing the image
in two steps. First, reducing the image by integer times
using reduce() or
draft() for JPEG images.
Second, resizing using regular resampling. The last step
changes size no less than by reducing_gap times.
reducing_gap may be None (no first step is performed)
or should be greater than 1.0. The bigger reducing_gap,
the closer the result to the fair resampling.
The smaller reducing_gap, the faster resizing.
With reducing_gap greater or equal to 3.0, the result is
indistinguishable from fair resampling in most cases.
The default value is 2.0 (very close to fair resampling
while still being faster in many cases).
Transforms this 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 in pixels, as a 2-tuple:
(width, height).
resample – Optional resampling filter. It can be one of
Resampling.NEAREST (use nearest neighbour),
Resampling.BILINEAR (linear interpolation in a 2x2
environment), or Resampling.BICUBIC (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image
has mode “1” or “P”, it is set to Resampling.NEAREST.
See: Filters.
fill – If method is an
ImageTransformHandler object, this is one of
the arguments passed to it. Otherwise, it is unused.
fillcolor – Optional fill color for the area outside the
transform in the output image.