pyvips: Python binding for libvips
pyvips is a Python binding for the high-performance libvips image processing library. It is designed for speed and low memory usage, particularly when handling large images, by employing a streaming, parallel processing pipeline that avoids loading entire images into memory. The library is actively maintained and supports Python versions 3.7 and newer.
Warnings
- breaking The `libvips` shared library is a mandatory external dependency. If not installed on your system, `pyvips` will fail to import with an `OSError` or `ModuleNotFoundError` for `_libvips`.
- gotcha Using `pip install "pyvips[binary]"` installs a self-contained `libvips` binary that may lack support for certain features like PDF loading, OpenSlide (for whole-slide images), or specific image formats. If you need these, a system-wide installation of `libvips` with full feature support is necessary.
- breaking Since `libvips` version 8.9, modifying metadata on 'shared' images (those with a reference count greater than one) is blocked to prevent race conditions. Attempts to do so will be ignored or raise a warning.
- gotcha Operations that draw directly onto an image, such as `Image.draw_circle()` or `Image.draw_line()`, inherently modify their input. `pyvips` will make a private copy of the image in memory before performing these operations to prevent crashes. Repeated drawing can thus be inefficient due to multiple memory copies.
- gotcha If `cffi` is unable to build a binary extension for `pyvips` (API mode), it will fall back to ABI mode, which results in approximately 20% slower execution and longer startup times.
- gotcha When processing extremely large images, errors like 'arithmetic overflow' can occur, often stemming from underlying `libvips` components (e.g., `libpng`) if a 32-bit `libvips` build is in use. This limits the maximum image size that can be handled.
Install
-
pip install pyvips -
pip install "pyvips[binary]"
Imports
- Image
import pyvips image = pyvips.Image.new_from_file(...)
Quickstart
import pyvips
import os
# Assuming 'input.jpg' exists in the current directory
# For demonstration, let's create a dummy image if not present
if not os.path.exists('input.jpg'):
# In a real scenario, you'd have an actual image file.
# For this quickstart, we'll create a simple black image.
dummy_image = pyvips.Image.black(100, 100, bands=3)
dummy_image.write_to_file('input.jpg')
# Load an image
image = pyvips.Image.new_from_file('input.jpg')
# Perform an operation, e.g., resize to 50% and convert to grayscale
processed_image = image.resize(0.5).colourspace('b-w')
# Save the processed image
processed_image.write_to_file('output_grayscale.png')
print(f"Processed image saved to output_grayscale.png (width: {processed_image.width}, height: {processed_image.height})")