Let’s learn how to do Image Processing with Python Pillow, but first we want to talk about Python Pillow library, also we want to talk about the installation process.
What is Pillow ?
Pillow is an open source Python library for image processing, Pillow is a fork of Python Imaging Library (PIL). there are a lot of tools in pillow that you can use for working with images, like opening and saving images, resizing, cropping, transforming and converting between image formats. Pillow is compatible with Python 2.7, as well as Python 3.x. Python Pillow supports different image formats like PNG, JPEG, BMP, GIF and TIFF.
How to Install Python Pillow?
You can Install Pillow using pip command, open your terminal or command prompt and write this command.
1 |
pip install pillow |
Opening and Displaying Image in Pillow
This code snippet opens an image and displays it using the default image viewer.
1 2 3 4 5 6 7 |
from PIL import Image # Open an image file img = Image.open("python.png") # Display the image img.show() |
Run the code and this will be the result
Resizing Image in Python Pillow
This code resizes the image to a width of 300 pixels and a height of 200 pixels and saves the resized image as resized_example.jpg.
1 2 3 4 5 6 7 8 9 10 |
from PIL import Image # Open an image file img = Image.open("python.png") # Resize image to specified size resized_img = img.resize((300, 200)) # Save the resized image resized_img.save("resized_example.png") |
Cropping Image with Python Pillow
This code crops the image to a rectangular region defined by the coordinates (100, 100) for the top-left corner and (400, 300) for the bottom-right corner, and after that saves the cropped image as cropped_example.jpg.
1 2 3 4 5 6 7 8 9 10 |
from PIL import Image # Open an image file img = Image.open("example.jpg") # Crop the image cropped_img = img.crop((100, 100, 400, 300)) # Save the cropped image cropped_img.save("cropped_example.jpg") |
Converting Image Formats with Python Pillow
This code opens an image file in PNG format and converts it to JPEG format, after that it saves the converted image as example.jpg.
1 2 3 4 5 6 7 8 9 10 |
from PIL import Image # Open an image file img = Image.open("python.png") # Convert image to JPEG format img_jpeg = img.convert("RGB") # Save converted image img_jpeg.save("example.jpg") |
Applying Image Filters with Pillow
This code applies a Gaussian blur filter to the image with a radius of 5 pixels and saves the blurred image as blurred_example.jpg.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from PIL import Image, ImageFilter # Open an image file img = Image.open("python.png") # Convert the image to RGB mode img = img.convert("RGB") # Apply a Gaussian blur filter blurred_img = img.filter(ImageFilter.GaussianBlur(5)) # Save the blurred image blurred_img.save("blurred_example.png") |
Subscribe and Get Free Video Courses & Articles in your Email