Chapter 22: Advanced Python Programming - Using the Pillow Library to Edit Images
Image processing is a common requirement in many Python applications, including automation, web development, and data science. The Pillow library—an easy-to-use fork of the Python Imaging Library (PIL)—offers powerful tools for image manipulation such as resizing, cropping, filtering, and format conversion.
This chapter provides a practical introduction to Pillow, explaining its installation, basic operations, and advanced image editing techniques with code examples.
22.2 Installing Pillow
To install Pillow, use the Python package installer:
pip install Pillow
You can now import the library using:
from PIL import Image
22.3 Opening and Displaying Images
Opening an Image
from PIL import Image
img = Image.open("example.jpg")
img.show()
Getting Image Information
print(img.format) # JPEG, PNG, etc.
print(img.size) # (width, height)
print(img.mode) # RGB, L (grayscale), etc.
22.4 Saving Images
You can save an image in the same or different format:
img.save("new_image.png")
Convert before saving:
img.convert("L").save("grayscale.png")
22.5 Resizing and Cropping
Resizing an Image
resized = img.resize((200, 300))
resized.show()
Thumbnail (Maintains Aspect Ratio)
img.thumbnail((100, 100))
img.show()
Cropping
box = (100, 100, 400, 400) # (left, upper, right, lower)
cropped = img.crop(box)
cropped.show()
22.6 Rotating and Flipping
Rotate an Image
rotated = img.rotate(90) # degrees
rotated.show()
Flipping (Mirroring)
from PIL import ImageOps
flipped = ImageOps.mirror(img)
flipped.show()
22.7 Changing Image Modes
Convert to Grayscale
gray = img.convert("L")
gray.show()
Convert to RGB
rgb_img = img.convert("RGB")
22.8 Drawing on Images
Use the ImageDraw
module to draw shapes and text:
from PIL import ImageDraw, ImageFont
draw = ImageDraw.Draw(img)
draw.rectangle([50, 50, 150, 150], outline="red")
draw.text((60, 60), "Hello", fill="blue")
img.show()
To use custom fonts:
font = ImageFont.truetype("arial.ttf", 20)
draw.text((60, 60), "Hi", font=font, fill="black")
22.9 Applying Filters and Enhancements
Using Built-in Filters
from PIL import ImageFilter
blurred = img.filter(ImageFilter.BLUR)
sharpened = img.filter(ImageFilter.SHARPEN)
blurred.show()
sharpened.show()
Enhancing Images
from PIL import ImageEnhance
enhancer = ImageEnhance.Contrast(img)
enhanced = enhancer.enhance(1.5) # 1.0 = original
enhanced.show()
22.10 Batch Processing Images
Loop through a folder and apply operations:
import os
folder = "images"
for file in os.listdir(folder):
if file.endswith(".jpg"):
img_path = os.path.join(folder, file)
img = Image.open(img_path)
gray = img.convert("L")
gray.save(f"gray_{file}")
22.11 Creating New Images
You can create a blank image:
blank = Image.new("RGB", (200, 200), "white")
blank.show()
Then draw on it:
draw = ImageDraw.Draw(blank)
draw.line((0, 0, 200, 200), fill="blue", width=3)
22.12 Real-Life Use Cases
-
Thumbnails for Uploads: Resize and crop to standard dimensions.
-
Watermarking: Overlay text on images.
-
Grayscale Conversion: Useful in ML applications.
-
Format Conversion: Convert images between JPEG, PNG, etc.
-
Custom Captchas: Generate images with text and shapes.
22.13 Summary
The Pillow library provides a versatile and accessible way to handle image editing tasks in Python. From basic format conversions to more advanced tasks like filtering, drawing, and batch editing, Pillow is a vital tool in the Python developer’s toolbox.
22.14 Exercises
1. Write a Python script to open an image and convert it to grayscale.
2. Resize all .jpg
images in a folder to 300x300 pixels and save them.
3. Draw a red circle and text "Sample" on a blank image.
4. Apply sharpen and contrast enhancement filters to an image.
5. Create a batch converter that transforms images from PNG to JPEG format.
22.15 Review Questions
-
What is the purpose of the Pillow library?
-
How do you convert an image to grayscale using Pillow?
-
How can you draw shapes and text on an image?
-
What is the difference between
resize()
andthumbnail()
? -
Describe a practical use-case of Pillow in web development or automation.
Comments
Post a Comment
"Thank you for seeking advice on your career journey! Our team is dedicated to providing personalized guidance on education and success. Please share your specific questions or concerns, and we'll assist you in navigating the path to a fulfilling and successful career."