Pillow: A Python Library for Image Processing!

In today’s digital age, image processing has become an indispensable part of our daily lives and work. Whether it’s photo editing on social media, image optimization in document processing, or research in the professional field of computer vision, image processing technology plays a crucial role. Python, as a powerful and easy-to-learn programming language, has many excellent image processing libraries, among which the Pillow library is a popular choice.

Pillow: A Python Library for Image Processing!

Pillow is a fork of the Python Imaging Library (PIL) that provides rich image processing capabilities for Python. Compared to PIL, Pillow is easier to install and use, and it supports more versions of Python. The Pillow library can handle various image formats, including JPEG, PNG, GIF, BMP, etc., and provides basic operations such as image resizing, cropping, rotating, applying filters, and color adjustments. It also supports more advanced features like image segmentation and feature extraction. In daily life, the Pillow library can help us quickly process photos, such as resizing images to fit different social media platforms, adding watermarks to protect copyrights, or performing color correction for better visual effects. In work scenarios, the Pillow library can be used for automating the processing of large numbers of images, improving work efficiency, such as batch renaming image files and generating thumbnails.

To use the Pillow library, you first need to install it. In most cases, we can use the pip package manager to install Pillow. Open the terminal or command prompt and run the following command:

pip install pillow
# If you are using an Anaconda environment, you can also use the conda command to install: pillow
conda install pillow

Once installed, we can import the Pillow library in our Python code and start using it.

Below are the basic usages of the Pillow library. Image processing using the Pillow library can typically be divided into the following steps:

1. Open an image file: Use the Image.open() function to open an image file, which takes the path of the image file as a parameter and returns an Image object.

from PIL import Image
# Open an image file
image = Image.open("example.jpg")

2. View image information: You can use the properties of the Image object to view basic information about the image, such as format, size, and mode.

# View image format
print("Image format:", image.format)
# View image size
print("Image size:", image.size)
# View image mode
print("Image mode:", image.mode)

3. Perform operations on the image: You can use various methods provided by the Image object to perform operations on the image, such as resizing, cropping, rotating, etc.

# Resize the image
resized_image = image.resize((500, 300))
# Crop the image
cropped_image = image.crop((100, 100, 400, 300))
# Rotate the image
rotated_image = image.rotate(45)

4. Save the processed image: Use the save() method of the Image object to save the processed image to a specified file.

# Save the resized image
resized_image.save("resized_example.jpg")
# Save the cropped image
cropped_image.save("cropped_example.jpg")
# Save the rotated image
rotated_image.save("rotated_example.jpg")

In addition to basic usage, the Pillow library also provides many advanced usages, such as applying filters, adjusting colors, and image composition. Below are some common advanced usages:

1. Apply filters: The Pillow library provides various filter effects that can be applied through the ImageFilter module.

from PIL import Image, ImageFilter
# Open an image
image = Image.open("example.jpg")
# Apply a blur filter
blurred_image = image.filter(ImageFilter.BLUR)
# Apply a sharpen filter
sharpened_image = image.filter(ImageFilter.SHARPEN)
# Save the processed images
blurred_image.save("blurred_example.jpg")
sharpened_image.save("sharpened_example.jpg")

2. Adjust colors: You can use the convert() method of the Image object to adjust the color mode of the image, such as converting a color image to grayscale.

# Convert to grayscale
gray_image = image.convert("L")
# Save the grayscale image
gray_image.save("gray_example.jpg")

3. Image composition: You can use the paste() method of the Image object to paste one image onto another, achieving the effect of image composition.

# Open two images
background = Image.open("background.jpg")
foreground = Image.open("foreground.png")
# Ensure the foreground image has an alpha channel
foreground = foreground.convert("RGBA")
# Paste the foreground image onto the background image
background.paste(foreground, (100, 100), foreground)
# Save the combined image
background.save("combined_image.jpg")

The Pillow library has many application scenarios in real life, below are a few common application scenarios:1. Social media image processing: When sharing photos on social media, we often need to adjust the size and quality of the photos to meet the requirements of different platforms. The Pillow library can help us automate these tasks, such as batch resizing photos and adding watermarks.2. Document processing: When processing documents, we may need to insert images, adjust image sizes or formats. The Pillow library can be used in conjunction with Python’s document processing libraries (such as python-docx) to automate the processing of images in documents.3. Data visualization: In the process of data visualization, we may need to further process the generated charts, such as adding titles and adjusting colors. The Pillow library can be used in conjunction with data visualization libraries like Matplotlib for advanced chart processing.4. Computer vision research: In the field of computer vision, the Pillow library can serve as a preprocessing tool for reading, processing, and converting images. For example, before training deep learning models, we often need to preprocess image data, and the Pillow library can help us accomplish these tasks.In summary, Pillow is a powerful and easy-to-use Python image processing library that provides us with rich image processing capabilities, helping us efficiently handle various image tasks in our daily lives and work. Whether it’s simple image adjustments or complex image compositions, the Pillow library can meet our needs. Through this article, I believe you have gained a deeper understanding of the Pillow library and mastered its basic and advanced usages.So, have you encountered any scenarios in your daily life or work that require image processing? Have you tried using the Pillow library to solve these problems? Feel free to share your experiences and thoughts! If you encounter any issues while using the Pillow library, you can also ask questions, and we can discuss solutions together.Below is a sample code that implements the image watermarking function using the Pillow library:

from PIL import Image, ImageDraw, ImageFont
def add_watermark(input_image_path, output_image_path, watermark_text, position=None, opacity=100):    """    Add a text watermark to the image
    Parameters:    input_image_path: Path to the input image    output_image_path: Path to the output image    watermark_text: Watermark text    position: Watermark position, default is None, indicating a random position    opacity: Watermark opacity, range from 0-100, default is 100 (completely opaque)    """    try:        # Open the original image        with Image.open(input_image_path) as img:            # Create a copy of the original image for drawing the watermark            watermarked = img.copy()
            # Ensure the image is in RGBA mode to support transparency            if watermarked.mode != 'RGBA':                watermarked = watermarked.convert('RGBA')            # Create a transparent image layer for drawing the watermark            watermark_layer = Image.new('RGBA', watermarked.size, (0, 0, 0, 0))            # Get the drawing context            draw = ImageDraw.Draw(watermark_layer)            # Set font and font size            # Note: Ensure the specified font file exists in the system, otherwise an exception will be thrown            try:                font = ImageFont.truetype("arial.ttf", 36)            except IOError:                # If the specified font is not found, use the default font                font = ImageFont.load_default()            # Calculate the size of the watermark text            text_width, text_height = draw.textsize(watermark_text, font=font)            # If no position is specified, use a random position            if position is None:                # Calculate the area where the watermark can be placed                max_x = watermarked.width - text_width - 10                max_y = watermarked.height - text_height - 10                # Ensure there is enough space to place the watermark                if max_x > 10 and max_y > 10:                    x = 10  # random.randint(10, max_x)                    y = 10  # random.randint(10, max_y)                else:                    x, y = 10, 10            else:                x, y = position            # Calculate opacity            alpha = int(255 * (opacity / 100))            # Draw the watermark text            draw.text((x, y), watermark_text, font=font, fill=(255, 255, 255, alpha))            # Merge the watermark layer with the original image            watermarked = Image.alpha_composite(watermarked, watermark_layer)            # Save the processed image            if output_image_path.lower().endswith('.jpg') or output_image_path.lower().endswith('.jpeg'):                # JPG format does not support transparency, need to convert to RGB mode                watermarked = watermarked.convert('RGB')            watermarked.save(output_image_path)            print(f"Watermark added to the image and saved to {output_image_path}")    except Exception as e:        print(f"Error adding watermark: {e}")
# Usage example
if __name__ == "__main__":    # Input image path    input_image = "example.jpg"    # Output image path    output_image = "watermarked_example.jpg"    # Watermark text    watermark_text = "© All Rights Reserved"
    # Add watermark, using default position and opacity    add_watermark(input_image, output_image, watermark_text)    # You can also specify position and opacity    # add_watermark(input_image, output_image, watermark_text, position=(100, 100), opacity=50

This sample code implements a simple image watermarking function that can add text watermarks to specified images. You can adjust the position, opacity, and text content of the watermark as needed. This function is very useful for protecting image copyrights and marking image sources.

Leave a Comment