Pillow is a powerful image processing library in Python that provides an easy-to-use interface for performing various image manipulation operations. In this tutorial, you will learn how to utilize Pillow to perform basic image manipulation tasks.
Installing Pillow:
First, you need to install Pillow. You can do this using pip by running the following command:
pip install pillow
Loading and Displaying Images:
Let’s start by loading an image using Pillow and displaying it.
from PIL import Image
# Load an image
image = Image.open('image.jpg')
# Display the image
image.show()
Basic Image Manipulation:
Now, let’s explore some basic image manipulation techniques using Pillow.
Resizing Images:
You can resize images using the resize()
method.
# Resize the image
resized_image = image.resize((width, height))
Rotating Images:
Rotate an image using the rotate()
method.
# Rotate the image by 90 degrees
rotated_image = image.rotate(90)
Converting Image Modes:
Convert between different color modes using the convert()
method.
# Convert the image to grayscale
grayscale_image = image.convert('L')
Applying Filters:
Pillow provides various filters for image enhancement. Let’s apply some filters to our image.
from PIL import ImageFilter
# Apply a blur filter
blurred_image = image.filter(ImageFilter.BLUR)
# Apply a sharpen filter
sharpened_image = image.filter(ImageFilter.SHARPEN)
Example and Real-world Case: Enhancing Images for OCR (Optical Character Recognition):
Case Description: Imagine you’re working on an OCR project and need to enhance image quality before processing with OCR algorithm. You’ll use Pillow to improve image quality.
from PIL import ImageEnhance
# Load a low-quality image
low_quality_image = Image.open('low_quality_image.jpg')
# Enhance image sharpness
enhancer = ImageEnhance.Sharpness(low_quality_image)
high_sharpness_image = enhancer.enhance(2.0)
# Save the enhanced image
high_sharpness_image.save('high_sharpness_image.jpg')
Conclusion:
In this tutorial, you’ve learned the basics of image manipulation using Pillow in Python. Pillow offers a wide range of functions for manipulating images, making it a valuable tool for various projects. Experiment with different techniques and explore Pillow’s documentation for more advanced features.