The most important class in the Python Imaging Library is the
Image class, defined in the module with the same name.
You can create instances of this class in several ways; either by loading
images from files, processing other images, or creating images from scratch.
To load an image from a file, use the open() function
in the Image module:
>>> fromPILimportImage>>> im
=
Image
.
open
(
"hopper.ppm"
)
If successful, this function returns an Image object.
You can now use instance attributes to examine the file contents:
The format attribute identifies the source of an
image. If the image was not read from a file, it is set to None. The size
attribute is a 2-tuple containing width and height (in pixels). The
mode attribute defines the number and names of the
bands in the image, and also the pixel type and depth. Common modes are “L”
(luminance) for grayscale images, “RGB” for true color images, and “CMYK” for
pre-press images.
If the file cannot be opened, an OSError exception is raised.
Once you have an instance of the Image class, you can use
the methods defined by this class to process and manipulate the image. For
example, let’s display the image we just loaded:
>>> im.show()
The following sections provide an overview of the different functions provided in this library.
Reading and writing images
The Python Imaging Library supports a wide variety of image file formats. To
read files from disk, use the open() function in the
Image module. You don’t have to know the file format to open a
file. The library automatically determines the format based on the contents of
the file.
To save a file, use the save() method of the
Image class. When saving files, the name becomes
important. Unless you specify the format, the library uses the filename
extension to discover which file storage format to use.
A second argument can be supplied to the save()
method which explicitly specifies a file format. If you use a non-standard
extension, you must always specify the format this way:
The Image class contains methods allowing you to
manipulate regions within an image. To extract a sub-rectangle from an image,
use the crop() method.
Copying a subrectangle from an image
box=(0,0,64,64)region=im.crop(box)
The region is defined by a 4-tuple, where coordinates are (left, upper, right,
lower). The Python Imaging Library uses a coordinate system with (0, 0) in the
upper left corner. Also note that coordinates refer to positions between the
pixels, so the region in the above example is exactly 64x64 pixels.
The region could now be processed in a certain manner and pasted back.
When pasting regions back, the size of the region must match the given region
exactly. In addition, the region cannot extend outside the image. However, the
modes of the original image and the region do not need to match. If they don’t,
the region is automatically converted before being pasted (see the section on
Color transforms below for details).
Here’s an additional example:
Rolling an image
defroll(im:Image.Image,delta:int)->Image.Image:"""Roll an image sideways."""xsize,ysize=im.sizedelta=delta%xsizeifdelta==0:return
Note that for a single-band image, split() returns
the image itself. To work with individual color bands, you may want to convert
the image to “RGB” first.
Geometrical transforms
The PIL.Image.Image class contains methods to
resize() and rotate() an
image. The former takes a tuple giving the new size, the latter the angle in
degrees counterclockwise.
To rotate the image in 90 degree steps, you can either use the
rotate() method or the
transpose() method. The latter can also be used to
flip an image around its horizontal or vertical axis.
Transposing an image
out=im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
out=im.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
Relative resizing
Instead of calculating the size of the new image when resizing, you can also
choose to resize relative to a given size.
The library supports transformations between each supported mode and the “L”
and “RGB” modes. To convert between other modes, you may have to use an
intermediate image (typically an “RGB” image).
Image enhancement
The Python Imaging Library provides a number of methods and modules that can be
used to enhance images.
Filters
The ImageFilter module contains a number of pre-defined
enhancement filters that can be used with the
filter() method.
The point() method can be used to translate the pixel
values of an image (e.g. image contrast manipulation). In most cases, a
function object expecting one argument can be passed to this method. Each
pixel is processed according to that function:
Applying point transforms
# multiply each pixel by 20out=im.point(lambdai:i*20)
Using the above technique, you can quickly apply any simple expression to an
image. You can also combine the and
methods to selectively modify an image:
Enhancement
For more advanced image enhancement, you can use the classes in the
ImageEnhance module. Once created from an image, an enhancement
object can be used to quickly try out different settings.
You can adjust contrast, brightness, color balance and sharpness in this way.
The Python Imaging Library contains some basic support for image sequences
(also called animation formats). Supported sequence formats include FLI/FLC,
GIF, and a few experimental formats. TIFF files can also contain more than one
frame.
When you open a sequence file, PIL automatically loads the first frame in the
sequence. You can use the seek and tell methods to move between different
frames:
Reading sequences
fromPILimportImagewithImage.open("animation.gif")asim:im.seek(1)# skip to the second frametry:while1:im.seek(im.tell()+1)# do something to imexceptEOFError:pass# end of sequence
As seen in this example, you’ll get an EOFError exception when the
sequence ends.
Writing sequences
You can create animated GIFs with Pillow, e.g.
fromPILimportImage# List of image filenamesimage_filenames=["hopper.jpg","rotated_hopper_270.jpg","rotated_hopper_180.jpg","rotated_hopper_90.jpg",]# Open images and create a listimages=[Image.open(filename)forfilenameinimage_filenames]
fromPILimportImageSequenceforframeinImageSequence.Iterator(im):# ...do something to frame...
PostScript printing
The Python Imaging Library includes functions to print images, text and
graphics on PostScript printers. Here’s a simple example:
Drawing PostScript
fromPILimportImage,PSDrawimportos# Define the PostScript fileps_file=open("hopper.ps","wb")# Create a PSDraw objectps=PSDraw.PSDraw(ps_file)# Start the documentps.begin_document()# Set the text to be drawntext="Hopper"# Define the PostScript fontfont_name="Helvetica-Narrow-Bold"font_size=36# Calculate text size (approximation as PSDraw doesn't provide direct method)# Assuming average character width as 0.6 of the font sizetext_width=len(text)*font_size*0.6text_height=font_size# Set the position (top-center)page_width,page_height=595,842# A4 size in pointstext_x=(page_width-text_width)//2text_y=page_height-text_height-50# Distance from the top of the page# Load the imageimage_path="hopper.ppm"# Update this with your image pathwithImage.open(image_path)asim:# Resize the image if it's too largeim.thumbnail((page_width-100,page_height//2))# Define the box where the image will be placedimg_x=(page_width-im.width)//2img_y=text_y+text_height-200# 200 points below the text# Draw the image (75 dpi)ps.image((img_x,img_y,img_x+im.width,img_y+im.height),im,75)# Draw the textps.setfont(font_name,font_size)ps.text((text_x,text_y),text)# End the documentps.end_document()ps_file.close()
More on reading images
As described earlier, the open() function of the
Image module is used to open an image file. In most cases, you
simply pass it the filename as an argument. Image.open() can be used as a
context manager:
If everything goes well, the result is an PIL.Image.Image object.
Otherwise, an OSError exception is raised.
You can use a file-like object instead of the filename. The object must
implement file.read, file.seek and file.tell methods,
and be opened in binary mode.
Note that the library rewinds the file (using seek(0)) before reading the
image header. In addition, seek will also be used when the image data is read
(by the load method). If the image file is embedded in a larger file, such as a
tar file, you can use the ContainerIO or
modules to access it.
Some decoders allow you to manipulate the image while reading it from a file.
This can often be used to speed up decoding when creating thumbnails (when
speed is usually more important than quality) and printing to a monochrome
laser printer (when only a grayscale version of the image is needed).
The draft() method manipulates an opened but not yet
loaded image so it as closely as possible matches the given mode and size. This
is done by reconfiguring the image decoder.
Note that the resulting image may not exactly match the requested mode and
size. To make sure that the image is not larger than the given size, use the
thumbnail method instead.
+
".thumbnail"
if
infile
!=
outfile
:
try
:
with
Image
.
open
(
infile
)
as
im
:
im
.
thumbnail
(
size
)
im
.
save
(
outfile
,
"JPEG"
)
except
OSError
:
print
(
"cannot create thumbnail for"
,
infile
)
It is important to note that the library doesn’t decode or load the raster data
unless it really has to. When you open a file, the file header is read to
determine the file format and extract things like mode, size, and other
properties required to decode the file, but the rest of the file is not
processed until later.
This means that opening an image file is a fast operation, which is independent
of the file size and compression type. Here’s a simple script to quickly
identify a set of image files:
f
"
{
im
.
size
}
x
{
im
.
mode
}
"
)
except
OSError
:
pass
im
part1
=
im
.
crop
((
0
,
0
,
delta
,
ysize
))
part2
=
im
.
crop
((
delta
,
0
,
xsize
,
ysize
))
im
.
paste
(
part1
,
(
xsize
-
delta
,
0
,
xsize
,
ysize
))
im
.
paste
(
part2
,
(
0
,
0
,
xsize
-
delta
,
ysize
))
return
im
Or if you would like to merge two images into a wider image:
(
im1
.
size
[
1
],
im2
.
size
[
1
])
im
=
Image
.
new
(
"RGBA"
,
(
w
,
h
))
im
.
paste
(
im1
)
im
.
paste
(
im2
,
(
im1
.
size
[
0
],
0
))
return
im
For more advanced tricks, the paste method can also take a transparency mask as
an optional argument. In this mask, the value 255 indicates that the pasted
image is opaque in that position (that is, the pasted image should be used as
is). The value 0 means that the pasted image is completely transparent. Values
in-between indicate different levels of transparency. For example, pasting an
RGBA image and also using it as the mask would paste the opaque portion
of the image but not its transparent background.
The Python Imaging Library also allows you to work with the individual bands of
a multi-band image, such as an RGB image. The split method creates a set of new
images, each containing one band from the original multi-band image. The merge
function takes a mode and a tuple of images, and combines them into a new
image. The following sample swaps the three bands of an RGB image:
out=im.transpose(Image.Transpose.ROTATE_90)
out=im.transpose(Image.Transpose.ROTATE_180)
out=im.transpose(Image.Transpose.ROTATE_270)
transpose(ROTATE) operations can also be performed identically with
rotate() operations, provided the expand flag is
true, to provide for the same changes to the image’s size.
A more general form of image transformations can be carried out via the
transform() method.
# split the image into individual bandssource=im.split()R,G,B=0,1,2# select regions where red is less than 100mask=source[R].point(lambdai:i<100and255)# process the green bandout=source[G].point(lambdai:i*0.7)# paste the processed band back, but only where red was < 100source[G].paste(out,None,mask)# build a new multiband imageim=Image.merge(im.mode,source)
Note the syntax used to create the mask:
imout=im.point(lambdai:expressionand255)
Python only evaluates the portion of a logical expression as is necessary to
determine the outcome, and returns the last value examined as the result of the
expression. So if the expression above is false (0), Python does not look at
the second operand, and thus returns 0. Otherwise, it returns 255.
"30% more contrast"
)
# Save the images as an animated GIF
images
[
0
]
.
save
(
"animated_hopper.gif"
,
append_images
=
images
[
1
:],
duration
=
500
,
# duration of each frame in milliseconds
loop
=
0
,
# loop forever
)
The following class lets you use the for-statement to loop over the sequence:
TarIO
img
.
mode
!=
"RGB"
:
img
=
img
.
convert
(
"RGB"
)
img
.
save
(
dest_path
,
"JPEG"
,
optimize
=
True
,
quality
=
80
)
paths
=
glob
.
glob
(
"*.png"
)
for
path
in
paths
:
compress_image
(
path
,
path
[:
-
4
]
+
".jpg"
)
Since images can also be opened from a Path from the pathlib module,
the example could be modified to use pathlib instead of the glob
module.