0
# Slide Operations
1
2
Core functionality for opening, reading, and manipulating whole-slide images. This module provides the primary user interface for working with digital pathology slides, supporting various file formats and providing efficient access to multi-resolution image data.
3
4
```python
5
import openslide
6
from openslide import OpenSlide, ImageSlide, OpenSlideCache, open_slide
7
from PIL import Image
8
from PIL.ImageCms import ImageCmsProfile
9
from collections.abc import Mapping
10
import os
11
```
12
13
## Capabilities
14
15
### Opening Slides
16
17
Functions and classes for opening different types of slide files with automatic format detection and proper resource management.
18
19
```python { .api }
20
def open_slide(filename: str | bytes | os.PathLike[Any]) -> OpenSlide | ImageSlide:
21
"""
22
Open a whole-slide or regular image file.
23
24
Automatically detects the file format and returns the appropriate slide object.
25
Returns OpenSlide for whole-slide images, ImageSlide for regular images.
26
27
Args:
28
filename: Path to the image file
29
30
Returns:
31
OpenSlide object for whole-slide images, ImageSlide for regular images
32
33
Raises:
34
OpenSlideError: If there's an error opening the file
35
"""
36
37
class OpenSlide:
38
"""
39
Main interface for OpenSlide whole-slide images.
40
41
Supports context manager protocol for automatic resource cleanup.
42
Has latching error semantics - once an error occurs, all operations fail.
43
"""
44
45
def __init__(self, filename: str | bytes | os.PathLike[Any]):
46
"""
47
Open a whole-slide image file.
48
49
Args:
50
filename: Path to the whole-slide image file
51
52
Raises:
53
OpenSlideUnsupportedFormatError: If the file format is not supported
54
OpenSlideError: If there's an error opening the file
55
"""
56
57
@classmethod
58
def detect_format(cls, filename: str | bytes | os.PathLike[Any]) -> str | None:
59
"""
60
Detect the format vendor of a slide file.
61
62
Args:
63
filename: Path to the slide file
64
65
Returns:
66
String describing the format vendor, or None if not recognized
67
"""
68
69
class ImageSlide:
70
"""
71
Wrapper for PIL.Image that provides the OpenSlide interface.
72
73
Allows regular images to be used with OpenSlide-compatible APIs.
74
"""
75
76
def __init__(self, file: str | bytes | os.PathLike[Any] | Image.Image):
77
"""
78
Open an image file or wrap a PIL.Image.
79
80
Args:
81
file: Path to image file or PIL.Image object
82
"""
83
84
@classmethod
85
def detect_format(cls, filename: str | bytes | os.PathLike[Any]) -> str | None:
86
"""
87
Detect the format of an image file.
88
89
Args:
90
filename: Path to the image file
91
92
Returns:
93
PIL format string, or None if not recognized
94
"""
95
```
96
97
### Reading Image Data
98
99
Methods for extracting regions, thumbnails, and associated images from slides.
100
101
```python { .api }
102
class AbstractSlide:
103
"""Base class for all slide objects"""
104
105
def read_region(self, location: tuple[int, int], level: int, size: tuple[int, int]) -> Image.Image:
106
"""
107
Read a rectangular region from the slide.
108
109
Args:
110
location: (x, y) top-left pixel coordinates in level 0 reference frame
111
level: Level number to read from (0 is highest resolution)
112
size: (width, height) size of region to read
113
114
Returns:
115
PIL.Image with RGBA format containing the region data
116
117
Raises:
118
OpenSlideError: If there's an error reading the region
119
"""
120
121
def get_thumbnail(self, size: tuple[int, int]) -> Image.Image:
122
"""
123
Generate a thumbnail of the entire slide.
124
125
Args:
126
size: Maximum (width, height) for the thumbnail
127
128
Returns:
129
PIL.Image in RGB format with thumbnail of the slide
130
"""
131
132
def get_best_level_for_downsample(self, downsample: float) -> int:
133
"""
134
Get the best level for a given downsample factor.
135
136
Args:
137
downsample: Desired downsample factor
138
139
Returns:
140
Level number that best matches the downsample factor
141
"""
142
143
def close(self) -> None:
144
"""
145
Close the slide and free associated resources.
146
147
After calling close(), no other operations are valid.
148
"""
149
```
150
151
### Slide Properties and Metadata
152
153
Access to slide dimensions, levels, properties, and associated images.
154
155
```python { .api }
156
class AbstractSlide:
157
@property
158
def dimensions(self) -> tuple[int, int]:
159
"""
160
Dimensions of level 0 (highest resolution) as (width, height).
161
"""
162
163
@property
164
def level_count(self) -> int:
165
"""
166
Number of resolution levels in the slide.
167
"""
168
169
@property
170
def level_dimensions(self) -> tuple[tuple[int, int], ...]:
171
"""
172
Dimensions for each level as tuple of (width, height) tuples.
173
174
level_dimensions[n] contains dimensions of level n.
175
"""
176
177
@property
178
def level_downsamples(self) -> tuple[float, ...]:
179
"""
180
Downsample factors for each level.
181
182
level_downsamples[n] contains the downsample factor of level n
183
relative to level 0.
184
"""
185
186
@property
187
def properties(self) -> Mapping[str, str]:
188
"""
189
Slide metadata as a mapping of property name to value.
190
191
Common properties include vendor, comment, objective power,
192
microns per pixel, and slide bounds information.
193
"""
194
195
@property
196
def associated_images(self) -> Mapping[str, Image.Image]:
197
"""
198
Associated images as a mapping of image name to PIL.Image.
199
200
Common associated images include 'label', 'macro', and 'thumbnail'.
201
Images are not premultiplied.
202
"""
203
204
@property
205
def color_profile(self) -> ImageCms.ImageCmsProfile | None:
206
"""
207
ICC color profile for the slide, or None if unavailable.
208
209
Requires OpenSlide 4.0.0+.
210
"""
211
```
212
213
### Performance Optimization
214
215
Caching functionality for improved performance when reading multiple regions.
216
217
```python { .api }
218
class OpenSlideCache:
219
"""
220
In-memory tile cache for improved slide reading performance.
221
222
Can be shared across multiple OpenSlide objects.
223
"""
224
225
def __init__(self, capacity: int):
226
"""
227
Create a tile cache.
228
229
Args:
230
capacity: Cache capacity in bytes
231
"""
232
233
class OpenSlide:
234
def set_cache(self, cache: OpenSlideCache) -> None:
235
"""
236
Use the specified cache for storing decoded slide tiles.
237
238
By default, each OpenSlide object has its own cache.
239
240
Args:
241
cache: OpenSlideCache object to use
242
243
Raises:
244
TypeError: If cache is not an OpenSlideCache object
245
"""
246
```
247
248
## Usage Examples
249
250
### Basic Slide Reading
251
252
```python
253
import openslide
254
255
# Open a slide with automatic format detection
256
with openslide.open_slide("slide.svs") as slide:
257
# Get slide information
258
print(f"Format: {slide.detect_format('slide.svs')}")
259
print(f"Dimensions: {slide.dimensions}")
260
print(f"Levels: {slide.level_count}")
261
262
# Read a 1000x1000 pixel region from level 0
263
region = slide.read_region((5000, 5000), 0, (1000, 1000))
264
region.save("region.png")
265
266
# Generate thumbnail
267
thumb = slide.get_thumbnail((500, 500))
268
thumb.save("thumbnail.jpg")
269
```
270
271
### Working with Multiple Levels
272
273
```python
274
with openslide.OpenSlide("slide.svs") as slide:
275
print("Level information:")
276
for level in range(slide.level_count):
277
dims = slide.level_dimensions[level]
278
downsample = slide.level_downsamples[level]
279
print(f" Level {level}: {dims[0]}x{dims[1]} (downsample: {downsample:.2f}x)")
280
281
# Read same region at different resolutions
282
location = (10000, 10000)
283
size = (512, 512)
284
285
# High resolution (level 0)
286
high_res = slide.read_region(location, 0, size)
287
288
# Lower resolution (level 2)
289
low_res = slide.read_region(location, 2, size)
290
```
291
292
### Using Caching for Performance
293
294
```python
295
import openslide
296
297
# Create a shared cache
298
cache = openslide.OpenSlideCache(256 * 1024 * 1024) # 256MB
299
300
# Use cache with multiple slides
301
with openslide.OpenSlide("slide1.svs") as slide1:
302
slide1.set_cache(cache)
303
region1 = slide1.read_region((0, 0), 0, (512, 512))
304
305
with openslide.OpenSlide("slide2.svs") as slide2:
306
slide2.set_cache(cache)
307
region2 = slide2.read_region((0, 0), 0, (512, 512))
308
```
309
310
### Accessing Slide Properties
311
312
```python
313
with openslide.OpenSlide("slide.svs") as slide:
314
# Access common properties using constants
315
vendor = slide.properties.get(openslide.PROPERTY_NAME_VENDOR, "Unknown")
316
objective = slide.properties.get(openslide.PROPERTY_NAME_OBJECTIVE_POWER, "Unknown")
317
mpp_x = slide.properties.get(openslide.PROPERTY_NAME_MPP_X, "Unknown")
318
319
print(f"Vendor: {vendor}")
320
print(f"Objective: {objective}")
321
print(f"Microns per pixel (X): {mpp_x}")
322
323
# List all available properties
324
print("All properties:")
325
for key, value in slide.properties.items():
326
print(f" {key}: {value}")
327
328
# Access associated images
329
print("Associated images:")
330
for name, image in slide.associated_images.items():
331
print(f" {name}: {image.size}")
332
image.save(f"associated_{name}.png")
333
```