← 输入框|python.land|刷新

Python Image Processing With Pillow

The Pillow Python Imaging Library is ideal for image processing. Typically, it’s used for archival and batch processing applications. Of course, you’re free to use it for anything else you can think of. You can use the library to:

  • Create thumbnails
  • Resize and crop images
  • Convert between file formats
  • Convert images to grayscale
  • Print images
  • Get a histogram (ideal for automatic contrast enhancement)
  • Rotate images
  • Apply filters like blur

Installing the image processing package

Pillow is a fork and continuation of the original Python Imaging Library (PIL). Install it inside a virtual environment with the pip install command:

python -m pip install pillow

Or, if you manage your project with uv, run uv add pillow.

After this, you can import the module. Even though the package is called Pillow, the module is still called PIL, so you import parts of it with the from PIL import ..... syntax.

Processing images

Pillow offers several filters which become available after importing ImageFilter. For example, to blur an image, use:

from PIL import Image, ImageFilter

im = Image.open("kittens.jpg")
blurred = im.filter(ImageFilter.BLUR)Code language: Python (python)

Other filters include SHARPEN, SMOOTH, and EDGE_ENHANCE. For a complete list of filters, check the reference docs on ImageFilter.

To rotate an image by 180 degrees:

rotated_image = im.rotate(180) Code language: Python (python)

And finally, to save the results of your hard work:

rotated_image.save("rotated.jpg")Code language: Python (python)

Resize an image

To resize an image to an exact size, use resize() with a tuple of (width, height). It returns a new image and leaves the original alone:

small = im.resize((800, 600))
print(small.size)
# (800, 600)Code language: Python (python)

Be careful: resize() doesn’t care about the aspect ratio. My kittens photo is 1920 by 1357 pixels, so squeezing it into 800 by 600 makes the kittens look a bit wider than they are.

Create a thumbnail

Usually, you want an image that fits within a certain size while keeping its proportions. That’s what thumbnail() does. Unlike resize(), it changes the image itself, so make a copy first if you still need the original:

thumb = im.copy()
thumb.thumbnail((400, 400))
print(thumb.size)
# (400, 283)Code language: Python (python)

The result is at most 400 pixels wide and 400 pixels high, with the original proportions intact.

Crop an image

To cut out part of an image, pass a box to crop(). The box is a tuple of four numbers: the left, upper, right, and lower pixel coordinates, where (0, 0) is the top-left corner:

# box = (left, upper, right, lower)
cropped = im.crop((100, 100, 600, 400))
print(cropped.size)
# (500, 300)Code language: Python (python)

Convert to grayscale

Every image has a mode, like RGB for color photos, RGBA for color with transparency, or L for grayscale. With convert(), you change the mode. To turn a photo into black and white:

gray = im.convert("L")
gray.save("kittens_gray.jpg")Code language: Python (python)

A grayscale image is also the easiest to analyze. gray.histogram() returns a list of 256 numbers: how many pixels there are of each brightness, from black (0) to white (255).

Convert between file formats

Pillow picks the file format from the extension you give to save(). So converting a JPEG to a PNG is a single line:

im.save("kittens.png")Code language: Python (python)

The other way around has a catch. PNG images often have transparency (mode RGBA), and JPEG doesn’t support that:

logo = Image.open("logo.png")
print(logo.mode)
# RGBA

logo.save("logo.jpg")
# OSError: cannot write mode RGBA as JPEGCode language: Python (python)

Convert the image to RGB first, and it works: logo.convert("RGB").save("logo.jpg"). The image file formats page in the Pillow docs lists all formats and their options, like the JPEG quality setting.

Batch process images

Where Pillow really shines is processing lots of images at once. This script creates a thumbnail of every JPEG file in the current directory and saves it in a thumbs directory, using pathlib to find the files:

from pathlib import Path
from PIL import Image

Path('thumbs').mkdir(exist_ok=True)

for path in Path('.').glob('*.jpg'):
    with Image.open(path) as im:
        im.thumbnail((400, 400))
        im.save(Path('thumbs') / path.name)Code language: Python (python)

Opening the image with a with statement makes sure each file is closed once you’re done with it, which matters when you loop over hundreds of files.

Displaying images

Besides image processing, this library can also be used to display images on the screen. Here’s some example code to display a file called kittens.jpg:

from PIL import Image

im = Image.open("kittens.jpg")
im.show()
print(im.format, im.size, im.mode)
# JPEG (1920, 1357) RGBCode language: Python (python)

show() saves the image to a temporary file and opens it in your system’s default image viewer.

In the following animated gif, I demonstrate how to use Pillow right from IPython:

Demonstration of python image processing using Pillow
Showing some kittens using Pillow from IPython

Further reading

The library has much more to offer. To learn everything about Python image processing using Pillow, it’s best to head over to the official tutorial!

Leave a Comment