Documentation Menu

ImageEnhance Module

The ImageEnhance module contains a number of classes that can be used for image enhancement. Each class takes a single argument, the image, and returns an enhancer object with an enhance(factor) method. A factor of 1.0 always returns a copy of the original image.

Import
from PIL import Image, ImageEnhance
ClassFactor = 0Factor = 1.0Factor = 2.0+
ImageEnhance.Contrast(image)Solid gray imageOriginalHigher contrast
ImageEnhance.Brightness(image)Black imageOriginalBrighter
ImageEnhance.Color(image)GrayscaleOriginalMore vibrant colour
ImageEnhance.Sharpness(image)BlurredOriginalSharpened
Enhancement Pipeline
img = Image.open("photo.jpg") img = ImageEnhance.Contrast(img).enhance(1.4) img = ImageEnhance.Sharpness(img).enhance(1.8) img = ImageEnhance.Color(img).enhance(1.2) img = ImageEnhance.Brightness(img).enhance(1.05) img.save("enhanced.jpg", quality=90)

ImageFont Module

The ImageFont module defines a class with the same name. Instances of this class store bitmap fonts, used with ImageDraw.text().

FunctionDescription
ImageFont.truetype(font, size, index=0, encoding="")Load a TrueType or OpenType font from a file path or URL. Returns an FreeTypeFont object.
ImageFont.load(filename)Load a BDF or PCF bitmap font. Limited to ASCII characters.
ImageFont.load_default(size=None)Load the built-in default bitmap font. If size is given, loads the default TrueType font at that size (Pillow 10.1+).
FreeTypeFont.getbbox(text)Returns (left, top, right, bottom) bounding box of the text.
FreeTypeFont.getlength(text)Returns the rendered length of the text in pixels.
FreeTypeFont.getmetrics()Returns (ascent, descent).
FreeTypeFont.font_variant(size, index, encoding, font_path)Create a new FreeTypeFont at a different size, useful for caching font objects.
ImageFont Usage
from PIL import ImageFont, ImageDraw, Image # Load TrueType font font = ImageFont.truetype("path/to/DejaVuSans.ttf", size=36) # Load bold variant bold_font = ImageFont.truetype("path/to/DejaVuSans-Bold.ttf", size=24) # Built-in default (no font file required) default = ImageFont.load_default(size=20) # Get text dimensions before drawing bbox = font.getbbox("Hello World") width = bbox[2] - bbox[0] height = bbox[3] - bbox[1]

ImageGrab Module

The ImageGrab module can be used to copy the contents of the screen or the clipboard to a PIL image memory. Only supported on Windows, macOS, and Linux (with Pillow[screenshot] extra).

FunctionDescription
ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=False, xdisplay=None)Take a screenshot. bbox is (left, upper, right, lower) to capture region. Default is full screen.
ImageGrab.grabclipboard()Grab the current contents of the clipboard as an image. Returns None if clipboard contains non-image data.
Screenshot Capture
from PIL import ImageGrab # Full screenshot im = ImageGrab.grab() im.save("screenshot.png") # Region screenshot region = ImageGrab.grab(bbox=(0, 0, 800, 600)) # Clipboard image clip_img = ImageGrab.grabclipboard() if clip_img: clip_img.save("from_clipboard.png")

ImageChops Module (Channel Operations)

The ImageChops module contains a number of arithmetical image operations, called channel operations ("chops"). Operations are applied to every pixel, for all channels.

FunctionFormulaDescription
add(image1, image2, scale=1.0, offset=0)(im1 + im2) / scale + offsetAdd two images. Clip to 0–255.
subtract(image1, image2, scale=1.0, offset=0)(im1 - im2) / scale + offsetSubtract two images.
multiply(image1, image2)im1 * im2 / MAXMultiply two images. Making darker.
screen(image1, image2)MAX - (MAX-im1)*(MAX-im2)/MAXScreen blend. Opposite of multiply — making lighter.
difference(image1, image2)|im1 - im2|Absolute difference. Useful for detecting changes between frames.
add_modulo(image1, image2)(im1 + im2) % MAXAdd modulo MAX (wraps around, no clipping).
subtract_modulo(image1, image2)(im1 - im2) % MAXSubtract modulo MAX.
invert(image)MAX - imInvert the image.
lighter(image1, image2)max(im1, im2)Return brighter pixels from both images.
darker(image1, image2)min(im1, im2)Return darker pixels from both images.
logical_and(image1, image2)ANDLogical AND on pixel data.
logical_or(image1, image2)ORLogical OR on pixel data.
logical_xor(image1, image2)XORLogical XOR on pixel data.
constant(image, value)Return a copy filled with the given pixel value.
duplicate(image)Return a copy of the image.
offset(image, xoffset, yoffset=None)Return a copy with pixels shifted by offset. Wraps around.
composite(image1, image2, mask)Composite two images using a mask.
hard_light(image1, image2)Hard light blend. Strong contrast effect.
soft_light(image1, image2)Soft light blend. Subtle lightening/darkening.
overlay(image1, image2)Overlay blend mode. Multiply for darks, screen for lights.

ImageStat Module

The ImageStat module calculates global statistics for an image, or for a region of an image. Each statistic is returned as a list of values, one per band.

AttributeTypeDescription
stat.extremalist of (min, max) tuplesMin and max value per band.
stat.countlist of intNumber of pixels per band.
stat.sumlist of floatSum of all pixel values per band.
stat.sum2list of floatSum of squares per band.
stat.meanlist of floatAverage pixel value per band.
stat.medianlist of floatMedian pixel value per band.
stat.rmslist of floatRoot mean square per band.
stat.varlist of floatVariance per band.
stat.stddevlist of floatStandard deviation per band.
ImageStat Example
from PIL import Image, ImageStat img = Image.open("photo.jpg") stat = ImageStat.Stat(img) print("Mean RGB:", stat.mean) # [R_mean, G_mean, B_mean] print("Std dev:", stat.stddev) # image contrast indicator print("RMS:", stat.rms) print("Extrema:", stat.extrema) # [(min,max), ...] # Stats over a specific region region_stat = ImageStat.Stat(img, mask=mask_image)

ImageMath Module

The ImageMath module can be used to evaluate "image expressions". The module provides two evaluation functions — choose based on whether you trust the input expressions.

FunctionDescription
ImageMath.lambda_eval(expression, environment={})Evaluate expression using a lambda. Safe for untrusted input. Expression is a callable taking band values.
ImageMath.unsafe_eval(expression, **environment)Evaluate expression string. Only use with trusted input. Supports operators: +, -, *, /, **, &, |, ^, ~, and functions like min(), max(), abs(), float(), int().
ImageMath Examples
from PIL import ImageMath, Image img = Image.open("photo.jpg").convert("L") # Safe lambda-based evaluation result = ImageMath.lambda_eval( lambda args: args["i"] * 0.5, {"i": img} ) # Gamma correction using unsafe_eval (trusted expression) corrected = ImageMath.unsafe_eval( "int(a ** 0.5 * 16)", a=img )

ImageSequence Module

The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence.

Sequence Iterator
from PIL import Image, ImageSequence gif = Image.open("animation.gif") for frame_number, frame in enumerate(ImageSequence.Iterator(gif)): frame.save(ff"frame_{frame_number:04d}.png") print(f"Total frames: {gif.n_frames}") print(f"Is animated: {gif.is_animated}")

ImageColor Module

The ImageColor module converts CSS3-style colour definitions to RGB tuples for use in Pillow drawing functions.

FunctionDescription
ImageColor.getrgb(color)Convert a colour string to an RGB or RGBA tuple. Supports named colours, hex (#rgb, #rrggbb, #aarrggbb), rgb(), rgba(), hsl(), hsla().
ImageColor.getcolor(color, mode)Same as getrgb() but converts to the given image mode. Useful for passing to Image.new().
ImageColor Examples
from PIL import ImageColor ImageColor.getrgb("red") # (255, 0, 0) ImageColor.getrgb("#ff6600") # (255, 102, 0) ImageColor.getrgb("hsl(120, 50%, 50%)") # (64, 191, 64) ImageColor.getrgb("rgba(0,0,255,128)") # (0, 0, 255, 128) # Convert for L-mode image ImageColor.getcolor("red", "L") # 76 (ITU-R luminance)

ExifTags Module

The ExifTags module exposes two dictionaries for decoding EXIF metadata: TAGS maps numeric tag IDs to human-readable names, and GPSTAGS maps GPS tag IDs to names.

EXIF Data Reading
from PIL import Image, ExifTags img = Image.open("camera_photo.jpg") exif = img.getexif() # Print all EXIF tags for tag_id, value in exif.items(): tag_name = ExifTags.TAGS.get(tag_id, ff"Unknown ({tag_id})") print(ff"{tag_name}: {value}") # Access specific tag (Make, Model, DateTime) make_tag = next(k for k, v in ExifTags.TAGS.items() if v == "Make") print("Camera make:", exif.get(make_tag)) # GPS Tags gps_info = exif.get_ifd(0x8825) # GPS IFD for tag_id, value in gps_info.items(): print(ExifTags.GPSTAGS.get(tag_id, tag_id), value)