Pillow is a powerful Python library that provides comprehensive image processing capabilities. This library enables developers to perform various image operations such as opening, modifying, and saving different image formats. With Pillow, you can implement transformations like resizing, rotating, cropping, and color adjustments efficiently.
Installation
To begin using Pillow, you need to install it via pip. Execute the following comand in your terminal:
pip install Pillow
After installation completes, you can start implementing image processing operations in your Python projects.
Loading and Displaying Images
The fundamental operation in image processing is loading an image file. Pillow provides the Image module with methods to open and display images:
from PIL import Image
# Load an image file
picture = Image.open('sample.jpg')
# Display the image
picture.show()
This code snippet loads an image named 'sample.jpg' and opens it in the default image viewer application.
Resizing Images
Resizing is a common operation when preparing images for different display contexts. Use the resize method to adjust dimensions:
# Modify image dimensions
scaled_picture = picture.resize((300, 300))
# Display the resized image
scaled_picture.show()
The above example resizes the image to 300x300 pixels while maintaining the aspect ratio if not specified otherwise.
Rotating Images
Pillow simplifies image rotation with the rotate method, which accepts an angle parameter:
# Rotate the image by 90 degrees
rotated_picture = picture.rotate(90)
# Display the rotated result
rotated_picture.show()
This code rotates the image by 90 degrees clockwise. Negative values can be used for counter-clockwise rotation.
Cropping Images
To extract a specific region from an image, use the crop method with a tuple defining the bounding box:
# Extract a region from the image
cropped_picture = picture.crop((50, 50, 350, 350))
# Display the cropped portion
cropped_picture.show()
The parameters represent the left, upper, right, and lower pixel coordinates of the region to extract.
Color Space Conversion
Pillow supports various color mode conversions. Converting to grayscale is a common operation:
# Convert to grayscale
monochrome_picture = picture.convert('L')
# Display the grayscale image
monochrome_picture.show()
The 'L' parameter specifies grayscale mode. Other conversion options include 'RGB', 'RGBA', and 'CMYK' among others.
Saving Modified Images
After processing, you can save the modified image to a file using the save method:
# Save the processed image
scaled_picture.save('modified_sample.jpg')
This saves the resized image to a new file. The format is determined by the file extension.