### Install OpenSlide Python and OpenSlide Source: https://github.com/openslide/openslide-python/blob/main/README.md Install both the OpenSlide Python package and the OpenSlide binary from PyPI. Ensure OpenSlide is discoverable by the Python package. ```console pip install openslide-python openslide-bin ``` -------------------------------- ### Flask Deep Zoom Server Example Source: https://context7.com/openslide/openslide-python/llms.txt Demonstrates how to embed the DeepZoomGenerator into a Flask application to serve Deep Zoom tiles over HTTP. ```APIDOC ## Flask Deep Zoom Server ### Description An example Flask application that serves a single whole-slide image as a Deep Zoom stream with an OpenSeadragon viewer, property inspector, and associated image panel. ### Usage ```python # Run from the command line: # python examples/deepzoom/deepzoom_server.py /path/to/slide.svs # Or embed in your own Flask app: from pathlib import Path from examples.deepzoom.deepzoom_server import create_app app = create_app({ 'DEEPZOOM_SLIDE': '/data/slides/tumor.svs', 'DEEPZOOM_FORMAT': 'jpeg', # 'jpeg' or 'png' 'DEEPZOOM_TILE_SIZE': 254, 'DEEPZOOM_OVERLAP': 1, 'DEEPZOOM_LIMIT_BOUNDS': True, # clip to non-empty tissue area 'DEEPZOOM_TILE_QUALITY': 75, # JPEG quality 'DEEPZOOM_COLOR_MODE': 'default', # ICC conversion: 'default', 'embed', 'ignore', # 'perceptual', 'relative-colorimetric', etc. }) # Endpoints served: # GET / → HTML viewer page # GET /slide.dzi → DZI XML descriptor # GET /slide_files/{level}/{col}_{row}.jpeg → individual tiles if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, threaded=True) ``` ``` -------------------------------- ### Install OpenSlide Python on Windows Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md On Windows, download OpenSlide binaries and extract them. Then, import openslide within an os.add_dll_directory() statement to specify the path to the binaries. ```python # The path can also be read from a config file, etc. OPENSLIDE_PATH = r'c:\path\to\openslide-win64\bin' import os if hasattr(os, 'add_dll_directory'): # Windows with os.add_dll_directory(OPENSLIDE_PATH): import openslide else: import openslide ``` -------------------------------- ### Embed Deep Zoom Server in a Flask Application Source: https://context7.com/openslide/openslide-python/llms.txt Provides an example of how to integrate the openslide Deep Zoom server into a custom Flask application. This allows serving slides over HTTP with an OpenSeadragon viewer. Configuration options are provided. ```python # Run from the command line: # python examples/deepzoom/deepzoom_server.py /path/to/slide.svs # Or embed in your own Flask app: from pathlib import Path from examples.deepzoom.deepzoom_server import create_app app = create_app({ 'DEEPZOOM_SLIDE': '/data/slides/tumor.svs', 'DEEPZOOM_FORMAT': 'jpeg', # 'jpeg' or 'png' 'DEEPZOOM_TILE_SIZE': 254, 'DEEPZOOM_OVERLAP': 1, 'DEEPZOOM_LIMIT_BOUNDS': True, # clip to non-empty tissue area 'DEEPZOOM_TILE_QUALITY': 75, # JPEG quality 'DEEPZOOM_COLOR_MODE': 'default', # ICC conversion: 'default', 'embed', 'ignore', # 'perceptual', 'relative-colorimetric', etc. }) # Endpoints served: # GET / → HTML viewer page # GET /slide.dzi → DZI XML descriptor # GET /slide_files/{level}/{col}_{row}.jpeg → individual tiles if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, threaded=True) ``` -------------------------------- ### Get Tile Coordinates for Raw Slide Access Source: https://context7.com/openslide/openslide-python/llms.txt Demonstrates how to retrieve the exact slide coordinates, level, and size for a specific Deep Zoom tile. This is useful for custom processing or caching at the raw slide level. Ensure 'scan.svs' exists. ```python from openslide import OpenSlide from openslide.deepzoom import DeepZoomGenerator with OpenSlide('scan.svs') as slide: dz = DeepZoomGenerator(slide, tile_size=254, overlap=1, limit_bounds=True) dz_level = dz.level_count - 3 # a mid-resolution DZI level address = (2, 3) # column 2, row 3 coords = dz.get_tile_coordinates(dz_level, address) location, slide_level, size = coords print(f'location={location}, slide_level={slide_level}, size={size}') # location=(1024, 1536), slide_level=1, size=(254, 254) # Directly call read_region with the same args raw = slide.read_region(location, slide_level, size) print(raw.size) # (254, 254) # Also get the expected output tile dimensions tile_dims = dz.get_tile_dimensions(dz_level, address) print(tile_dims) # (255, 255) - includes overlap pixels ``` -------------------------------- ### OpenSlide.dimensions Property Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Gets the dimensions (width and height) of the whole-slide image at level 0 (the highest resolution). ```APIDOC #### dimensions A `(width, height)` tuple for level 0 of the slide. * **Type:** tuple[int, int] ``` -------------------------------- ### OpenSlide.level_count Property Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Retrieves the total number of resolution levels available in the whole-slide image. Levels are indexed starting from 0 for the highest resolution. ```APIDOC #### level_count The number of levels in the slide. Levels are numbered from `0` (highest resolution) to `level_count - 1` (lowest resolution). * **Type:** int ``` -------------------------------- ### Initialize OpenSeadragon Viewer and Scalebar Source: https://github.com/openslide/openslide-python/blob/main/examples/deepzoom/templates/slide-multipane.html Initializes the OpenSeadragon viewer with specified settings and adds a scale bar. Use this for setting up the main image viewing area. ```javascript var dzi_data = {{ dzi_data|default('{}')|safe }}; var viewer = new OpenSeadragon({ id: "view", prefixUrl: "static/images/", timeout: 120000, animationTime: 0.5, blendTime: 0.1, constrainDuringPan: true, maxZoomPixelRatio: 2, minZoomImageRatio: 1, visibilityRatio: 1, zoomPerScroll: 2, }); viewer.scalebar({ xOffset: 10, yOffset: 10, barThickness: 3, color: '#555555', fontColor: '#333333', backgroundColor: 'rgba(255, 255, 255, 0.5)', }); ``` -------------------------------- ### OpenSeadragon Viewer Initialization Source: https://github.com/openslide/openslide-python/blob/main/examples/deepzoom/templates/slide-fullpage.html Initializes an OpenSeadragon viewer with specified tile sources and configuration options. Includes settings for navigation, zoom, and performance. ```javascript $(function() { var viewer = new OpenSeadragon({ id: "view", tileSources: "{{ slide_url }}", prefixUrl: "{{ url_for('static', filename='images/') }}", showNavigator: true, showRotationControl: true, animationTime: 0.5, blendTime: 0.1, constrainDuringPan: true, maxZoomPixelRatio: 2, minZoomImageRatio: 1, visibilityRatio: 1, zoomPerScroll: 2, timeout: 120000, }); var mpp = parseFloat("{{ slide_mpp }}"); viewer.scalebar({ pixelsPerMeter: mpp ? (1e6 / mpp) : 0, xOffset: 10, yOffset: 10, barThickness: 3, color: '#555555', fontColor: '#333333', backgroundColor: 'rgba(255, 255, 255, 0.5)', }); }); ``` -------------------------------- ### Open Slide or Image File with open_slide Source: https://context7.com/openslide/openslide-python/llms.txt Use the `open_slide` factory function as the recommended entry point for opening whole-slide images or standard image files. It returns an `OpenSlide` object for WSI or an `ImageSlide` wrapper for regular images. Handle potential `OSError` exceptions during file opening. ```python from openslide import open_slide, OpenSlideUnsupportedFormatError try: slide = open_slide('tumor_section.svs') print(type(slide)) # print(slide.dimensions) # (46000, 32914) - (width, height) at level 0 slide.close() except OSError as e: print(f'Could not open file: {e}') # Works equally well with a regular PNG img_slide = open_slide('overview.png') print(type(img_slide)) # img_slide.close() ``` -------------------------------- ### Create OpenSlideCache Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Demonstrates the instantiation of an OpenSlideCache with a specified capacity in bytes. Requires OpenSlide version 4.0.0 or later. ```python openslide.OpenSlideCache(capacity: int) ``` -------------------------------- ### HTML and CSS for Full-Page Viewer Source: https://github.com/openslide/openslide-python/blob/main/examples/deepzoom/templates/slide-fullpage.html Basic HTML and CSS to set up a full-page container for the image viewer. Ensures the viewer occupies the entire browser window. ```html {{ slide_filename }}
``` ```css html { overflow: hidden; } body { margin: 0; padding: 0; } div#view { position: absolute; left: 0; width: 100%; height: 100%; background-color: black; color: white; } ``` -------------------------------- ### Build and Apply Color Transform Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Illustrates creating a reusable ImageCmsTransform for efficient color conversion of multiple slide regions. ```python toProfile = ImageCms.createProfile('sRGB') intent = ImageCms.getDefaultIntent(slide.color_profile) transform = ImageCms.buildTransform( slide.color_profile, toProfile, 'RGBA', 'RGBA', intent, 0 ) # for each region image: ImageCms.applyTransform(image, transform, True) ``` -------------------------------- ### Load and Read Image Data with openslide-python Source: https://context7.com/openslide/openslide-python/llms.txt Demonstrates loading an image from a file path or a PIL Image object and reading specific regions. Ensure the image file exists. ```python from openslide import ImageSlide from PIL import Image # From a file path with ImageSlide('overview.png') as slide: print(slide.level_count) # 1 print(slide.dimensions) # (2048, 1536) print(slide.level_downsamples) # (1.0,) region = slide.read_region((100, 100), 0, (256, 256)) print(region.size) # (256, 256) # Wrap an in-memory PIL Image img = Image.open('photo.jpg') with ImageSlide(img) as slide: thumb = slide.get_thumbnail((200, 200)) print(thumb.size) # e.g. (200, 150) ``` -------------------------------- ### Initial Slide Load and Event Listener Source: https://github.com/openslide/openslide-python/blob/main/examples/deepzoom/templates/slide-multipane.html Loads the initial slide specified by slide_url and slide_mpp. It also sets up an event listener for clicks on elements with the class 'load-slide' to open new slides. ```javascript open_slide("{{ slide_url }}", parseFloat('{{ slide_mpp }}')); $(".load-slide").on("click", function(ev) { $(".current-slide").removeClass("current-slide"); $(this).parent().addClass("current-slide"); open_slide($(this).attr('data-url'), parseFloat($(this).attr('data-mpp'))); ev.preventDefault(); }); ``` -------------------------------- ### Save Image with ICC Profile Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Demonstrates how to save an image to disk while including its embedded ICC color profile. ```python image.save(filename, icc_profile=image.info.get('icc_profile')) ``` -------------------------------- ### Load OpenSlide DLLs on Windows Source: https://context7.com/openslide/openslide-python/llms.txt On Windows, if managing OpenSlide binaries manually, load the DLL directory before importing the openslide library. This ensures the library can find its dependencies. ```python import os OPENSLIDE_PATH = r'C:\path\to\openslide-win64\bin' if hasattr(os, 'add_dll_directory'): with os.add_dll_directory(OPENSLIDE_PATH): import openslide else: import openslide ``` -------------------------------- ### Transform Image using ICC Profiles Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Shows how to use PIL.ImageCms to transform an image's colors using its embedded ICC profile and a target sRGB profile. ```python from io import BytesIO from PIL import ImageCms fromProfile = ImageCms.getOpenProfile(BytesIO(image.info['icc_profile'])) toProfile = ImageCms.createProfile('sRGB') intent = ImageCms.getDefaultIntent(fromProfile) ImageCms.profileToProfile( image, fromProfile, toProfile, intent, 'RGBA', True, 0 ) ``` -------------------------------- ### ImageSlide Usage Source: https://context7.com/openslide/openslide-python/llms.txt Demonstrates how to open image slides from a file path or a PIL Image object and access basic slide properties. ```APIDOC ## ImageSlide ### Description Opens an image slide from a file path or a PIL Image object. ### Usage ```python from openslide import ImageSlide from PIL import Image # From a file path with ImageSlide('overview.png') as slide: print(slide.level_count) print(slide.dimensions) print(slide.level_downsamples) region = slide.read_region((100, 100), 0, (256, 256)) print(region.size) # Wrap an in-memory PIL Image img = Image.open('photo.jpg') with ImageSlide(img) as slide: thumb = slide.get_thumbnail((200, 200)) print(thumb.size) ``` ``` -------------------------------- ### OpenSlide.detect_format Class Method Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Detects the format of a given whole-slide image file. Returns a string describing the format vendor or None if the format is not recognized. ```APIDOC #### *classmethod* detect_format(filename: str | bytes | PathLike[Any]) → str | None Return a string describing the format vendor of the specified file. This string is also accessible via the [`PROPERTY_NAME_VENDOR`](#openslide.PROPERTY_NAME_VENDOR) property. If the file is not recognized, return `None`. * **Parameters:** **filename** – the file to examine ``` -------------------------------- ### open_slide Function Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Opens a slide image file and returns an appropriate slide object. ```APIDOC ### openslide.open_slide(filename: str | bytes | PathLike[Any]) → [OpenSlide](#openslide.OpenSlide) | [ImageSlide](#openslide.ImageSlide) Return an [`OpenSlide`](#openslide.OpenSlide) for whole-slide images and an [`ImageSlide`](#openslide.ImageSlide) for other types of images. * **Parameters:** **filename** – the file to open * **Raises:** * [**OpenSlideError**](#openslide.OpenSlideError) – if the file is recognized by OpenSlide but an error occurred * **OSError** – if the file is not recognized at all ``` -------------------------------- ### DeepZoomGenerator Source: https://context7.com/openslide/openslide-python/llms.txt Explains how to use DeepZoomGenerator to create Deep Zoom tiles from an AbstractSlide object. ```APIDOC ## openslide.deepzoom.DeepZoomGenerator ### Description Wraps any `AbstractSlide` to generate tiled Deep Zoom images compatible with OpenSeadragon and other DZI viewers. Computes a full DZI pyramid with configurable tile size, overlap, and optional bounding-box clipping. ### Usage ```python from openslide import open_slide from openslide.deepzoom import DeepZoomGenerator with open_slide('scan.svs') as slide: dz = DeepZoomGenerator(slide, tile_size=254, overlap=1, limit_bounds=True) print(dz.level_count) print(dz.tile_count) print(dz.level_dimensions) print(dz.level_tiles) # Get the XML .dzi descriptor dzi_xml = dz.get_dzi('jpeg') print(dzi_xml[:120]) # Fetch a specific tile as a PIL RGB Image last_level = dz.level_count - 1 tile = dz.get_tile(last_level, (0, 0)) print(tile.size) print(tile.mode) # Save a tile to disk from io import BytesIO buf = BytesIO() tile.save(buf, 'jpeg', quality=75, icc_profile=tile.info.get('icc_profile')) ``` ``` -------------------------------- ### Generate Thumbnail with OpenSlide Source: https://context7.com/openslide/openslide-python/llms.txt Generates an RGB Pillow Image thumbnail scaled to fit within specified dimensions while preserving aspect ratio. Applies slide background color and ICC profile. ```python from openslide import OpenSlide with OpenSlide('scan.svs') as slide: thumb = slide.get_thumbnail((512, 512)) print(thumb.size) # e.g. (512, 365) - aspect ratio preserved print(thumb.mode) # 'RGB' # Save with embedded ICC profile if available thumb.save('thumbnail.png', icc_profile=thumb.info.get('icc_profile')) ``` -------------------------------- ### Set Custom Cache for OpenSlide Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Explains how to attach a custom OpenSlideCache object to an OpenSlide instance to manage recently decoded tiles. Requires OpenSlide version 4.0.0 or later. ```python openslide.OpenSlide.set_cache(cache) ``` -------------------------------- ### Generate Deep Zoom Tiles with DeepZoomGenerator Source: https://context7.com/openslide/openslide-python/llms.txt Shows how to use DeepZoomGenerator to create a Deep Zoom pyramid from a slide. This is useful for web-based viewers like OpenSeadragon. Ensure the 'scan.svs' file exists. ```python from openslide import open_slide from openslide.deepzoom import DeepZoomGenerator with open_slide('scan.svs') as slide: dz = DeepZoomGenerator(slide, tile_size=254, overlap=1, limit_bounds=True) print(dz.level_count) # e.g. 16 print(dz.tile_count) # total number of tiles across all levels print(dz.level_dimensions) # dimensions in pixels per DZI level print(dz.level_tiles) # (cols, rows) tile counts per DZI level # Get the XML .dzi descriptor (serve as application/xml) dzi_xml = dz.get_dzi('jpeg') print(dzi_xml[:120]) # # # Fetch a specific tile as a PIL RGB Image last_level = dz.level_count - 1 tile = dz.get_tile(last_level, (0, 0)) print(tile.size) # e.g. (255, 255) print(tile.mode) # 'RGB' # Save a tile to disk from io import BytesIO buf = BytesIO() tile.save(buf, 'jpeg', quality=75, icc_profile=tile.info.get('icc_profile')) ``` -------------------------------- ### OpenSlide.properties Source: https://context7.com/openslide/openslide-python/llms.txt Provides read-only access to a mapping of all OpenSlide properties for the slide. This includes vendor-specific metadata and standard properties like microns-per-pixel, objective power, and background color. ```APIDOC ## `OpenSlide.properties` — Access slide metadata A read-only `Mapping[str, str]` of all OpenSlide properties for the slide, including vendor-specific metadata and standard properties (microns-per-pixel, objective power, background color, bounding box of tissue region, etc.). ```python import openslide from openslide import OpenSlide with OpenSlide('scan.svs') as slide: props = slide.properties # Standard property constants print(props.get(openslide.PROPERTY_NAME_VENDOR)) # 'aperio' print(props.get(openslide.PROPERTY_NAME_MPP_X)) # '0.2527' print(props.get(openslide.PROPERTY_NAME_MPP_Y)) # '0.2527' print(props.get(openslide.PROPERTY_NAME_OBJECTIVE_POWER)) # '40' print(props.get(openslide.PROPERTY_NAME_BACKGROUND_COLOR)) # 'FFFFFF' # Microns-per-pixel for physical scale mpp_x = float(props.get(openslide.PROPERTY_NAME_MPP_X, 0)) mpp_y = float(props.get(openslide.PROPERTY_NAME_MPP_Y, 0)) print(f'Physical resolution: {mpp_x:.4f} x {mpp_y:.4f} µm/px') # Enumerate all properties for key, value in props.items(): print(f' {key}: {value}') ``` ``` -------------------------------- ### OpenSlide.get_thumbnail Source: https://context7.com/openslide/openslide-python/llms.txt Generates an RGB Pillow Image thumbnail, scaled to fit within specified dimensions while maintaining aspect ratio. It also applies the slide's background color and ICC profile. ```APIDOC ## `OpenSlide.get_thumbnail` — Generate a scaled thumbnail Returns an RGB Pillow `Image` thumbnail, scaled to fit within the specified maximum size while preserving aspect ratio. Applies the slide's background color and ICC profile. ```python from openslide import OpenSlide with OpenSlide('scan.svs') as slide: thumb = slide.get_thumbnail((512, 512)) print(thumb.size) # e.g. (512, 365) - aspect ratio preserved print(thumb.mode) # 'RGB' # Save with embedded ICC profile if available thumb.save('thumbnail.png', icc_profile=thumb.info.get('icc_profile')) ``` ``` -------------------------------- ### openslide.OpenSlide Source: https://context7.com/openslide/openslide-python/llms.txt The primary class for reading whole-slide image (WSI) files. It supports context manager usage for automatic resource cleanup and raises specific errors for unsupported formats or read failures. ```APIDOC ## openslide.OpenSlide — Open a whole-slide image The primary class for reading WSI files. Supports context manager usage for automatic resource cleanup. Raises `OpenSlideUnsupportedFormatError` if the format is not recognized and `OpenSlideError` (with latching semantics) on read failures. ```python from openslide import OpenSlide, OpenSlideUnsupportedFormatError # Detect format without opening vendor = OpenSlide.detect_format('scan.tiff') print(vendor) # e.g. 'generic-tiff', 'aperio', 'hamamatsu', or None # Open and inspect slide metadata with OpenSlide('scan.svs') as slide: print(slide.level_count) # 4 print(slide.dimensions) # (46000, 32914) print(slide.level_dimensions) # ((46000, 32914), (11500, 8228), (2875, 2057), (718, 514)) print(slide.level_downsamples) # (1.0, 4.0, 16.0, 64.0) # Find the best level for a given display downsample factor level = slide.get_best_level_for_downsample(20) print(level) # 2 ``` ``` -------------------------------- ### get_tile Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Retrieves an RGB Image for a specified tile at a given Deep Zoom level. ```APIDOC ## get_tile(level: int, address: tuple[int, int]) -> Image ### Description Return an RGB `Image` for a tile. ### Parameters #### Path Parameters - **level** (int) - Required - The Deep Zoom level. - **address** (tuple[int, int]) - Required - The address of the tile within the level as a (column, row) tuple. ### Response #### Success Response (200) - **Image** - An RGB Image object representing the tile. ``` -------------------------------- ### Access Slide Metadata with OpenSlide Properties Source: https://context7.com/openslide/openslide-python/llms.txt Accesses a read-only mapping of OpenSlide properties for a slide, including vendor-specific metadata and standard properties like microns-per-pixel and objective power. Use constants like openslide.PROPERTY_NAME_MPP_X for reliable access. ```python import openslide from openslide import OpenSlide with OpenSlide('scan.svs') as slide: props = slide.properties # Standard property constants print(props.get(openslide.PROPERTY_NAME_VENDOR)) # 'aperio' print(props.get(openslide.PROPERTY_NAME_MPP_X)) # '0.2527' print(props.get(openslide.PROPERTY_NAME_MPP_Y)) # '0.2527' print(props.get(openslide.PROPERTY_NAME_OBJECTIVE_POWER)) # '40' print(props.get(openslide.PROPERTY_NAME_BACKGROUND_COLOR)) # 'FFFFFF' # Microns-per-pixel for physical scale mpp_x = float(props.get(openslide.PROPERTY_NAME_MPP_X, 0)) mpp_y = float(props.get(openslide.PROPERTY_NAME_MPP_Y, 0)) print(f'Physical resolution: {mpp_x:.4f} x {mpp_y:.4f} µm/px') # Enumerate all properties for key, value in props.items(): print(f' {key}: {value}') ``` -------------------------------- ### Jinja2 Template for Recursive File Listing Source: https://github.com/openslide/openslide-python/blob/main/examples/deepzoom/templates/files.html This Jinja2 template iterates through directory entries, displaying them as a nested list. It generates links for files and recursively lists subdirectories. Use this for dynamic navigation of hierarchical file structures. ```html {% for entry in root_dir.children recursive %}* {% if entry.url_path %} [{{ entry.name }}]({{ url_for('slide', path=entry.url_path) }}) {% else %} {{ entry.name }} {% endif %} {% if entry.children %} {{ loop(entry.children) }}{% endif %} {% else %}* None {% endfor %} ``` -------------------------------- ### get_thumbnail Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Generates and returns an RGB thumbnail of the slide, constrained by the specified maximum size. ```APIDOC ## get_thumbnail(size: tuple[int, int]) -> Image ### Description Return an `Image` containing an RGB thumbnail of the slide. ### Parameters #### Path Parameters - **size** (tuple[int, int]) - Required - the maximum size of the thumbnail as a `(width, height)` tuple ``` -------------------------------- ### Open Slide Functionality Source: https://github.com/openslide/openslide-python/blob/main/examples/deepzoom/templates/slide-multipane.html Defines a function to open a slide in the viewer, handling both DZI XML provided directly and DZI XML fetched from a server. It also updates the scale bar with the correct pixels per meter. ```javascript function open_slide(url, mpp) { var tile_source; if (dzi_data[url]) { // DZI XML provided as template argument (deepzoom_python) tile_source = new OpenSeadragon.DziTileSource( OpenSeadragon.DziTileSource.prototype.configure( OpenSeadragon.parseXml(dzi_data[url]), url)); } else { // DZI XML fetched from server (deepzoom_server.py) tile_source = url; } viewer.open(tile_source); viewer.scalebar({ pixelsPerMeter: mpp ? (1e6 / mpp) : 0, }); } ``` -------------------------------- ### Wrap Standard Image as OpenSlide Source: https://context7.com/openslide/openslide-python/llms.txt Wraps a Pillow-readable image or a PIL.Image object into an OpenSlide-compatible interface, allowing unified code paths for both Whole Slide Images and standard images. ```python from PIL import Image from openslide import ImageSlide ``` -------------------------------- ### openslide.ImageSlide Source: https://context7.com/openslide/openslide-python/llms.txt Wraps standard Pillow-readable images (like PNG, JPEG, TIFF) or existing `PIL.Image` objects into an `OpenSlide`-compatible interface. This allows for unified code paths that can handle both whole slide images and regular images seamlessly. ```APIDOC ## `openslide.ImageSlide` — Wrap a standard image as a slide Wraps any Pillow-readable image (PNG, JPEG, TIFF, etc.) or an existing `PIL.Image` object in an `OpenSlide`-compatible interface, enabling unified code paths that work for both WSI and standard images. ```python from PIL import Image from openslide import ImageSlide ``` ``` -------------------------------- ### Inspect OpenSlide Image Metadata Source: https://context7.com/openslide/openslide-python/llms.txt Open a whole-slide image using the `OpenSlide` class and inspect its metadata such as level count, dimensions, level dimensions, and downsample factors. Supports context manager usage for automatic resource cleanup. ```python from openslide import OpenSlide, OpenSlideUnsupportedFormatError # Detect format without opening vendor = OpenSlide.detect_format('scan.tiff') print(vendor) # e.g. 'generic-tiff', 'aperio', 'hamamatsu', or None # Open and inspect slide metadata with OpenSlide('scan.svs') as slide: print(slide.level_count) # 4 print(slide.dimensions) # (46000, 32914) print(slide.level_dimensions) # ((46000, 32914), (11500, 8228), (2875, 2057), (718, 514)) print(slide.level_downsamples) # (1.0, 4.0, 16.0, 64.0) # Find the best level for a given display downsample factor level = slide.get_best_level_for_downsample(20) print(level) # 2 ``` -------------------------------- ### openslide.open_slide Source: https://context7.com/openslide/openslide-python/llms.txt A convenience factory function to open any slide or image file. It returns an OpenSlide object for recognized whole-slide formats or an ImageSlide wrapper for standard image files. This is the recommended entry point for most use cases. ```APIDOC ## openslide.open_slide — Open any slide or image file Convenience factory that returns an `OpenSlide` for recognized whole-slide formats, or an `ImageSlide` wrapper for standard image files (PNG, JPEG, etc.). This is the recommended entry point for most use cases. ```python from openslide import open_slide, OpenSlideUnsupportedFormatError try: slide = open_slide('tumor_section.svs') print(type(slide)) # print(slide.dimensions) # (46000, 32914) - (width, height) at level 0 slide.close() except OSError as e: print(f'Could not open file: {e}') # Works equally well with a regular PNG img_slide = open_slide('overview.png') print(type(img_slide)) # img_slide.close() ``` ``` -------------------------------- ### OpenSlide Property Names Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Constants representing property names for accessing slide metadata. ```APIDOC ## openslide.PROPERTY_NAME_QUICKHASH1 The name of the property containing the “quickhash-1” sum. ## openslide.PROPERTY_NAME_BACKGROUND_COLOR The name of the property containing a slide’s background color, if any. It is represented as an RGB hex triplet. ## openslide.PROPERTY_NAME_OBJECTIVE_POWER The name of the property containing a slide’s objective power, if known. ## openslide.PROPERTY_NAME_MPP_X The name of the property containing the number of microns per pixel in the X dimension of level 0, if known. ## openslide.PROPERTY_NAME_MPP_Y The name of the property containing the number of microns per pixel in the Y dimension of level 0, if known. ## openslide.PROPERTY_NAME_BOUNDS_X The name of the property containing the X coordinate of the rectangle bounding the non-empty region of the slide, if available. ## openslide.PROPERTY_NAME_BOUNDS_Y The name of the property containing the Y coordinate of the rectangle bounding the non-empty region of the slide, if available. ## openslide.PROPERTY_NAME_BOUNDS_WIDTH The name of the property containing the width of the rectangle bounding the non-empty region of the slide, if available. ## openslide.PROPERTY_NAME_BOUNDS_HEIGHT The name of the property containing the height of the rectangle bounding the non-empty region of the slide, if available. ``` -------------------------------- ### get_best_level_for_downsample Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Determines the most suitable level for displaying the slide at a given downsample factor. ```APIDOC ## get_best_level_for_downsample(downsample: float) -> int ### Description Return the best level for displaying the given downsample. ### Parameters #### Path Parameters - **downsample** (float) - Required - the desired downsample factor ``` -------------------------------- ### OpenSlide Exceptions Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Custom exceptions raised by the OpenSlide library for error handling. ```APIDOC ## openslide.OpenSlideError An error produced by the OpenSlide library. Once [`OpenSlideError`](#openslide.OpenSlideError) has been raised by a particular [`OpenSlide`](#openslide.OpenSlide), all future operations on that [`OpenSlide`](#openslide.OpenSlide) (other than [`close()`](#openslide.OpenSlide.close)) will also raise [`OpenSlideError`](#openslide.OpenSlideError). ## openslide.OpenSlideUnsupportedFormatError OpenSlide does not support the requested file. Subclass of [`OpenSlideError`](#openslide.OpenSlideError). ## openslide.OpenSlideVersionError This version of OpenSlide does not support the requested functionality. Subclass of [`OpenSlideError`](#openslide.OpenSlideError). ``` -------------------------------- ### OpenSlide.color_profile Source: https://context7.com/openslide/openslide-python/llms.txt Retrieves the embedded ICC color profile as a Pillow `ImageCmsProfile` object. Returns `None` if no profile is available. This profile can be used to transform image regions from the slide's color space to sRGB. ```APIDOC ## `OpenSlide.color_profile` — Access the ICC color profile Returns the embedded ICC color profile as a Pillow `ImageCmsProfile` object, or `None` if no profile is available. All regions/thumbnails from a given slide share the same pyramid color profile, accessible here as a convenience. ```python from io import BytesIO from PIL import ImageCms from openslide import OpenSlide with OpenSlide('scan.tiff') as slide: if slide.color_profile is not None: # Convert a region from slide color space to sRGB region = slide.read_region((0, 0), 0, (512, 512)) to_srgb = ImageCms.createProfile('sRGB') intent = ImageCms.getDefaultIntent(slide.color_profile) # Build a reusable transform for multiple regions transform = ImageCms.buildTransform( slide.color_profile, to_srgb, 'RGBA', 'RGBA', intent, 0 ) ImageCms.applyTransform(region, transform, inPlace=True) region.save('region_srgb.png') else: print('No ICC profile embedded in this slide') ``` ``` -------------------------------- ### OpenSlide Class Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md The main class for interacting with whole-slide images. It allows opening image files, accessing properties, and reading image data. Operations can raise OpenSlideError on failure. The object can be used as a context manager. ```APIDOC ## class openslide.OpenSlide(filename: str | bytes | PathLike[Any]) An open whole-slide image. If any operation on the object fails, [`OpenSlideError`](#openslide.OpenSlideError) is raised. OpenSlide has latching error semantics: once [`OpenSlideError`](#openslide.OpenSlideError) is raised, all future operations on the [`OpenSlide`](#openslide.OpenSlide), other than [`close()`](#openslide.OpenSlide.close), will also raise [`OpenSlideError`](#openslide.OpenSlideError). [`close()`](#openslide.OpenSlide.close) is called automatically when the object is deleted. The object may be used as a context manager, in which case it will be closed upon exiting the context. * **Parameters:** **filename** – the file to open * **Raises:** * [**OpenSlideUnsupportedFormatError**](#openslide.OpenSlideUnsupportedFormatError) – if the file is not recognized by OpenSlide * [**OpenSlideError**](#openslide.OpenSlideError) – if the file is recognized but an error occurred ``` -------------------------------- ### OpenSlideCache Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md An in-memory tile cache that can be attached to OpenSlide objects to store recently decoded tiles. ```APIDOC ### *class* openslide.OpenSlideCache(capacity: int) An in-memory tile cache. Tile caches can be attached to one or more [`OpenSlide`](#openslide.OpenSlide) objects with [`OpenSlide.set_cache()`](#openslide.OpenSlide.set_cache) to cache recently-decoded tiles. By default, each [`OpenSlide`](#openslide.OpenSlide) has its own cache with a default size. ### Parameters #### Path Parameters - **capacity** (int) - the cache capacity in bytes ### Raises [**OpenSlideVersionError**](#openslide.OpenSlideVersionError) – if OpenSlide is older than version 4.0.0 ``` -------------------------------- ### get_tile_coordinates Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Returns the arguments needed for OpenSlide.read_region() corresponding to a specific tile. ```APIDOC ## get_tile_coordinates(level: int, address: tuple[int, int]) -> tuple[tuple[int, int], int, tuple[int, int]] ### Description Return the [`OpenSlide.read_region()`](#openslide.OpenSlide.read_region) arguments corresponding to the specified tile. Most applications should use [`get_tile()`](#openslide.deepzoom.DeepZoomGenerator.get_tile) instead. ### Parameters #### Path Parameters - **level** (int) - Required - The Deep Zoom level. - **address** (tuple[int, int]) - Required - The address of the tile within the level as a (column, row) tuple. ### Response #### Success Response (200) - **tuple[tuple[int, int], int, tuple[int, int]]** - Arguments for OpenSlide.read_region(). ``` -------------------------------- ### DeepZoomGenerator Class Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Generates Deep Zoom tiles from a slide object. ```APIDOC ### *class* openslide.deepzoom.DeepZoomGenerator(osr: [AbstractSlide](#openslide.AbstractSlide), tile_size: int = 254, overlap: int = 1, limit_bounds: bool = False) A Deep Zoom generator that wraps an [`OpenSlide`](#openslide.OpenSlide) object, [`ImageSlide`](#openslide.ImageSlide) object, or user-provided instance of [`AbstractSlide`](#openslide.AbstractSlide). * **Parameters:** * **osr** – the slide object * **tile_size** – the width and height of a single tile. For best viewer performance, `tile_size + 2 * overlap` should be a power of two. * **overlap** – the number of extra pixels to add to each interior edge of a tile * **limit_bounds** – `True` to render only the non-empty slide region #### level_count The number of Deep Zoom levels in the image. * **Type:** int #### tile_count The total number of Deep Zoom tiles in the image. * **Type:** int #### level_tiles A tuple of `(tiles_x, tiles_y)` tuples for each Deep Zoom level. `level_tiles[k]` are the tile counts of level `k`. * **Type:** tuple[tuple[int, int], …] #### level_dimensions A tuple of `(pixels_x, pixels_y)` tuples for each Deep Zoom level. `level_dimensions[k]` are the dimensions of level `k`. * **Type:** tuple[tuple[int, int], …] #### get_dzi(format: str) → str Return a string containing the XML metadata for the Deep Zoom `.dzi` file. * **Parameters:** **format** – the delivery format of the individual tiles (`png` or `jpeg`) ``` -------------------------------- ### ImageSlide Class Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md A class that wraps a Pillow Image object, providing an OpenSlide-compatible API. ```APIDOC ### *class* openslide.ImageSlide(file: str | bytes | PathLike[Any] | Image) A wrapper around an `Image` object that provides an [`OpenSlide`](#openslide.OpenSlide)-compatible API. * **Parameters:** **file** – a filename or `Image` object * **Raises:** **OSError** – if the file cannot be opened ``` -------------------------------- ### Attach Shared Tile Cache with OpenSlide Source: https://context7.com/openslide/openslide-python/llms.txt Attaches an OpenSlideCache to an OpenSlide object to share decoded tiles among multiple OpenSlide instances, managing total memory usage. Requires OpenSlide version 4.0.0 or later. ```python from openslide import OpenSlide, OpenSlideCache # Create a 256 MB shared cache shared_cache = OpenSlideCache(256 << 20) slides = [] for path in ['slide1.svs', 'slide2.svs', 'slide3.svs']: s = OpenSlide(path) s.set_cache(shared_cache) slides.append(s) # All three slides share the 256 MB tile cache for slide in slides: region = slide.read_region((0, 0), 0, (512, 512)) # ... process region ... slide.close() ``` -------------------------------- ### Handle ICC Color Profile with OpenSlide Source: https://context7.com/openslide/openslide-python/llms.txt Accesses the embedded ICC color profile as a Pillow ImageCmsProfile object. If a profile exists, it can be used to transform image regions from the slide's color space to sRGB. ```python from io import BytesIO from PIL import ImageCms from openslide import OpenSlide with OpenSlide('scan.tiff') as slide: if slide.color_profile is not None: # Convert a region from slide color space to sRGB region = slide.read_region((0, 0), 0, (512, 512)) to_srgb = ImageCms.createProfile('sRGB') intent = ImageCms.getDefaultIntent(slide.color_profile) # Build a reusable transform for multiple regions transform = ImageCms.buildTransform( slide.color_profile, to_srgb, 'RGBA', 'RGBA', intent, 0 ) ImageCms.applyTransform(region, transform, inPlace=True) region.save('region_srgb.png') else: print('No ICC profile embedded in this slide') ``` -------------------------------- ### set_cache Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Configures the OpenSlide object to use a specified cache for recently decoded slide tiles. This replaces the default private cache. ```APIDOC ## set_cache(cache: [OpenSlideCache](#openslide.OpenSlideCache)) -> None ### Description Use the specified [`OpenSlideCache`](#openslide.OpenSlideCache) to store recently decoded slide tiles. By default, the [`OpenSlide`](#openslide.OpenSlide) has a private cache with a default size. ### Parameters #### Path Parameters - **cache** ([OpenSlideCache](#openslide.OpenSlideCache)) - Required - a cache object ### Raises [**OpenSlideVersionError**](#openslide.OpenSlideVersionError) – if OpenSlide is older than version 4.0.0 ``` -------------------------------- ### OpenSlide.set_cache Source: https://context7.com/openslide/openslide-python/llms.txt Attaches a shared `OpenSlideCache` to the slide, allowing multiple `OpenSlide` objects to share a single tile cache. This helps manage total memory usage across parallel workflows. Requires OpenSlide version 4.0.0 or later. ```APIDOC ## `OpenSlide.set_cache` — Attach a shared tile cache Attaches an `OpenSlideCache` to the slide to store recently decoded tiles, replacing the per-slide private cache. Multiple `OpenSlide` objects can share the same cache to manage total memory usage across parallel workflows. Requires OpenSlide ≥ 4.0.0. ```python from openslide import OpenSlide, OpenSlideCache # Create a 256 MB shared cache shared_cache = OpenSlideCache(256 << 20) slides = [] for path in ['slide1.svs', 'slide2.svs', 'slide3.svs']: s = OpenSlide(path) s.set_cache(shared_cache) slides.append(s) # All three slides share the 256 MB tile cache for slide in slides: region = slide.read_region((0, 0), 0, (512, 512)) # ... process region ... slide.close() ``` ``` -------------------------------- ### close Source: https://github.com/openslide/openslide-python/blob/main/doc/index.md Releases resources associated with the OpenSlide object by closing it. ```APIDOC ## close() -> None ### Description Close the OpenSlide object. ``` -------------------------------- ### Access Associated Images with OpenSlide Source: https://context7.com/openslide/openslide-python/llms.txt Retrieves embedded images like 'label' or 'thumbnail' from a slide file as RGBA Pillow objects. Handles ICC profile data if available. Raises KeyError for missing image names. ```python from openslide import OpenSlide with OpenSlide('scan.svs') as slide: print(list(slide.associated_images.keys())) # ['label', 'thumbnail', 'macro'] label = slide.associated_images['label'] print(label.size) # e.g. (387, 463) print(label.mode) # 'RGBA' label.save('label.png', icc_profile=label.info.get('icc_profile')) # KeyError for missing names try: slide.associated_images['missing'] except KeyError: print('Associated image not found') ``` -------------------------------- ### OpenSlide.associated_images Source: https://context7.com/openslide/openslide-python/llms.txt Accesses a mapping of images embedded within the slide file, such as 'label' (slide label scan) and 'thumbnail' (macro overview image). Images are returned as RGBA Pillow objects and include ICC profile data if available. ```APIDOC ## `OpenSlide.associated_images` — Access label and macro images A `Mapping[str, PIL.Image]` of images embedded in the slide file, such as `'label'` (slide label scan) and `'thumbnail'` (macro overview image). Images are returned as RGBA Pillow objects and include ICC profile data where available. ```python from openslide import OpenSlide with OpenSlide('scan.svs') as slide: print(list(slide.associated_images.keys())) # ['label', 'thumbnail', 'macro'] label = slide.associated_images['label'] print(label.size) # e.g. (387, 463) print(label.mode) # 'RGBA' label.save('label.png', icc_profile=label.info.get('icc_profile')) # KeyError for missing names try: slide.associated_images['missing'] except KeyError: print('Associated image not found') ``` ```