Fundamentals 6 min read

Advanced Usage of Python Pillow Library for Image Processing

This article introduces advanced techniques using Python's Pillow library, covering filters, image blending, word cloud generation, dynamic resizing, border addition, GIF creation, slicing, flipping, color space conversion, and batch processing, with complete code examples to enhance image manipulation capabilities.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Advanced Usage of Python Pillow Library for Image Processing

Python's Pillow library provides powerful capabilities for image manipulation, and this article demonstrates ten advanced techniques with full code examples.

1. Advanced Filter Application

from PIL import Image, ImageFilter

def apply_advanced_filter(image_path, output_path):
    img = Image.open(image_path)
    img_with_filter = img.filter(ImageFilter.GaussianBlur(radius=2))
    img_with_filter.save(output_path)

apply_advanced_filter('input.jpg', 'blurred.jpg')

2. Image Blending

from PIL import Image

def blend_images(image1_path, image2_path, output_path):
    img1 = Image.open(image1_path).convert("RGBA")
    img2 = Image.open(image2_path).convert("RGBA")
    blended = Image.blend(img1, img2, alpha=0.5)
    blended.save(output_path)

blend_images('image1.jpg', 'image2.jpg', 'blended.jpg')

3. Word Cloud Generation

from PIL import Image, ImageDraw, ImageFont

def generate_word_cloud(text, font_path, output_path):
    img = Image.new('RGB', (800, 400), color='white')
    d = ImageDraw.Draw(img)
    font = ImageFont.truetype(font_path, 36)
    d.text((10, 10), text, fill=(0, 0, 0), font=font)
    img.save(output_path)

generate_word_cloud('Python is awesome!', 'arial.ttf', 'word_cloud.jpg')

4. Dynamic Image Resizing

from PIL import Image

def resize_image(image_path, max_size, output_path):
    img = Image.open(image_path)
    img.thumbnail(max_size)
    img.save(output_path)

resize_image('large_image.jpg', (800, 800), 'resized.jpg')

5. Adding Borders Dynamically

from PIL import Image, ImageOps

def add_border(image_path, border_size, output_path):
    img = Image.open(image_path)
    img_with_border = ImageOps.expand(img, border=border_size, fill='black')
    img_with_border.save(output_path)

add_border('image.jpg', 30, 'bordered.jpg')

6. Creating Animated GIFs

from PIL import Image

def create_gif(image_paths, output_path, duration=200):
    frames = [Image.open(image) for image in image_paths]
    frames[0].save(output_path, format='GIF', append_images=frames[1:], save_all=True, duration=duration, loop=0)

create_gif(['frame1.png', 'frame2.png'], 'animation.gif')

7. Image Slicing and Stitching

from PIL import Image

def slice_and_stitch(image_path, slices, output_path):
    img = Image.open(image_path)
    width, height = img.size
    slice_width = width // slices
    slices = [img.crop((i * slice_width, 0, (i + 1) * slice_width, height)) for i in range(slices)]
    stitched = Image.new('RGB', (width, height))
    for i, slice in enumerate(slices):
        stitched.paste(slice, (i * slice_width, 0))
    stitched.save(output_path)

slice_and_stitch('wide_image.jpg', 3, 'stitched.jpg')

8. Image Flipping and Mirroring

from PIL import Image

def flip_image(image_path, output_path):
    img = Image.open(image_path)
    flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)
    flipped_img.save(output_path)

flip_image('original.jpg', 'flipped.jpg')

9. Color Space Conversion

from PIL import Image

def change_color_space(image_path, output_path):
    img = Image.open(image_path)
    img_rgb = img.convert('RGB')
    img_gray = img.convert('L')
    img_rgb.save(output_path.replace('.jpg', '_rgb.jpg'))
    img_gray.save(output_path.replace('.jpg', '_gray.jpg'))

change_color_space('colorful.jpg', 'converted.jpg')

10. Batch Image Processing

from PIL import Image
import os

def batch_process(directory, operation):
    for filename in os.listdir(directory):
        if filename.endswith('.jpg'):
            img = Image.open(os.path.join(directory, filename))
            # Apply your operation here, e.g., img.thumbnail((800, 800))
            img.save(os.path.join(directory, filename))

batch_process('/path/to/images', lambda img: img.thumbnail((800, 800)))

These examples illustrate how Pillow can handle everything from simple filters to complex animations, empowering developers to create compelling visual effects for personal projects or commercial applications.

Pythonimage processingcode examplespillowAdvanced Techniques
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.