stainnormprogram 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. stainnormprogram/__about__.py +1 -0
  2. stainnormprogram/__init__.py +2 -0
  3. stainnormprogram/assessment/__init__.py +1 -0
  4. stainnormprogram/assessment/assessment.py +1186 -0
  5. stainnormprogram/assessment/background.py +211 -0
  6. stainnormprogram/assessment/color.py +770 -0
  7. stainnormprogram/assessment/contrast.py +252 -0
  8. stainnormprogram/assessment/gamut.py +407 -0
  9. stainnormprogram/assessment/palette.py +648 -0
  10. stainnormprogram/assessment/plot.py +759 -0
  11. stainnormprogram/assessment/structure.py +158 -0
  12. stainnormprogram/correction/__init__.py +1 -0
  13. stainnormprogram/correction/macenko.py +469 -0
  14. stainnormprogram/io/__init__.py +0 -0
  15. stainnormprogram/io/write_slide.py +119 -0
  16. stainnormprogram/library/TCGA-Manifest.txt +31 -0
  17. stainnormprogram/library/TCIA-Instructions.md +15 -0
  18. stainnormprogram/library/library.md +14 -0
  19. stainnormprogram/norm/__init__.py +1 -0
  20. stainnormprogram/norm/adjustments.py +88 -0
  21. stainnormprogram/norm/background.py +273 -0
  22. stainnormprogram/norm/normalization.py +126 -0
  23. stainnormprogram/norm/pipeline/__init__.py +0 -0
  24. stainnormprogram/norm/pipeline/macenko.py +302 -0
  25. stainnormprogram/norm/pipeline/pipeline.py +61 -0
  26. stainnormprogram/norm/style_estimation/__init__.py +0 -0
  27. stainnormprogram/norm/style_estimation/macenko.py +649 -0
  28. stainnormprogram/norm/subset.py +127 -0
  29. stainnormprogram/norm/translation/__init__.py +0 -0
  30. stainnormprogram/norm/translation/macenko.py +92 -0
  31. stainnormprogram/norm/utils.py +96 -0
  32. stainnormprogram/slide.py +1085 -0
  33. stainnormprogram-1.0.0.dist-info/METADATA +75 -0
  34. stainnormprogram-1.0.0.dist-info/RECORD +36 -0
  35. stainnormprogram-1.0.0.dist-info/WHEEL +4 -0
  36. stainnormprogram-1.0.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,1085 @@
1
+ import os
2
+ import random
3
+ import math
4
+ import time
5
+ import copy
6
+ from collections.abc import Callable
7
+
8
+ import openslide
9
+ import numpy as np
10
+ from skimage.color import rgb2hsv, rgb2luv, rgb2xyz, rgb2gray
11
+ from skimage.filters import threshold_otsu
12
+ import skimage.feature
13
+ import tifffile
14
+ import zarr
15
+ import colour
16
+ import pyvips
17
+ from PIL import Image
18
+ from bioio import BioImage
19
+ import bioio_bioformats
20
+
21
+ from stainnormprogram.norm.adjustments import Adjustment
22
+
23
+ class Tile:
24
+
25
+ def __init__(self, rgb_array: np.ndarray, adjustment: Adjustment | None = None):
26
+ """Wrapper around an image tile. Caches calculated color space conversions.
27
+
28
+ Args:
29
+ rgb_array: RGB (H,W,3) np.ndarray uint8 [0,255]
30
+ adjustment: Adjustment to apply.
31
+ """
32
+ if adjustment is not None:
33
+ rgb_array = adjustment.apply(rgb_array)
34
+ self.rgb_uint8 = rgb_array
35
+ self.rgb_tile = rgb_array / 255.0
36
+ self.hsv_tile = None
37
+ self.luv_tile = None
38
+ self.oklab_tile = None
39
+ self.u_prime = None
40
+ self.v_prime = None
41
+ self.od_tile = None
42
+ self.I0 = None
43
+ self.clip_min = None
44
+ self.gray_tile = None
45
+ self.canny_tile = None
46
+ self.sigma = None
47
+ self.lab_tile = None
48
+
49
+ def __repr__(self):
50
+ return f"Tile(H={self.rgb_tile.shape[0]}, W={self.rgb_tile.shape[1]}, C={self.rgb_tile.shape[2]})"
51
+
52
+ def rgb(self, as_uint8=False) -> np.ndarray:
53
+ """Get pixels in RGB (red, green, blue) color space.
54
+
55
+ Args:
56
+ as_uint8: When True, returns as RGB uint8 [0,255]. When False, values are scaled within the interval [0.,1.].
57
+
58
+ Returns:
59
+ A np.ndarray of RGB pixels.
60
+ """
61
+ return self.rgb_uint8 if as_uint8 else self.rgb_tile
62
+
63
+ def hsv(self) -> np.ndarray:
64
+ """Get pixels in HSV (hue, saturation, value) color space.
65
+
66
+ Expected output ranges:
67
+ * H 0.0 to 1.0
68
+ * S 0.0 to 1.0
69
+ * V 0.0 to 1.0
70
+
71
+ Returns:
72
+ A np.ndarray of HSV pixels.
73
+ """
74
+ if self.hsv_tile is None:
75
+ self.hsv_tile = rgb2hsv(self.rgb_tile)
76
+ return self.hsv_tile
77
+
78
+ def luv(self) -> np.ndarray:
79
+ """Get pixels in CIELUV color space.
80
+
81
+ Expected output ranges:
82
+ * L 0.0 to 100.0
83
+ * U -134.0 to 220.0 (Theoretically unbounded)
84
+ * V -140.0 to 122.0 (Theoretically unbounded)
85
+
86
+ Returns:
87
+ A np.ndarray of CIELUV pixels.
88
+ """
89
+ if self.luv_tile is None:
90
+ self.luv_tile = rgb2luv(self.rgb_tile)
91
+ return self.luv_tile
92
+
93
+ def oklab(self) -> np.ndarray:
94
+ """Get pixels in OKLAB color space.
95
+
96
+ Expected output ranges:
97
+ * L 0.0 to 1.0
98
+ * a -0.5 to 0.5 (Theoretically unbounded)
99
+ * b -0.5 to 0.5 (Theoretically unbounded)
100
+
101
+ Returns:
102
+ A np.ndarray of OKLAB pixels.
103
+ """
104
+ if self.oklab_tile is None:
105
+ self.oklab_tile = colour.convert(self.rgb_tile, "sRGB", "Oklab")
106
+ return self.oklab_tile
107
+
108
+ def u_prime_v_prime(self) -> tuple[np.ndarray, np.ndarray]:
109
+ """Get pixels in CIE 1976 u'v' chromaticity coordinates.
110
+
111
+ This function can return np.ndarrays containing np.nan when the denominator is 0.
112
+
113
+ Expected output ranges:
114
+ * u' 0.0 to 0.7 (Theoretically unbounded)
115
+ * v' 0.0 to 0.7 (Theoretically unbounded)
116
+
117
+ Returns:
118
+ A tuple of np.ndarrays, each (H,W). The first is u' and the second is v'.
119
+ """
120
+ if self.u_prime is None or self.v_prime is None:
121
+ xyz = rgb2xyz(self.rgb_tile)
122
+ X = xyz[:,:,0]
123
+ Y = xyz[:,:,1]
124
+ Z = xyz[:,:,2]
125
+ denominator = X + (15 * Y) + (3 * Z)
126
+ self.u_prime = np.divide(4 * X, denominator, out=np.full_like(X, np.nan, dtype=np.float64), where=denominator!=0)
127
+ self.v_prime = np.divide(9 * Y, denominator, out=np.full_like(Y, np.nan, dtype=np.float64), where=denominator!=0)
128
+ return self.u_prime, self.v_prime
129
+
130
+ def od(self, I0: np.ndarray, clip_min: int = 20) -> np.ndarray:
131
+ """Get pixels in Beer-Lambert's optical density (OD) space.
132
+
133
+ Args:
134
+ I0: Initial intensity.
135
+ clip_min: Min clamp [0, 255].
136
+
137
+ Returns:
138
+ A np.ndarray of OD pixels.
139
+ """
140
+ if self.od_tile is None or (not np.array_equal(self.I0, I0) or self.clip_min != clip_min):
141
+ tile = np.clip(self.rgb_uint8, clip_min, 255)
142
+ tile = np.log(tile / I0) * -1.0
143
+ tile = np.clip(tile, 0, None)
144
+ self.od_tile = tile
145
+ self.I0 = I0
146
+ self.clip_min = clip_min
147
+ return self.od_tile
148
+
149
+ def gray(self) -> np.ndarray:
150
+ """Get pixels in grayscale (uses scikit-image's rgb2gray, which is a perceptual grayscale instead of simple average).
151
+
152
+ Returns:
153
+ A np.ndarray of grayscale pixels.
154
+ """
155
+ if self.gray_tile is None:
156
+ self.gray_tile = rgb2gray(self.rgb_tile)
157
+ return self.gray_tile
158
+
159
+ def canny(self, sigma: float = 1.0) -> np.ndarray:
160
+ """Get Canny edge detection.
161
+
162
+ Args:
163
+ sigma: Gaussian filter sigma.
164
+
165
+ Returns:
166
+ A np.ndarray of a Canny edge detection bool mask. The output shape is (H,W).
167
+ """
168
+ if self.canny_tile is None or (self.sigma != sigma):
169
+ self.canny_tile = skimage.feature.canny(self.gray(), sigma=sigma)
170
+ self.sigma = sigma
171
+ return self.canny_tile
172
+
173
+ def lab(self) -> np.ndarray:
174
+ """Get pixels in CIELAB color space.
175
+
176
+ Expected output ranges:
177
+ * L 0.0 to 100.0
178
+ * A -128.0 to 127.0 (Theoretically unbounded)
179
+ * B -128.0 to 127.0 (Theoretically unbounded)
180
+
181
+ Returns:
182
+ A np.ndarray of CIELAB pixels.
183
+ """
184
+ if self.lab_tile is None:
185
+ self.lab_tile = colour.XYZ_to_Lab(colour.sRGB_to_XYZ(self.rgb_tile))
186
+ return self.lab_tile
187
+
188
+ class SequentialSlideImageIterator:
189
+
190
+ def __init__(self, slide: SlideImage, tile_size: int = 512):
191
+ """Iterator to go through tiles in a SlideImage sequentially (row major order).
192
+
193
+ Args:
194
+ slide: The SlideImage to iterate over.
195
+ tile_size: Tile size to use.
196
+ """
197
+ self.slide = slide
198
+ self.tile_size = tile_size
199
+ self.y = 0
200
+ self.x = 0
201
+ self.tile = None
202
+
203
+ def __next__(self) -> tuple[Tile, dict[str, int]]:
204
+
205
+ if self.x >= self.slide.shape[1]:
206
+ self.x = 0
207
+ self.y += self.tile_size
208
+ if self.y >= self.slide.shape[0]:
209
+ raise StopIteration
210
+ tile_w = self.tile_size
211
+ tile_h = self.tile_size
212
+ if self.y + tile_h > self.slide.shape[0]:
213
+ tile_h = self.slide.shape[0] - self.y
214
+ if self.x + tile_w > self.slide.shape[1]:
215
+ tile_w = self.slide.shape[1] - self.x
216
+
217
+ self.tile = self.slide.get_tile(self.y, self.x, tile_h, tile_w)
218
+
219
+ y = self.y
220
+ x = self.x
221
+ self.x += self.tile_size
222
+
223
+ return self.tile, {"y": y, "x": x, "h": tile_h, "w": tile_w}
224
+
225
+ class RandomSlideImageIterator:
226
+
227
+ def __init__(self, slide: SlideImage, tile_size: int = 128):
228
+ """Iterator to go through tiles in a SlideImage randomly (chosen using a grid).
229
+
230
+ Args:
231
+ slide: The SlideImage to iterate over.
232
+ tile_size: Tile size to use.
233
+ """
234
+ self.slide = slide
235
+ self.tile_size = tile_size
236
+ self.tile = None
237
+ self.coords = self._compute_random_sequence()
238
+ self.next_idx = 0
239
+
240
+ def _compute_random_sequence(self) -> list[tuple[int, int, int, int]]:
241
+ """Compute a random sequence of tile locations.
242
+
243
+ Returns:
244
+ A list containing tuples of y, x, tile height, tile width ints.
245
+ """
246
+ h, w = self.slide.shape
247
+ coords = []
248
+ for y in range(0, h, self.tile_size):
249
+ for x in range(0, w, self.tile_size):
250
+ tile_h = self.tile_size
251
+ tile_w = self.tile_size
252
+ if y + self.tile_size > h:
253
+ tile_h = h - y
254
+ if x + self.tile_size > w:
255
+ tile_w = w - x
256
+ coords.append((y, x, tile_h, tile_w))
257
+
258
+ random.shuffle(coords)
259
+
260
+ return coords
261
+
262
+ def __next__(self) -> tuple[Tile, dict[str, int]]:
263
+
264
+ if self.next_idx > len(self.coords) - 1:
265
+ raise StopIteration
266
+
267
+ y, x, tile_h, tile_w = self.coords[self.next_idx]
268
+ self.tile = self.slide.get_tile(y, x, tile_h, tile_w)
269
+ self.next_idx = self.next_idx + 1
270
+
271
+ return self.tile, {"y": y, "x": x, "h": tile_h, "w": tile_w}
272
+
273
+ class CustomSlideImageIterator:
274
+
275
+ def __init__(self, slide: SlideImage, locs: list[dict[str, int] | tuple[int, int, int, int]]):
276
+ """Iterator to go over tiles in a SlideImage using a custom order of locations to visit.
277
+
278
+ Args:
279
+ slide: The SlideImage to iterate over.
280
+ locs: A list of tile locations to visit in their preferred order. Each item is a dictionary with keys "y", "x", "h", and "w" and values as ints specifying the tile location. Each item can also be a tuple of the ints in y, x, h, w order.
281
+ """
282
+ self.slide = slide
283
+ self.locs = locs
284
+ self.tile = None
285
+ self.next_idx = 0
286
+
287
+ def __next__(self) -> tuple[Tile, dict[str, int] | tuple[int, int, int, int]]:
288
+
289
+ if self.next_idx > len(self.locs) - 1:
290
+ raise StopIteration
291
+
292
+ loc = self.locs[self.next_idx]
293
+ if isinstance(loc, dict):
294
+ y, x, tile_h, tile_w = loc["y"], loc["x"], loc["h"], loc["w"]
295
+ else:
296
+ y, x, tile_h, tile_w = loc
297
+ self.tile = self.slide.get_tile(y, x, tile_h, tile_w)
298
+ self.next_idx = self.next_idx + 1
299
+
300
+ return self.tile, loc
301
+
302
+ class CustomSlideImageCollectionIterator:
303
+
304
+ def __init__(self, slides: list[SlideImage], locs: list[dict[str, int | str]]):
305
+ """Iterator to go over tiles in a list of SlideImages using a custom order of locations to visit.
306
+
307
+ Args:
308
+ slides: The list of SlideImages to iterate over.
309
+ locs: A list of tile locations to visit in their preferred order. Each item is a dictionary with keys "identifier", "y", "x", "h", and "w" and values specifying the tile location.
310
+ """
311
+ self.slides = slides
312
+ self.locs = locs
313
+ self.tile = None
314
+ self.next_idx = 0
315
+
316
+ def __next__(self) -> tuple[Tile, dict[str, int | str]]:
317
+
318
+ if self.next_idx > len(self.locs) - 1:
319
+ raise StopIteration
320
+
321
+ loc = self.locs[self.next_idx]
322
+ identifier = loc["identifier"]
323
+ slide = self.slides[identifier]
324
+
325
+ y, x, tile_h, tile_w = loc["y"], loc["x"], loc["h"], loc["w"]
326
+
327
+ self.tile = slide.get_tile(y, x, tile_h, tile_w)
328
+ self.next_idx = self.next_idx + 1
329
+
330
+ return self.tile, loc
331
+
332
+ class RandomSlideImageCollectionIterator:
333
+
334
+ def __init__(self, slides: list[SlideImage], tile_size: int = 512):
335
+ """Iterator to go over tiles in a list of SlideImages randomly.
336
+
337
+ Args:
338
+ slides: The list of SlideImages to iterate over.
339
+ tile_size: Tile size to use.
340
+ """
341
+ self.slides = slides
342
+ self.tile_size = tile_size
343
+
344
+ for s in self.slides:
345
+ s.set_mode("random")
346
+ s.set_tile_size(tile_size)
347
+
348
+ self.iterators = {}
349
+ self.slide_keys = self.slides.keys()
350
+ self.slide_keys_copy = []
351
+
352
+ def __next__(self) -> tuple[Tile, dict[str, int | str]]:
353
+
354
+ while True:
355
+
356
+ if len(self.slide_keys_copy) == 0:
357
+
358
+ if len(self.slide_keys) == 0:
359
+ raise StopIteration
360
+
361
+ self.slide_keys_copy = self.slide_keys.copy()
362
+ random.shuffle(self.slide_keys_copy)
363
+
364
+ slide_key = self.slide_keys_copy.pop(0)
365
+ s = self.slides[slide_key]
366
+ if s.identifier not in self.iterators:
367
+ self.iterators[s.identifier] = iter(s)
368
+
369
+ try:
370
+ tile, metadata = next(self.iterators[s.identifier])
371
+ metadata["identifier"] = s.identifier
372
+ return tile, metadata
373
+ except StopIteration as si:
374
+ self.slide_keys.remove(slide_key)
375
+
376
+ class SlideImageCollection:
377
+
378
+ def __init__(self, identifier: str, tile_size: int = 512, mode: str = "random", custom_iter_locs: list[dict[str, str | int]] | None = None):
379
+ """A wrapper to collect multiple SlideImages together.
380
+
381
+ Args:
382
+ identifier: A str to identify this collection.
383
+ tile_size: The tile size to use.
384
+ mode: Sampling mode. Either "random" or "custom".
385
+ custom_iter_locs: If mode is "custom", then you should set custom_iter_locs. This should be a list of tile locations to visit in their preferred order. Each item is a dictionary with keys "identifier", "y", "x", "h", and "w" and values specifying the tile location.
386
+ """
387
+ self.identifier = identifier
388
+ self.tile_size = tile_size
389
+
390
+ self.slides = {}
391
+ self.set_mode(mode)
392
+ self.set_custom_iter_locs(custom_iter_locs)
393
+
394
+ def append(self, path: str, identifier: str | None = None):
395
+ """Append an image to this collection.
396
+
397
+ Args:
398
+ path: The file path to the image.
399
+ identifier: An identifer for the image. If None, the identifier is taken from the filename.
400
+ """
401
+ slide = SlideImage(path, identifier=identifier, tile_size=self.tile_size)
402
+ identifier = slide.identifier
403
+ self.slides[identifier] = slide
404
+
405
+ def __repr__(self):
406
+ return f"SlideImageCollection(\n \
407
+ identifier={self.identifier}\n \
408
+ tile_size={self.tile_size}\n \
409
+ slides={self.slides}\n)"
410
+
411
+ def set_mode(self, mode: str):
412
+ """Set the sampling mode.
413
+
414
+ Args:
415
+ mode: Either "random" or "custom".
416
+ """
417
+ if mode not in ["random", "custom"]:
418
+ raise Exception(f"{mode} is not a valid mode.")
419
+ self.mode = mode
420
+
421
+ def get_tile(self, y: int, x: int, h: int, w: int, identifier: str) -> Tile:
422
+ """Get tile.
423
+
424
+ Args:
425
+ identifier: The ID (filename without extension) of the image to get the tile from.
426
+ y: int y-coordinate of the upper left corner.
427
+ x: int x-coordinate of the upper left corner.
428
+ h: int height of the tile.
429
+ w: int width of the tile.
430
+
431
+ Returns:
432
+ The requested Tile.
433
+ """
434
+ return self.slides[identifier].get_tile(y, x, h, w)
435
+
436
+ def get_tile_using_dict(self, metadata: dict[str, int | str]) -> Tile:
437
+ """Get tile using a metadata dictionary.
438
+
439
+ Args:
440
+ metadata: A dictionary with "identifier", "y", "x", "h", "w" entries for fully specifying the location of the tile to retrieve.
441
+
442
+ Returns:
443
+ The requested Tile.
444
+ """
445
+ y, x, h, w, identifier = metadata["y"], metadata["x"], metadata["h"], metadata["w"], metadata["identifier"]
446
+ return self.get_tile(y, x, h, w, identifier)
447
+
448
+ def set_custom_iter_locs(self, custom_iter_locs: list[dict[str, str | int]] | None):
449
+ """Set custom tile locations for iteration.
450
+
451
+ Each tile location is a dictionary with these key/value pairs:
452
+ * "identifier": The ID (filename without extension) of the image to get the tile from.
453
+ * "y": int y-coordinate of the upper left corner.
454
+ * "x": int x-coordinate of the upper left corner.
455
+ * "h": int height of the tile.
456
+ * "w": int width of the tile.
457
+
458
+ Args:
459
+ custom_iter_locs: A list of tile locations (in their desired order), with each location being a dictionary.
460
+ """
461
+ self.custom_iter_locs = custom_iter_locs
462
+
463
+ def set_tile_size(self, tile_size: int):
464
+ """Set tile size.
465
+
466
+ Args:
467
+ tile_size: Tile size to use.
468
+ """
469
+ self.tile_size = tile_size
470
+
471
+ def __len__(self) -> int:
472
+ """Number of slides in this collection.
473
+
474
+ Returns:
475
+ The number of slides in this collection.
476
+ """
477
+ return len(self.slides)
478
+
479
+ def __iter__(self):
480
+ if self.mode == "random":
481
+ return RandomSlideImageCollectionIterator(self.slides, self.tile_size)
482
+ elif self.mode == "custom":
483
+ if self.custom_iter_locs is not None:
484
+ return CustomSlideImageCollectionIterator(self.slides, self.custom_iter_locs)
485
+ else:
486
+ raise Exception("custom_iter_locs must be set to perform custom iteration over this SlideImageCollection.")
487
+
488
+ class SlideImage:
489
+
490
+ def __init__(
491
+ self,
492
+ path: str,
493
+ identifier: str | None = None,
494
+ tile_size: int = 512,
495
+ mode: str = "sequential",
496
+ custom_iter_locs: list[dict[str, int] | tuple[int, int, int, int]] | None = None,
497
+ adjustment: Adjustment | None = None
498
+ ):
499
+ """A wrapper for a whole slide image. Manages reading different file types by choosing an appropriate reader based on the file extension.
500
+
501
+ Args:
502
+ path: A file path to the whole slide image.
503
+ identifier: A str identifier for the image. If None, the identifier is taken from the filename.
504
+ tile_size: Tile size to use.
505
+ mode: Sampling mode ("sequential", "random", or "custom").
506
+ custom_iter_locs: If "custom" mode is used, specify a list of tile locations to visit. It should be a list of tile locations to visit in their preferred order. Each item is a dictionary with keys "y", "x", "h", and "w" and values as ints specifying the tile location. Each item can also be a tuple of the ints in y, x, h, w order.
507
+ adjustment: An Adjustment to apply to the image.
508
+ """
509
+ self.path = path
510
+ self.slide, self.reader = self._guess_reader(path)
511
+ self.tile_size = tile_size
512
+ self.set_mode(mode)
513
+
514
+ if identifier is None:
515
+ self.identifier, _ = is_valid_extension(path, split=True, reader=self.reader)
516
+ else:
517
+ self.identifier = identifier
518
+
519
+ self.set_adjustment(adjustment)
520
+
521
+ if custom_iter_locs is not None:
522
+ if mode != "custom":
523
+ raise Exception("If custom_iter_locs is set, the mode should be set to \"custom\"")
524
+ self.set_custom_iter_locs(custom_iter_locs)
525
+
526
+ # Thumbnail cache
527
+ self.thumbnail = None
528
+ self.thumbnail_mask = None
529
+ self.thumbnail_params = {}
530
+
531
+ def pickleable(self):
532
+ """Make this object pickleable by setting the slide reference to None.
533
+
534
+ You can undo this operation by calling load_slide.
535
+ """
536
+ self.slide = None
537
+
538
+ def load_slide(self):
539
+ """Load the slide back again after calling pickleable.
540
+ """
541
+ self.slide, self.reader = self._guess_reader(self.path)
542
+
543
+ def compute_random_sequence(self) -> list[tuple[int, int, int, int]]:
544
+ """Compute a random tile location sequence.
545
+
546
+ Calling this function automatically sets the sampling mode of this slide to "custom" and its custom_iter_locs to the computed random sequence.
547
+
548
+ Returns:
549
+ A list of tuples, each consisting of y, x, tile_h, tile_w ints for the tile location.
550
+ """
551
+ h, w = self.slide.shape
552
+ coords = []
553
+ for y in range(0, h, self.tile_size):
554
+ for x in range(0, w, self.tile_size):
555
+ tile_h = self.tile_size
556
+ tile_w = self.tile_size
557
+ if y + self.tile_size > h:
558
+ tile_h = h - y
559
+ if x + self.tile_size > w:
560
+ tile_w = w - x
561
+ coords.append((y, x, tile_h, tile_w))
562
+
563
+ random.shuffle(coords)
564
+
565
+ self.set_mode("custom")
566
+ self.custom_iter_locs = coords
567
+ return coords
568
+
569
+ def __repr__(self):
570
+ return f"SlideImage(identifier={self.identifier}, h={self.slide.shape[0]}, w={self.slide.shape[1]})"
571
+
572
+ def purge(self):
573
+ """Set thumbnail cache variables to None or default values to release memory.
574
+ """
575
+ self.thumbnail = None
576
+ self.thumbnail_params = {}
577
+ self.thumbnail_mask = None
578
+
579
+ @property
580
+ def shape(self):
581
+ """Get the shape of the image.
582
+
583
+ Returns:
584
+ Provides the shape (in pixels) of the image as (H,W).
585
+ """
586
+ return self.slide.shape
587
+
588
+ @property
589
+ def resolution(self):
590
+ """Get the resolution of the image.
591
+
592
+ Returns:
593
+ Provides the resolution (in microns per pixel) of the image as [x resolution, y resolution]. May be [None, None] if the resolution is not known.
594
+ """
595
+ return self.slide.resolution
596
+
597
+ def set_mode(self, mode: str):
598
+ """Set the sampling mode.
599
+
600
+ Args:
601
+ mode: "sequential" for row major order, "random" for random selection from a grid, "custom" for a custom order specified using set_custom_iter_locs.
602
+ """
603
+ if mode not in ["sequential", "random", "custom"]:
604
+ raise Exception(f"{mode} is not a valid mode.")
605
+ self.mode = mode
606
+
607
+ def set_tile_size(self, tile_size: int):
608
+ """Set the tile size.
609
+
610
+ Args:
611
+ tile_size: The tile size to set.
612
+ """
613
+ self.tile_size = tile_size
614
+
615
+ def get_pyvips(self) -> pyvips.Image:
616
+ """Get the pyvips version of this image.
617
+
618
+ If an Adjustment has been set, the pyvips image will have the adjustment in its computational path.
619
+
620
+ Returns:
621
+ A pyvips.Image image.
622
+ """
623
+ image = pyvips.Image.new_from_file(self.path, access="sequential")
624
+ if self.adjustment is not None:
625
+ image = self.adjustment.apply(image)
626
+ return image
627
+ else:
628
+ return image
629
+
630
+ def get_thumbnail(self, height: int = 4096, width_max: int = 10_000, smooth: bool = True) -> np.ndarray:
631
+ """Get the thumbnail of the whole slide image using Pyvips.
632
+
633
+ Args:
634
+ height: The maximum height of the thumbnail.
635
+ width_max: The maximum width of the thumbnail.
636
+ smooth: Allow the use of interpolation that smooths pixels.
637
+
638
+ Returns:
639
+ A np.ndarray of a thumbnail of the slide image.
640
+ """
641
+ if self.thumbnail is not None and self.thumbnail_params["height"] == height and self.thumbnail_params["width_max"] == width_max and self.thumbnail_params["smooth"] == smooth:
642
+ return self.thumbnail
643
+
644
+ self.thumbnail_params = {"height": height, "width_max": width_max, "smooth": smooth}
645
+ self.thumbnail_mask = None
646
+
647
+ if height > self.slide.shape[0]:
648
+ height = self.slide.shape[0]
649
+
650
+ # Estimate the output width
651
+ scale = height / self.slide.shape[0]
652
+ width = self.slide.shape[1] * scale
653
+ if width > width_max:
654
+ width = width_max
655
+ scale = width / self.slide.shape[1]
656
+ height = round(self.slide.shape[0] * scale)
657
+
658
+ if smooth:
659
+ self.thumbnail = pyvips.Image.thumbnail(self.path, height).numpy()
660
+ else:
661
+ self.thumbnail = self.get_pyvips().resize(scale, kernel="nearest").numpy()
662
+
663
+ self.thumbnail = self.thumbnail[:,:,:3]
664
+ if self.adjustment is not None:
665
+ self.thumbnail = self.adjustment.apply(self.thumbnail)
666
+
667
+ return self.thumbnail
668
+
669
+ def get_thumbnail_mask(self, filter_fn: Callable[[np.ndarray], np.ndarray]) -> np.ndarray:
670
+ """Get a foreground mask of the thumbnail.
671
+
672
+ Args:
673
+ filter_fn: A function for thresholding the thumbnail and outputs a mask.
674
+
675
+ Returns:
676
+ A np.ndarray for the foreground mask (True = foreground).
677
+ """
678
+ if self.thumbnail_mask is not None and self.thumbnail_params["filter_fn"] == filter_fn:
679
+ return self.thumbnail_mask
680
+
681
+ thumbnail = self.get_thumbnail()
682
+ thumbnail = Tile(thumbnail)
683
+ self.thumbnail_mask = filter_fn(thumbnail)
684
+
685
+ self.thumbnail_params["filter_fn"] = filter_fn
686
+ return self.thumbnail_mask
687
+
688
+ def set_adjustment(self, adjustment: Adjustment | None):
689
+ """Set a pre-adjustment on the image (or set back to None).
690
+
691
+ Args:
692
+ adjustment: The Adjustment to set.
693
+ """
694
+ self.adjustment = adjustment
695
+ self.slide.set_adjustment(adjustment)
696
+
697
+ def set_custom_iter_locs(self, custom_iter_locs: list[dict[str, int] | tuple[int]] | None):
698
+ """Set the custom tile locations to visit during iteration.
699
+
700
+ This automatically sets the mode to "custom".
701
+
702
+ Args:
703
+ custom_iter_locs: List of tile locations to visit. It should be a list of tile locations to visit in their preferred order. Each item is a dictionary with keys "y", "x", "h", and "w" and values as ints specifying the tile location. Each item can also be a tuple of the ints in y, x, h, w order.
704
+ """
705
+ self.set_mode("custom")
706
+ self.custom_iter_locs = custom_iter_locs
707
+
708
+ def __len__(self) -> int:
709
+ """Number of tiles.
710
+
711
+ Returns:
712
+ The number of tiles.
713
+ """
714
+ return int(math.ceil(self.slide.shape[0] / self.tile_size) * math.ceil(self.slide.shape[1] / self.tile_size))
715
+
716
+ def __iter__(self):
717
+ if self.mode == "sequential":
718
+ return SequentialSlideImageIterator(self.slide, self.tile_size)
719
+ elif self.mode == "random":
720
+ return RandomSlideImageIterator(self.slide, self.tile_size)
721
+ elif self.mode == "custom":
722
+ if self.custom_iter_locs is None:
723
+ raise Exception("Mode set to custom. Call set_custom_iter_locs first to specify the custom tile order.")
724
+ return CustomSlideImageIterator(self.slide, self.custom_iter_locs)
725
+
726
+ def _guess_reader(self, path: str) -> tuple[Any, str]:
727
+ """Lazy load the image by guessing which package will work.
728
+
729
+ Args:
730
+ path: The file path to the whole slide image.
731
+
732
+ Returns:
733
+ The whole slide image object and str for the reader used.
734
+ """
735
+ if not os.path.exists(path):
736
+ raise Exception(f"{path} does not exist")
737
+
738
+ try:
739
+ if not is_valid_extension(path, reader="openslide"):
740
+ raise Exception
741
+ slide = OpenSlideImage(path)
742
+ return slide, "openslide"
743
+ except Exception:
744
+ pass
745
+
746
+ try:
747
+ if not is_valid_extension(path, reader="tifffile"):
748
+ raise Exception
749
+ slide = TifffileZarrImage(path)
750
+ return slide, "tifffile"
751
+ except Exception:
752
+ pass
753
+
754
+ try:
755
+ if not is_valid_extension(path, reader="bioformats"):
756
+ raise Exception
757
+ slide = BioformatsImage(path)
758
+ return slide, "bioformats"
759
+ except Exception:
760
+ pass
761
+
762
+ raise Exception(f"Tried all available slide readers on {path} but was unsuccessful. Convert your image into a format compatible with OpenSlide, tifffile, or bioio-bioformats.")
763
+
764
+ def get_tile(self, y: int, x: int, h: int, w: int) -> Tile:
765
+ """Get tile.
766
+
767
+ Args:
768
+ y: int y-coordinate of the upper left corner.
769
+ x: int x-coordinate of the upper left corner.
770
+ h: int height of the tile.
771
+ w: int width of the tile.
772
+
773
+ Returns:
774
+ The requested Tile.
775
+ """
776
+ tile = self.slide.get_tile(y, x, h, w)
777
+ if self.adjustment is not None:
778
+ tile = self.adjustment.apply(tile)
779
+ return tile
780
+
781
+ def get_tile_using_dict(self, metadata: dict[str, int]) -> Tile:
782
+ """Get tile using a metadata dictionary.
783
+
784
+ Args:
785
+ metadata: A dictionary with "y", "x", "h", "w" entries for fully specifying the location of the tile to retrieve.
786
+
787
+ Returns:
788
+ The requested Tile.
789
+ """
790
+ y, x, h, w = metadata["y"], metadata["x"], metadata["h"], metadata["w"]
791
+ return self.get_tile(y, x, h, w)
792
+
793
+ def write_thumbnail(self, output_path: str, height: int = 4096):
794
+ """Write a thumbnail of this image to disk.
795
+
796
+ Args:
797
+ output_path: The path to output the thumbnail.
798
+ height: The maximum height of the thumbnail.
799
+ """
800
+ if os.path.exists(output_path):
801
+ raise Exception(f"{output_path} already exists.")
802
+ thumbnail = self.get_thumbnail(height=height)
803
+ thumbnail_pil = Image.fromarray(thumbnail)
804
+ thumbnail_pil.save(output_path)
805
+
806
+ def filter_coords_using_thumbnail(self, filter_fn: Callable[[np.ndarray], np.ndarray], coords: list[tuple[int, int, int, int]], tolerance: float = 0.05, purge_thumbnails_after: bool = True) -> list[tuple[int, int, int, int]]:
807
+ """Detect the tissue in the thumbnail of the slide image. From this detection, accept only tile locations that have tissue in it and remove locations that don't have tissue in it.
808
+
809
+ When this function is called, the filtered coordinates will be set as the custom_iter_locs and the sampling mode of the slide will change to "custom".
810
+
811
+ Args:
812
+ filter_fn: A function to threshold the thumbnail, outputting a foreground mask.
813
+ coords: A list of tile coordinates to filter. Each tuple should be y, x, tile height, tile width.
814
+ tolerance: Min percent of the tile that must have tissue to be accepted [0.0,1.0].
815
+ purge_thumbnails_after: If True, thumbnail cache will be dereferenced to avoid using too much RAM.
816
+
817
+ Returns:
818
+ A list of tuples (each tuple consisting of y, x, tile height, tile width) of filtered tile locations.
819
+ """
820
+ print(f"Filtering given coordinates using thumbnail...")
821
+
822
+ thumbnail_mask = self.get_thumbnail_mask(filter_fn)
823
+ thumb_h, thumb_w = thumbnail_mask.shape
824
+ real_h, real_w = self.shape
825
+ scale = thumb_h / real_h
826
+ if not math.isclose(scale, thumb_w / real_w, rel_tol=10, abs_tol=0.1):
827
+ raise Exception(f"Thumbnail expected to be scaled equally in both dimensions. Y scale = {scale}, X scale = {thumb_w / real_w}")
828
+
829
+ filtered_coords = []
830
+
831
+ for y, x, tile_h, tile_w in coords:
832
+ thumb_y = round(y * scale)
833
+ thumb_x = round(x * scale)
834
+ thumb_tile_h = round(tile_h * scale)
835
+ thumb_tile_w = round(tile_w * scale)
836
+ px_tolerance = min(round(tolerance * thumb_tile_h * thumb_tile_w), 1)
837
+
838
+ tile_mask = thumbnail_mask[thumb_y:thumb_y+thumb_tile_h, thumb_x:thumb_x+thumb_tile_w]
839
+ if np.sum(tile_mask) >= px_tolerance:
840
+ filtered_coords.append((y, x, tile_h, tile_w))
841
+
842
+ print(f"Tiles before filtering = {len(coords)}, Tiles after filtering = {len(filtered_coords)}")
843
+
844
+ if purge_thumbnails_after:
845
+ self.purge()
846
+ self.set_mode("custom")
847
+ self.set_custom_iter_locs(filtered_coords)
848
+ return filtered_coords
849
+
850
+ class OpenSlideImage:
851
+
852
+ def __init__(self, path: str):
853
+ """Wrapper for an OpenSlide image.
854
+
855
+ Args:
856
+ path: File path of the image.
857
+ """
858
+ self.data = openslide.OpenSlide(path)
859
+ self.shape = self.data.dimensions[::-1] # (width, height) -> (height, width)
860
+ self.level = 0
861
+ self.adjustment = None
862
+ self.resolution = self._guess_resolution()
863
+
864
+ def _guess_resolution(self) -> list[float]:
865
+ """Guess the microns per pixel resolution of the image based on the metadata.
866
+
867
+ Returns:
868
+ A list with two floats [mpp_x, mpp_y] for the microns per pixel in the x and y directions.
869
+ """
870
+ mpp_x = None
871
+ mpp_y = None
872
+ if "openslide.mpp-x" in self.data.properties and "openslide.mpp-y" in self.data.properties:
873
+ mpp_x = float(self.data.properties["openslide.mpp-x"])
874
+ mpp_y = float(self.data.properties["openslide.mpp-y"])
875
+ return [mpp_x, mpp_y]
876
+
877
+ def get_tile(self, y: int, x: int, height: int, width: int) -> Tile:
878
+ """Get tile.
879
+
880
+ Args:
881
+ y: int y-coordinate of the upper left corner.
882
+ x: int x-coordinate of the upper left corner.
883
+ height: int height of the tile.
884
+ width: int width of the tile.
885
+
886
+ Returns:
887
+ The requested Tile.
888
+ """
889
+ tile = self.data.read_region((x, y), self.level, (width, height))
890
+ tile = np.array(tile)[:,:,:3]
891
+ tile = Tile(tile, adjustment=self.adjustment)
892
+ return tile
893
+
894
+ def set_adjustment(self, adjustment: Adjustment | None):
895
+ """Set a pre-adjustment.
896
+
897
+ Args:
898
+ adjustment: The Adjustment to set.
899
+ """
900
+ self.adjustment = adjustment
901
+
902
+ class TifffileZarrImage:
903
+
904
+ def __init__(self, path: str):
905
+ """Wrapper for a tifffile/zarr image.
906
+
907
+ Args:
908
+ path: File path of the image.
909
+ """
910
+ store = tifffile.imread(path, aszarr=True)
911
+ self.data = zarr.open(store, mode='r')
912
+ if self.data.shape[0] == 3:
913
+ self.color_dim = 0
914
+ elif self.data.shape[-1] == 3:
915
+ self.color_dim = -1
916
+ else:
917
+ raise Exception("Could not find the color dimension.")
918
+ self.shape = self.data.shape[1:] if self.color_dim == 0 else self.data.shape[:-1]
919
+ self.adjustment = None
920
+ self.resolution = [None, None]
921
+
922
+ def get_tile(self, y: int, x: int, height: int, width: int) -> Tile:
923
+ """Get tile.
924
+
925
+ Args:
926
+ y: int y-coordinate of the upper left corner.
927
+ x: int x-coordinate of the upper left corner.
928
+ height: int height of the tile.
929
+ width: int width of the tile.
930
+
931
+ Returns:
932
+ The requested Tile.
933
+ """
934
+ if self.color_dim == 0:
935
+ tile = self.data[:, y:y+height, x:x+width]
936
+ else:
937
+ tile = self.data[y:y+height, x:x+width, :]
938
+ tile = Tile(tile, adjustment=self.adjustment)
939
+ return tile
940
+
941
+ def set_adjustment(self, adjustment: Adjustment | None):
942
+ """Set a pre-adjustment.
943
+
944
+ Args:
945
+ adjustment: The Adjustment to set.
946
+ """
947
+ self.adjustment = adjustment
948
+
949
+ class BioformatsImage:
950
+
951
+ def __init__(self, path: str):
952
+ """Wrapper for a Bioformats image.
953
+
954
+ Args:
955
+ path: File path of the image.
956
+ """
957
+ store = BioImage(path, reader=bioio_bioformats.Reader)
958
+
959
+ if len(store.scenes) > 1:
960
+ max_y = 0
961
+ best_scene = 0
962
+ for i in range(len(store.scenes)):
963
+ store.set_scene(i)
964
+ if store.dims.Y > max_y:
965
+ max_y = store.dims.Y
966
+ best_scene = i
967
+ store.set_scene(best_scene)
968
+
969
+ if store.dims.T > 1:
970
+ raise Exception("Expected the T dimension of this image to be 1. Images with a T dimension are not supported yet.")
971
+ if store.dims.Z > 1:
972
+ raise Exception("Expected the Z dimension of this image to be 1. Images with a Z dimension are not supported yet.")
973
+
974
+ if store.dims.C == 3:
975
+ self.data = store.get_image_dask_data("YXC")
976
+ elif store.dims.S == 3:
977
+ self.data = store.get_image_dask_data("YXS")
978
+ else:
979
+ raise Exception("Cannot find the color dimension in this image.")
980
+
981
+ self.shape = self.data.shape[:2]
982
+ self.adjustment = None
983
+ self.resolution = [None, None]
984
+
985
+ print("WARNING: Using Bioformats to read the image. We do not support parallel compute with this reader yet.")
986
+
987
+ def get_tile(self, y: int, x: int, height: int, width: int) -> Tile:
988
+ """Get tile.
989
+
990
+ Args:
991
+ y: int y-coordinate of the upper left corner.
992
+ x: int x-coordinate of the upper left corner.
993
+ height: int height of the tile.
994
+ width: int width of the tile.
995
+
996
+ Returns:
997
+ The requested Tile.
998
+ """
999
+ tile = np.array(self.data[y:y+height, x:x+width, :])
1000
+ tile = Tile(tile, adjustment=self.adjustment)
1001
+ return tile
1002
+
1003
+ def set_adjustment(self, adjustment: Adjustment | None):
1004
+ """Set a pre-adjustment.
1005
+
1006
+ Args:
1007
+ adjustment: The Adjustment to set.
1008
+ """
1009
+ self.adjustment = adjustment
1010
+
1011
+ openslide_valid_extensions = [
1012
+ ".svs",
1013
+ ".avs",
1014
+ ".dcm",
1015
+ ".vms", ".vmu", ".ndpi",
1016
+ ".tif", ".tiff",
1017
+ ".scn",
1018
+ ".mrxs",
1019
+ ".svslide",
1020
+ ".bif",
1021
+ ".czi",
1022
+ ]
1023
+
1024
+ tifffile_valid_extensions = [
1025
+ ".ome.tiff", ".ome.tif", ".tif", ".tiff",
1026
+ ]
1027
+
1028
+ bioformats_valid_extensions = [
1029
+ ".vsi",
1030
+ ]
1031
+
1032
+ two_part_extensions = [
1033
+ "ome", "nii",
1034
+ ]
1035
+
1036
+ def is_valid_extension(path: str, split: bool = False, reader: str | None = None) -> bool | tuple[str, str]:
1037
+ """Check if the path is a valid whole slide image based on its extension.
1038
+
1039
+ Args:
1040
+ path: The file path to the whole slide image.
1041
+ split: If True, the filename without extension and the extension will be returned. If False, the function just returns a bool if the path is a valid whole slide image.
1042
+ reader: If None, the path is checked against all available readers. Otherwise, the path is checked against only the reader specified ("tifffile", "openslide", "bioformats").
1043
+
1044
+ Returns:
1045
+ Either a bool (if split is False) indicating if the path is a valid whole slide image that can be read or two strings corresponding to the filename without extension and the extension if it is valid.
1046
+ """
1047
+ filename = os.path.basename(path)
1048
+
1049
+ valid_extensions = []
1050
+ if reader == "tifffile" or reader is None:
1051
+ valid_extensions.extend(tifffile_valid_extensions)
1052
+ if reader == "openslide" or reader is None:
1053
+ valid_extensions.extend(openslide_valid_extensions)
1054
+ if reader == "bioformats" or reader is None:
1055
+ # A full listing of what bioformats can load is at bioio_bioformats.reader_metadata.ReaderMetadata.get_supported_extensions()
1056
+ # We restrict the valid formats using bioformats_valid_extensions since there are some formats (e.g., .txt) that don't make sense for our use.
1057
+ valid_extensions.extend(bioformats_valid_extensions)
1058
+
1059
+ filename_wo_ext, filename_ext = split_filename(filename)
1060
+
1061
+ for ext in valid_extensions:
1062
+ if filename_ext.lower() == ext:
1063
+ if split:
1064
+ return filename_wo_ext, filename_ext
1065
+ return True
1066
+ return False
1067
+
1068
+ def split_filename(filename: str) -> tuple[str, str]:
1069
+ """Helper function to split a filename into its name without extension and extension.
1070
+
1071
+ Args:
1072
+ filename: The filename to split.
1073
+
1074
+ Returns:
1075
+ The filename without extension and the extension.
1076
+ """
1077
+
1078
+ parts = filename.split(".")
1079
+
1080
+ if len(parts) >= 3:
1081
+ for ext in two_part_extensions:
1082
+ if parts[-2].lower() == ext:
1083
+ return ".".join(parts[:-2]), "." + ".".join(parts[-2:])
1084
+
1085
+ return ".".join(parts[:-1]), "." + parts[-1]