π‘ Top 50 Pillow Operations for Image Processing
I. File & Basic Operationsβ’ Open an image file.
from PIL import Image
img = Image.open("image.jpg")
β’ Save an image.
img.save("new_image.png")β’ Display an image (opens in default viewer).
img.show()
β’ Create a new blank image.
new_img = Image.new("RGB", (200, 100), "blue")β’ Get image format (e.g., 'JPEG').
print(img.format)
β’ Get image dimensions as a (width, height) tuple.
width, height = img.size
β’ Get pixel format (e.g., 'RGB', 'L' for grayscale).
print(img.mode)
β’ Convert image mode.
grayscale_img = img.convert("L")β’ Get a pixel's color value at (x, y).
r, g, b = img.getpixel((10, 20))
β’ Set a pixel's color value at (x, y).
img.putpixel((10, 20), (255, 0, 0))
II. Cropping, Resizing & Pastingβ’ Crop a rectangular region.
box = (100, 100, 400, 400)
cropped_img = img.crop(box)
β’ Resize an image to an exact size.
resized_img = img.resize((200, 200))
β’ Create a thumbnail (maintains aspect ratio).
img.thumbnail((128, 128))
β’ Paste one image onto another.
img.paste(another_img, (50, 50))
III. Rotation & Transformationβ’ Rotate an image (counter-clockwise).
rotated_img = img.rotate(45, expand=True)
β’ Flip an image horizontally.
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)
β’ Flip an image vertically.
flipped_img = img.transpose(Image.FLIP_TOP_BOTTOM)
β’ Rotate by 90, 180, or 270 degrees.
img_90 = img.transpose(Image.ROTATE_90)
β’ Apply an affine transformation.
transformed = img.transform(img.size, Image.AFFINE, (1, 0.5, 0, 0, 1, 0))
IV. ImageOps Module Helpersβ’ Invert image colors.
from PIL import ImageOps
inverted_img = ImageOps.invert(img)
β’ Flip an image horizontally (mirror).
mirrored_img = ImageOps.mirror(img)
β’ Flip an image vertically.
flipped_v_img = ImageOps.flip(img)
β’ Convert to grayscale.
grayscale = ImageOps.grayscale(img)
β’ Colorize a grayscale image.
colorized = ImageOps.colorize(grayscale, black="blue", white="yellow")
β’ Reduce the number of bits for each color channel.
posterized = ImageOps.posterize(img, 4)
β’ Auto-adjust image contrast.
adjusted_img = ImageOps.autocontrast(img)
β’ Equalize the image histogram.
equalized_img = ImageOps.equalize(img)
β’ Add a border to an image.
bordered = ImageOps.expand(img, border=10, fill='black')
V. Color & Pixel Operationsβ’ Split image into individual bands (e.g., R, G, B).
r, g, b = img.split()
β’ Merge bands back into an image.
merged_img = Image.merge("RGB", (r, g, b))β’ Apply a function to each pixel.
brighter_img = img.point(lambda i: i * 1.2)
β’ Get a list of colors used in the image.
colors = img.getcolors(maxcolors=256)
β’ Blend two images with alpha compositing.
# Both images must be in RGBA mode
blended = Image.alpha_composite(img1_rgba, img2_rgba)
VI. Filters (ImageFilter)