OpenSlide Python

1.4.3 · active · verified Thu Apr 16

OpenSlide Python provides a Python interface to the OpenSlide C library, which is designed for reading high-resolution whole-slide images (WSI) commonly used in digital pathology. These images, often gigapixels in size, are too large for standard image processing libraries, so OpenSlide offers efficient multi-resolution access. The current version is 1.4.3, and the project maintains a regular release cadence with frequent updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to open a whole-slide image, access its basic properties (dimensions, level count, vendor, objective power), and generate a thumbnail image using the `OpenSlide` object. It includes error handling for common issues like file not found or unsupported formats.

import openslide
from PIL import Image
import os

# NOTE: Replace 'path/to/your/slide.svs' with an actual whole-slide image file.
# You might need to adjust the path if running on Windows and openslide-bin isn't used,
# by adding the OpenSlide DLL directory to os.add_dll_directory().
# Example for Windows (uncomment and modify if needed):
# os.add_dll_directory(r'C:\path\to\OpenSlide\bin')

slide_path = os.environ.get('OPENSLIDE_TEST_SLIDE', 'path/to/your/slide.svs')

try:
    with openslide.OpenSlide(slide_path) as slide:
        print(f"Slide dimensions (level 0): {slide.dimensions}")
        print(f"Number of levels: {slide.level_count}")
        print(f"Vendor: {slide.properties.get(openslide.PROPERTY_NAME_VENDOR, 'Unknown')}")
        print(f"Objective Power: {slide.properties.get(openslide.PROPERTY_NAME_OBJECTIVE_POWER, 'Unknown')}")

        # Get a thumbnail (e.g., max 200x200 pixels)
        thumbnail: Image.Image = slide.get_thumbnail((200, 200))
        # thumbnail.save('thumbnail.png')
        print(f"Generated thumbnail with size: {thumbnail.size}")

        # Read a region at a specific level (e.g., 512x512 pixels at level 2)
        # region: Image.Image = slide.read_region((0, 0), 2, (512, 512))
        # region.save('region_level2.png')

except openslide.OpenSlideError as e:
    print(f"Error opening slide: {e}")
except FileNotFoundError:
    print(f"Error: Slide file not found at '{slide_path}'")

view raw JSON →