Basic Image Operations in Pillow
Pillow makes it easy to perform fundamental image operations such as opening, displaying, saving images, and converting them between different modes (e.g., RGB, Grayscale). Let’s explore these operations step by step.
Opening and Displaying Images
Opening an Image
Use the Image.open()
method to open an image file.
from PIL import Image
# Open an image file
img = Image.open("example.jpg")
print("Image format:", img.format)
print("Image size:", img.size)
print("Image mode:", img.mode)
Displaying an Image
Use the show()
method to display an image in the default image viewer.
# Display the image
img.show()
Saving Images in Different Formats
You can save images in various formats such as JPEG, PNG, or BMP using the save()
method.
# Save the image as a PNG file
img.save("example_copy.png", format="PNG")
# Save the image as a JPEG file
img.save("example_copy.jpg", format="JPEG")
Supported Formats
Pillow supports a wide range of formats including:
- JPEG
- PNG
- BMP
- GIF
- TIFF
Check the Pillow documentation for the complete list.
Converting Between Modes
Pillow supports different image modes:
- RGB: Red, Green, Blue (standard color image).
- L: Grayscale.
- CMYK: Cyan, Magenta, Yellow, Black (used in printing).
Converting to Grayscale
Convert an image to grayscale using the convert()
method:
# Convert to grayscale
gray_img = img.convert("L")
gray_img.show()
Converting to RGB
Convert an image to RGB mode:
# Convert to RGB
rgb_img = gray_img.convert("RGB")
rgb_img.show()
Example: Batch Conversion
Convert multiple images to grayscale:
import os
from PIL import Image
# Path to the folder containing images
folder_path = "images/"
output_folder = "grayscale_images/"
# Ensure the output folder exists
os.makedirs(output_folder, exist_ok=True)
# Convert all images in the folder to grayscale
for filename in os.listdir(folder_path):
if filename.endswith(".jpg") or filename.endswith(".png"):
img = Image.open(os.path.join(folder_path, filename))
gray_img = img.convert("L")
gray_img.save(os.path.join(output_folder, filename))
Try It Yourself
Problem 1: Open and Display an Image
Write a Python script to open an image named sample.jpg
and display its size, mode, and format.
Show Solution
from PIL import Image
img = Image.open("sample.jpg")
print("Image Format:", img.format)
print("Image Size:", img.size)
print("Image Mode:", img.mode)
img.show()
Problem 2: Convert and Save Images
Write a script to open sample.jpg
, convert it to grayscale, and save it as sample_gray.png
.
Show Solution
from PIL import Image
img = Image.open("sample.jpg")
gray_img = img.convert("L")
gray_img.save("sample_gray.png")
gray_img.show()
With these basic operations, you can start manipulating images effectively using Pillow. Stay tuned for more advanced topics in the next sections!