Image Processing Library in Python: Pillow

Mastering Python can change your life! — Become a builder of the Python application ecosystem.In the future, artificial intelligence will increasingly take over our jobs, and one-person companies are rapidly emerging. Various intelligent agents and applications are transforming countless industries. I am also using code and AI projects to deploy and build many applications. From LLM large models to OCR, TTS, ASR, RVC, Agents, digital humans, to basic file operations in Python, audio and video operations, browser web operations, data analysis, knowledge processing RAG, image processing, software design, hardware and system control, etc., I aim to create a world of enhanced efficiency, amplifying your ideas and capabilities through code. Today, I will introduce the image processing library Pillow.Image processing libraries include Pillow, OpenCV, imageio, TorchVision, scikit-image, dlib, Pillow-SIMD, with the first four being commonly used. Among them, Pillow has become the developer’s choice due to its simple API and powerful features. As a modern branch of PIL (Python Imaging Library), it supports processing of over 30 image formats.It can help you batch process images for cropping, adding watermarks, enhancing, format conversion, etc. I have developed various software for factory label generation, image cleaning, and more using it.Image Processing Library in Python: PillowImage Library Comparison

Comparison Dimension Pillow OpenCV imageio
Core Positioning Lightweight image processing library focused on basic operations and format handling, with a simple and easy-to-use API. Professional library in the field of computer vision, focusing on real-time processing, feature extraction, object detection, and other advanced functions. Focuses on reading and writing operations for images/videos, supports various formats, often used as a data input/output tool in conjunction with other libraries.
Underlying Implementation Implemented in Python, encapsulating the functionality of PIL, with a pure Python interface. Implemented in C/C++, providing Python bindings, with high runtime efficiency. Implemented in Python, with some functions relying on other libraries (e.g., FFmpeg).
Supported Formats Supports common formats (JPG, PNG, GIF, BMP, etc.), with limited support for special formats. Supports mainstream image/video formats, with better support for video streams and camera inputs. Supports a wide range of formats (including medical images, 3D images, videos, etc.), extensible through plugins.
Core Functions – Basic operations: scaling, cropping, rotating, format conversion– Simple effects: filters, text watermarks– Color mode processing: grayscale conversion, channel separation and merging – Computer vision: object detection, edge detection, feature matching– Real-time processing: video stream analysis, camera invocation– Matrix operations: image operations based on NumPy arrays – Read/write functions: reading/saving images and videos in various formats– Simple processing: basic frame extraction, format conversion
Data Structure Based on its own <span>Image</span> object, needs to be converted to a NumPy array for numerical operations. Directly uses NumPy arrays to store images (BGR channel order), facilitating numerical calculations and matrix operations. Returns NumPy arrays (images) or lists (video frames) after reading, compatible with numerical operations.
Applicable Scenarios Simple image processing tasks: format conversion, size adjustment, adding watermarks, etc. Computer vision projects: object tracking, face recognition, image segmentation, real-time video processing, and other advanced tasks. Cross-format data read/write: handling special format images/videos, batch importing/exporting data, preprocessing in conjunction with other libraries.
Learning Curve Low, API design is intuitive, suitable for beginners to quickly get started. High, involves many computer vision concepts and matrix operations, requiring a certain mathematical foundation. Low, core functions focus on read/write, simple interface, easy to master.
Dependency Situation Fewer dependencies, easy installation. More dependencies (e.g., FFmpeg, numpy), installation process may be complex (especially in Windows environments). Basic functions have few dependencies, but extended formats require additional plugin installations (e.g., <span>imageio-ffmpeg</span>).
Typical Application Examples – Batch converting image formats– Generating thumbnails– Adding text or watermarks to images – Face detection and recognition– Real-time tracking of moving objects in video surveillance– Image stitching and panorama synthesis – Reading medical DICOM format images– Extracting frames from videos and saving as images– Batch reading image data in different formats
Advantages Lightweight, easy to use, suitable for quickly implementing simple image processing needs. Powerful features, efficient operation, supports complex computer vision tasks and real-time processing. Extremely strong format compatibility, comprehensive read/write functions, suitable as an intermediate tool for data processing.
Limitations Does not support complex computer vision algorithms, lower efficiency when processing large images or videos. Relatively cumbersome interface, may be too heavyweight for simple image processing tasks. Does not provide complex image processing functions by itself, needs to be used in conjunction with other libraries (e.g., Pillow, OpenCV).

Installing Pillow

pip install pillow

Pillow Architecture

Class Name Main Functionality

Image Core class for image operations (open/save/process)

ImageDraw Provides 2D graphics drawing functionality

ImageFont Font management

ImageFilter Image filter processing

ImageEnhance Image enhancement tools

ImageOps Preset image operations

ImageColor Color management

Function Name Description

Image.point() Pixel-level operations (e.g., threshold processing)

Image.quantize() Reduce the number of colors (generate indexed images)

Image.getbands() Get image channel types (‘R’,’G’,’B’)

Image.getextrema() Get min/max values for each channel

Image.transform() Complex geometric transformations

Image.composite() Blend two images

Image.eval() Apply function to each pixel

Basic Image Operations

from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance, ImageOps, ImageColor
import os
from pathlib import Path

# Create output directory (global)
output_dir = Path("output_images")
output_dir.mkdir(exist_ok=True)

def open_image(image_path):
    """Open image file"""
    return Image.open(image_path)

def show_image(img):
    """Display image (system default viewer)"""
    img.show()

def save_image(img, output_path, format=None):
    """Save image, can specify format"""
    img.save(output_path, format=format)

def get_image_info(img):
    """Get image information"""
    return {
        'format': img.format,
        'size': img.size,
        'mode': img.mode
    }

Resizing and Thumbnail Generation

def resize_image(img, size, resample=Image.NEAREST):
    """Resize image"""
    return img.resize(size, resample=resample)

def create_thumbnail(img, size, save_path=None):
    """Create thumbnail (in-place operation)"""
    img.thumbnail(size)
    if save_path:
        img.save(save_path)
    return img

Image Cropping and Rotation

def crop_image(img, box):
    """Crop image (left, top, right, bottom)"""
    return img.crop(box)

def rotate_image(img, angle, expand=True):
    """Rotate image (counterclockwise)"""
    return img.rotate(angle, expand=expand)

Applying Image Filters

def apply_filter(img, filter_type, **kwargs):
    """Apply image filter"""
    if filter_type == 'gaussian_blur':
        return img.filter(ImageFilter.GaussianBlur(radius=kwargs.get('radius', 5)))
    elif filter_type == 'edge_enhance':
        return img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    elif filter_type == 'blur':
        return img.filter(ImageFilter.BLUR)
    elif filter_type == 'contour':
        return img.filter(ImageFilter.CONTOUR)
    elif filter_type == 'emboss':
        return img.filter(ImageFilter.EMBOSS)
    elif filter_type == 'unsharp_mask':
        return img.filter(ImageFilter.UnsharpMask(
            radius=kwargs.get('radius', 2),
            percent=kwargs.get('percent', 150)
        ))
    else:
        raise ValueError(f"Unknown filter type: {filter_type}")

# Color Mode Conversion
def convert_image(img, mode):
    """Convert image color mode"""
    return img.convert(mode)

Adding Text and Image Watermarks

def add_text_watermark(img, text, position, font_path=None, font_size=36, color='red'):
    """Add text watermark"""
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default()
    draw.text(position, text, fill=color, font=font)
    return img
def overlay_image(img, overlay_img, position, use_mask=True):
    """Overlay layer"""
    if use_mask and overlay_img.mode == 'RGBA':
        img.paste(overlay_img, position, overlay_img)
    else:
        img.paste(overlay_img, position)
    return img

Creating New Images and Pixel Operations

def create_new_image(mode, size, color):
    """Create new image"""
    return Image.new(mode, size, color=color)
def split_channels(img):
    """Separate image channels"""
    return img.split()
def merge_channels(channels, mode):
    """Merge image channels"""
    return Image.merge(mode, channels)
def get_pixel(img, position):
    """Get pixel value"""
    return img.getpixel(position)
def set_pixel(img, position, color):
    """Set pixel value"""
    img.putpixel(position, color)
    return img

Drawing Operations

def draw_shapes(img, shapes):
    """Draw geometric shapes on the image"""
    draw = ImageDraw.Draw(img)
    for shape in shapes:
        shape_type = shape['type']
        if shape_type == 'rectangle':
            draw.rectangle(
                shape['coords'],
                outline=shape.get('outline', 'black'),
                width=shape.get('width', 1),
                fill=shape.get('fill')
            )
        elif shape_type == 'ellipse':
            draw.ellipse(
                shape['coords'],
                outline=shape.get('outline', 'black'),
                width=shape.get('width', 1),
                fill=shape.get('fill')
            )
        elif shape_type == 'polygon':
            draw.polygon(
                shape['coords'],
                outline=shape.get('outline', 'black'),
                fill=shape.get('fill')
            )
        elif shape_type == 'arc':
            draw.arc(
                shape['coords'],
                start=shape['start'],
                end=shape['end'],
                fill=shape.get('fill', 'black'),
                width=shape.get('width', 1)
            )
    return img

Text Processing

def draw_text(img, text, position, font_path=None, font_size=24, color='black'):
    """Draw text on the image"""
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(font_path, font_size) if font_path else ImageFont.load_default()
    draw.text(position, text, fill=color, font=font)
    return img

Image Enhancement

def enhance_image(img, enhancement_type, factor):
    """Enhance image properties"""
    if enhancement_type == 'color':
        enhancer = ImageEnhance.Color(img)
    elif enhancement_type == 'brightness':
        enhancer = ImageEnhance.Brightness(img)
    elif enhancement_type == 'contrast':
        enhancer = ImageEnhance.Contrast(img)
    elif enhancement_type == 'sharpness':
        enhancer = ImageEnhance.Sharpness(img)
    else:
        raise ValueError(f"Unknown enhancement type: {enhancement_type}")
    return enhancer.enhance(factor)

Preset Operations

def apply_image_ops(img, operation, **kwargs):
    """Apply preset image operations"""
    if operation == 'autocontrast':
        return ImageOps.autocontrast(img)
    elif operation == 'expand':
        return ImageOps.expand(
            img,
            border=kwargs.get('border', 10),
            fill=kwargs.get('fill', 'black')
        )
    elif operation == 'invert':
        return ImageOps.invert(img.convert('RGB'))
    elif operation == 'mirror':
        return ImageOps.mirror(img)
    elif operation == 'flip':
        return ImageOps.flip(img)
    elif operation == 'grayscale':
        return ImageOps.grayscale(img)
    elif operation == 'equalize':
        return ImageOps.equalize(img)
    else:
        raise ValueError(f"Unknown operation: {operation}")

Pillow also supports more advanced features:

✅ Image histogram analysis

✅ Pixel-level operations

✅ EXIF data reading

✅ Animated GIF processing

By mastering these core methods, you can solve 90% of daily image processing needs.

Pillow Official Reference

https://pillow.readthedocs.io/en/stable/

Image Processing Library in Python: Pillow

Historical Articles on Python:

Fundamental Articles on Learning Python

Basics of Basics (Suitable for Beginners)

Must-Know Python: The OS Standard Library

A Comprehensive Overview of Python Built-in Functions

Applications of Regular Expressions in Office Work

Must-Know Python: The sys Standard Library

Python Knowledge Handy Reference

Using Domestic Sources for pip to Speed Up Python Library Installation

Usage of Python’s lambda

Must-Know Python: The socket Library

Four Ways to Package Python Projects into exe

Common Programming Reference Atlas for Python

Common Programming Knowledge Reference Atlas for Python II

Four Progress Bars in Python

Timestamp Calculation in Python

Mathematics and Computation

Special Topic: The Three Musketeers of Python Mathematical Operations: pandas

Special Topic: The Three Musketeers of Python Mathematical Operations: Numpy

Special Topic: The Three Musketeers of Python Mathematical Operations: A Brief Discussion on scipy

The Wonderful Collision of Python and Mathematics, Making Computation Easy

Data Analysis and Visualization

Python Visualization with the Bokeh Library

Python Visualization with pyechart

Matplotlib: Turning Mathematics into Visualization

Python Visualization Charts with the Seaborn Library

The Cute Python Hand-Drawn Chart Library: CuteCharts

Web Scraping

Notes on the New Version of Selenium 4.0

Must-Know Python: The BeautifulSoup Library

Practical: Easily Implement HTTP Requests with the requests Library

Scrapy: To Be Supplemented

urllib: To Be Supplemented

Playwright Library: Let Python Help You with Browser Tasks

Image Processing

Must-Know Python: The OpenCV Library

Pillow: To Be Supplementedimageio: To Be SupplementedNatural Language Processing

Chinese Word Segmentation with the jieba Library

Natural Language Processing in Python with the spaCy Library

NLTK: To Be Introduced

Office Applications

Python Task Scheduling Tool: Schedule, Let It Help You Work on Time

Automating Word Document Processing with Python-docx

Five Ways to Write Data into CSV Files with Python

Various Ways to Read and Write Files in Python

Getting Started with Python Documentation Generation using the Sphinx Library

The Swiss Army Knife for PDF Operations in Python: The PyMuPDF Library

PyPDF2: To Be Supplemented

Automating Operations with the pyautogui Library

Software Interfaces and GamesPyQt Development Library: To Be IntroducedTkinter Interface Library: To Be IntroducedUsing Pygame to Teach You How to Create a Plane Battle GameEngineering Projects

Getting Started with Python’s Automated Testing Library: Pytest

Logging in Python Projects with the Loguru Library

Must-Know Python: The threading Library

Using Lightweight Databases SQLite in Python Projects

Must-Know Python: The Cryptography Library

Exploring the Faker Library: A Powerful Tool for Generating Test Data

Thread Pool Relatedconcurrent.futures: To Be Introduced

Fun Projects

Python Takes You to Explore the Stars and the Sea with the skyfield Library

The Super Fun Python Library: Turtle Graphics

Deep Use of Python in Music Creation [For Audio Processing Reference]

System Hardware, etc.

The Psutil Library: A Tool for System Monitoring and Process Management in Python

platformdirs: To Be Supplemented

pypiwin32: To Be Supplemented

pyserial: To Be Supplemented

pywifi: To Be Supplemented

Python Web Development Related

Flask: To Be IntroducedDjango: To Be IntroducedVideo Processingffmpeg-python: To Be UpdatedAccurately Dubbing Videos in Bulk with PythonPython Development: A Tool for Translating Chinese Videos into 30+ Languages

Others

Python Application Universe: All Uses Explained

Organizing Personal Library Files Installed in pip list

Popular Articles

Python Video Processing Tools: Assisting Learning and Recreation

A Comprehensive Overview of Domestic GPU Rental Platforms (The Most Comprehensive on the Internet)

Notes on the New Version of Selenium 4.0

Four Progress Bars in Python

The Super Fun Python Library: Turtle Graphics

Must-Know Python: The BeautifulSoup Library

Must-Know Python: The OpenCV Library

Must-Know Python: The threading Library

Must-Know Python: The OS Standard Library

Reading Large CSV Files and Searching Content with Python

Python Task Scheduling Tool: Schedule, Let It Help You Work on Time

Creating a Custom Pomodoro Timer with Python to Improve Work Efficiency

Using Domestic Sources for pip to Speed Up Python Library Installation

Five Ways to Write Data into CSV Files with Python

Various Ways to Read and Write Files in Python

Four Ways to Package Python Projects into exe

Automating Operations with the pyautogui Library

Historical Articles on Intelligent Agents

Detailed Analysis and Operation Modification of the Intelligent Agent OWL Architecture

Detailed Breakdown of the OpenManus Intelligent Agent

Historical Articles on AIRecords of Deploying Speech-to-Text Deep Learning Tools on Local CPUs

Guide to Feeding the Deepseek API for Multi-Turn Conversations with Python

Alternative Solutions for Busy Deepseek Servers (Ongoing Follow-Up)

The Most Comprehensive Alternative Solutions and Evaluations for Deepseek on the Internet

Building Your Own Deepseek R1 and Knowledge Base: A Step-by-Step Guide

Instructions for Feeding the Suno API with Python

A Comprehensive Overview of Domestic GPU Rental Platforms (The Most Comprehensive on the Internet)

Recreating Your Digital Avatar: Voice Avatar

Case Applications

A Tool for Accurate Insertion of Video Subtitles Created with Python

Python Video Processing Tools: Assisting Learning and Recreation

Implementing 10 Average Algorithms with Python

Using Pygame to Create Your Own Piano Keyboard (Part 1)

Python Implementation of the Knapsack Algorithm

Practical: Implementing a Device QR Code Generator with Python

Practical: I Used MoviePy to Create a Simple Version of Jianying

Reading Large CSV Files and Searching Content with Python

Automatically Sending Emails with Python for Remote Device Maintenance

Python Task Scheduling Tool: Schedule, Let It Help You Work on Time

Creating a Custom Pomodoro Timer with Python to Improve Work Efficiency

A Unique Practical Case of Python Application

Using Python to Help You Research and Make Money

Deep Use of Python in Music Creation

Efficiently Implementing Your Labeling Freedom with Python

Implementing 10 Average Algorithms with Python

Leave a Comment