Language: Python
Data Science
Pillow was created in 2010 as a friendly fork of PIL to continue development and maintain compatibility with newer versions of Python. It has become the de facto library for image processing in Python, widely used for applications such as image manipulation, format conversion, and automated image processing pipelines.
Pillow is a modern fork of the Python Imaging Library (PIL) that adds support for opening, manipulating, and saving many different image file formats in Python.
pip install pillowconda install -c conda-forge pillowPillow provides an Image class to handle images, along with functions to resize, crop, rotate, convert formats, apply filters, draw text, and handle transparency. It integrates seamlessly with NumPy arrays for advanced image processing.
from PIL import Image
img = Image.open('image.jpg')
img.show()Opens an image file and displays it using the default image viewer.
from PIL import Image
img = Image.open('image.jpg')
resized = img.resize((256, 256))
resized.show()Resizes the image to 256x256 pixels while maintaining the aspect ratio.
from PIL import Image
img = Image.open('image.png')
img.save('image.jpg')Converts a PNG image to JPEG format.
from PIL import Image
img = Image.open('image.jpg')
cropped = img.crop((50, 50, 200, 200))
cropped.show()Crops a rectangular region from the image defined by the bounding box coordinates (left, upper, right, lower).
from PIL import Image
img = Image.open('image.jpg')
rotated = img.rotate(45)
rotated.show()Rotates the image 45 degrees counterclockwise.
from PIL import Image, ImageFilter
img = Image.open('image.jpg')
blurred = img.filter(ImageFilter.GaussianBlur(5))
blurred.show()Applies a Gaussian blur filter to the image.
from PIL import Image, ImageDraw, ImageFont
img = Image.open('image.jpg')
draw = ImageDraw.Draw(img)
font = ImageFont.load_default()
draw.text((10,10), 'Hello, Pillow!', fill='white', font=font)
img.show()Draws white text on the image at position (10,10) using the default font.
Use `with Image.open(...) as img:` to ensure proper resource handling.
Convert images to RGB mode before saving in formats that don’t support alpha channels.
Use thumbnail() for memory-efficient resizing.
Combine Pillow with NumPy for advanced image processing.
Handle exceptions for file operations to prevent crashes.