Python interface to OpenSlide for reading whole-slide images used in digital pathology
—
Direct bindings to the OpenSlide C library providing maximum performance and fine-grained control. This module provides nearly direct equivalents to the OpenSlide C API for advanced users who need precise control over slide operations and resource management.
import openslide.lowlevel as lowlevel
from openslide.lowlevel import OpenSlideError, OpenSlideVersionError, OpenSlideUnsupportedFormatError
from PIL import Image
import osBasic slide operations including opening, closing, and library information retrieval.
import openslide.lowlevel as lowlevel
def open(filename: str | bytes | os.PathLike[Any]) -> lowlevel._OpenSlide:
"""
Open a whole-slide image file.
Args:
filename: Path to the slide file
Returns:
_OpenSlide handle for the opened slide
Raises:
OpenSlideUnsupportedFormatError: If file format is not supported
OpenSlideError: If there's an error opening the file
"""
def close(slide: lowlevel._OpenSlide) -> None:
"""
Close a slide and free associated resources.
Args:
slide: _OpenSlide handle to close
Note: After calling close(), the slide handle becomes invalid
"""
def detect_vendor(filename: str | bytes | os.PathLike[Any]) -> str:
"""
Detect the format vendor of a slide file.
Args:
filename: Path to the slide file
Returns:
String describing the format vendor
Raises:
OpenSlideError: If there's an error accessing the file
"""
def get_version() -> str:
"""
Get the OpenSlide library version string.
Returns:
Version string of the OpenSlide C library
"""
def get_error(slide: lowlevel._OpenSlide) -> str:
"""
Get the current error state of a slide.
Args:
slide: _OpenSlide handle
Returns:
Error message string, or None if no error
"""Functions for querying slide structure and resolution levels.
def get_level_count(slide: lowlevel._OpenSlide) -> int:
"""
Get the number of resolution levels in the slide.
Args:
slide: _OpenSlide handle
Returns:
Number of levels in the slide
"""
def get_level_dimensions(slide: lowlevel._OpenSlide, level: int) -> tuple[int, int]:
"""
Get the dimensions of a specific level.
Args:
slide: _OpenSlide handle
level: Level number (0-based)
Returns:
(width, height) tuple for the specified level
"""
def get_level_downsample(slide: lowlevel._OpenSlide, level: int) -> float:
"""
Get the downsample factor for a specific level.
Args:
slide: _OpenSlide handle
level: Level number (0-based)
Returns:
Downsample factor relative to level 0
"""
def get_best_level_for_downsample(slide: lowlevel._OpenSlide, downsample: float) -> int:
"""
Find the best level for a given downsample factor.
Args:
slide: _OpenSlide handle
downsample: Desired downsample factor
Returns:
Level number that best matches the downsample factor
"""Low-level functions for reading image data from slides.
def read_region(slide: lowlevel._OpenSlide, x: int, y: int, level: int, w: int, h: int) -> Image.Image:
"""
Read a rectangular region from the slide.
Args:
slide: _OpenSlide handle
x: X coordinate in level 0 reference frame
y: Y coordinate in level 0 reference frame
level: Level number to read from
w: Width of region to read
h: Height of region to read
Returns:
PIL.Image in RGBA format with the region data (not premultiplied)
Raises:
OpenSlideError: If w or h is negative, or other read error occurs
"""Functions for accessing slide metadata and properties.
def get_property_names(slide: lowlevel._OpenSlide) -> list[str]:
"""
Get list of all property names available for the slide.
Args:
slide: _OpenSlide handle
Returns:
List of property name strings
"""
def get_property_value(slide: lowlevel._OpenSlide, name: str | bytes) -> str | None:
"""
Get the value of a specific property.
Args:
slide: _OpenSlide handle
name: Property name
Returns:
Property value as string, or None if property doesn't exist
"""Functions for working with associated images like labels and thumbnails.
def get_associated_image_names(slide: lowlevel._OpenSlide) -> list[str]:
"""
Get list of all associated image names.
Args:
slide: _OpenSlide handle
Returns:
List of associated image name strings
"""
def get_associated_image_dimensions(slide: lowlevel._OpenSlide, name: str | bytes) -> tuple[int, int]:
"""
Get dimensions of an associated image.
Args:
slide: _OpenSlide handle
name: Associated image name
Returns:
(width, height) tuple for the associated image
"""
def read_associated_image(slide: lowlevel._OpenSlide, name: str | bytes) -> Image.Image:
"""
Read an associated image.
Args:
slide: _OpenSlide handle
name: Associated image name
Returns:
PIL.Image with the associated image data (not premultiplied)
Raises:
KeyError: If the associated image name doesn't exist
"""Functions for accessing ICC color profiles (requires OpenSlide 4.0.0+).
def get_icc_profile_size(slide: lowlevel._OpenSlide) -> int:
"""
Get the size of the ICC color profile for the slide.
Args:
slide: _OpenSlide handle
Returns:
Size of ICC profile in bytes, or 0 if no profile available
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""
def read_icc_profile(slide: lowlevel._OpenSlide) -> bytes | None:
"""
Read the ICC color profile for the slide.
Args:
slide: _OpenSlide handle
Returns:
ICC profile as bytes, or None if no profile available
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""
def get_associated_image_icc_profile_size(slide: lowlevel._OpenSlide, name: str | bytes) -> int:
"""
Get the size of the ICC color profile for an associated image.
Args:
slide: _OpenSlide handle
name: Associated image name
Returns:
Size of ICC profile in bytes, or 0 if no profile available
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""
def read_associated_image_icc_profile(slide: lowlevel._OpenSlide, name: str | bytes) -> bytes | None:
"""
Read the ICC color profile for an associated image.
Args:
slide: _OpenSlide handle
name: Associated image name
Returns:
ICC profile as bytes, or None if no profile available
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""Functions for managing tile caches (requires OpenSlide 4.0.0+).
def cache_create(capacity: int) -> lowlevel._OpenSlideCache:
"""
Create a new tile cache.
Args:
capacity: Cache capacity in bytes
Returns:
_OpenSlideCache handle
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""
def set_cache(slide: lowlevel._OpenSlide, cache: lowlevel._OpenSlideCache) -> None:
"""
Set the tile cache for a slide.
Args:
slide: _OpenSlide handle
cache: _OpenSlideCache handle
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""
def cache_release(cache: lowlevel._OpenSlideCache) -> None:
"""
Release a tile cache and free associated resources.
Args:
cache: _OpenSlideCache handle to release
Raises:
OpenSlideVersionError: If OpenSlide version < 4.0.0
"""class _OpenSlide:
"""
Wrapper class for OpenSlide C library handles.
Not intended for direct instantiation - use lowlevel.open() instead.
"""
class _OpenSlideCache:
"""
Wrapper class for OpenSlide cache handles.
Not intended for direct instantiation - use lowlevel.cache_create() instead.
"""
# Type alias for filename parameters
Filename = str | bytes | os.PathLike[Any]class OpenSlideError(Exception):
"""
Base exception class for OpenSlide errors.
Raised when the OpenSlide C library encounters an error.
"""
class OpenSlideVersionError(OpenSlideError):
"""
Exception raised when requested functionality requires a newer OpenSlide version.
Attributes:
minimum_version: String indicating the minimum required version
"""
def __init__(self, minimum_version: str): ...
class OpenSlideUnsupportedFormatError(OpenSlideError):
"""
Exception raised when OpenSlide doesn't support the requested file format.
"""import openslide.lowlevel as lowlevel
from PIL import Image
# Open slide at low level
slide = lowlevel.open("slide.svs")
try:
# Get basic information
level_count = lowlevel.get_level_count(slide)
dimensions = lowlevel.get_level_dimensions(slide, 0)
print(f"Levels: {level_count}, Level 0 dimensions: {dimensions}")
# Read a region
region = lowlevel.read_region(slide, 1000, 1000, 0, 512, 512)
region.save("region.png")
# Check for errors
error = lowlevel.get_error(slide)
if error:
print(f"Error: {error}")
finally:
# Always close the slide
lowlevel.close(slide)import openslide.lowlevel as lowlevel
slide = lowlevel.open("slide.svs")
try:
# Get all property names
prop_names = lowlevel.get_property_names(slide)
print(f"Found {len(prop_names)} properties:")
# Read specific properties
for name in prop_names:
value = lowlevel.get_property_value(slide, name)
print(f" {name}: {value}")
# Check for specific properties
vendor = lowlevel.get_property_value(slide, "openslide.vendor")
if vendor:
print(f"Slide vendor: {vendor}")
finally:
lowlevel.close(slide)import openslide.lowlevel as lowlevel
# Check if caching is available
if lowlevel.cache_create.available:
# Create a 128MB cache
cache = lowlevel.cache_create(128 * 1024 * 1024)
slide1 = lowlevel.open("slide1.svs")
slide2 = lowlevel.open("slide2.svs")
try:
# Share cache between slides
lowlevel.set_cache(slide1, cache)
lowlevel.set_cache(slide2, cache)
# Read regions (will use shared cache)
region1 = lowlevel.read_region(slide1, 0, 0, 0, 1024, 1024)
region2 = lowlevel.read_region(slide2, 0, 0, 0, 1024, 1024)
finally:
lowlevel.close(slide1)
lowlevel.close(slide2)
lowlevel.cache_release(cache)
else:
print("Caching not available - upgrade to OpenSlide 4.0.0+")import openslide.lowlevel as lowlevel
from PIL import ImageCms
from io import BytesIO
slide = lowlevel.open("slide.svs")
try:
if lowlevel.read_icc_profile.available:
# Read main image ICC profile
profile_data = lowlevel.read_icc_profile(slide)
if profile_data:
profile = ImageCms.getOpenProfile(BytesIO(profile_data))
print(f"Color space: {profile.color_space}")
# Read associated image profiles
assoc_names = lowlevel.get_associated_image_names(slide)
for name in assoc_names:
assoc_profile = lowlevel.read_associated_image_icc_profile(slide, name)
if assoc_profile:
print(f"Associated image '{name}' has ICC profile")
else:
print("ICC profile support not available - upgrade to OpenSlide 4.0.0+")
finally:
lowlevel.close(slide)Install with Tessl CLI
npx tessl i tessl/pypi-openslide-python