-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
tiler.py
480 lines (389 loc) · 15.1 KB
/
tiler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
from abc import abstractmethod
from typing import Tuple
import numpy as np
from histolab.exceptions import LevelError
from .slide import Slide
from .tile import Tile
from .types import CoordinatePair
from .util import (
lru_cache,
region_coordinates,
regions_from_binary_mask,
scale_coordinates,
)
try:
from typing import Protocol, runtime_checkable
except ImportError:
from typing_extensions import Protocol, runtime_checkable
@runtime_checkable
class Tiler(Protocol):
level: int
tile_size: int
@lru_cache(maxsize=100)
def box_mask_thumb(self, slide: Slide) -> np.ndarray:
"""Return binary mask, at thumbnail level, of the box for tiles extraction.
The mask pixels set to True correspond to the tissue box.
Parameters
----------
slide : Slide
The Slide from which to extract the extraction mask
Returns
-------
np.ndarray
Extraction mask at thumbnail level
"""
return slide.biggest_tissue_box_mask
def _tile_filename(
self, tile_wsi_coords: CoordinatePair, tiles_counter: int
) -> str:
"""Return the tile filename according to its 0-level coordinates and a counter.
Parameters
----------
tile_wsi_coords : CoordinatePair
0-level coordinates of the slide the tile has been extracted from.
tiles_counter : int
Counter of extracted tiles.
Returns
-------
str
Tile filename, according to the format
`{prefix}tile_{tiles_counter}_level{level}_{x_ul_wsi}-{y_ul_wsi}-{x_br_wsi}"
"-{y_br_wsi}{suffix}`
"""
x_ul_wsi, y_ul_wsi, x_br_wsi, y_br_wsi = tile_wsi_coords
tile_filename = (
f"{self.prefix}tile_{tiles_counter}_level{self.level}_{x_ul_wsi}-{y_ul_wsi}"
f"-{x_br_wsi}-{y_br_wsi}{self.suffix}"
)
return tile_filename
@abstractmethod
def extract(self, slide: Slide):
raise NotImplementedError
class GridTiler(Tiler):
"""Extractor of tiles arranged in a grid, at the given level, with the given size.
Arguments
---------
tile_size : Tuple[int, int]
(width, height) of the extracted tiles.
level : int, optional
Level from which extract the tiles. Default is 0.
check_tissue : bool, optional
Whether to check if the tile has enough tissue to be saved. Default is True.
pixel_overlap : int, optional
Number of overlapping pixels (for both height and width) between two adjacent
tiles. If negative, two adjacent tiles will be strided by the absolute value of
``pixel_overlap``. Default is 0.
prefix : str, optional
Prefix to be added to the tile filename. Default is an empty string.
suffix : str, optional
Suffix to be added to the tile filename. Default is '.png'
"""
def __init__(
self,
tile_size: Tuple[int, int],
level: int = 0,
check_tissue: bool = True,
pixel_overlap: int = 0,
prefix: str = "",
suffix: str = ".png",
):
self.tile_size = tile_size
self.level = level
self.check_tissue = check_tissue
self.pixel_overlap = pixel_overlap
self.prefix = prefix
self.suffix = suffix
@property
def tile_size(self) -> Tuple[int, int]:
return self._valid_tile_size
@tile_size.setter
def tile_size(self, tile_size_: Tuple[int, int]):
if tile_size_[0] < 1 or tile_size_[1] < 1:
raise ValueError(f"Tile size must be greater than 0 ({tile_size_})")
self._valid_tile_size = tile_size_
@property
def level(self) -> int:
return self._valid_level
@level.setter
def level(self, level_: int):
if level_ < 0:
raise LevelError(f"Level cannot be negative ({level_})")
self._valid_level = level_
def extract(self, slide: Slide):
"""Extract tiles arranged in a grid and save them to disk, following this
filename pattern:
`{prefix}tile_{tiles_counter}_level{level}_{x_ul_wsi}-{y_ul_wsi}-{x_br_wsi}-{y_br_wsi}{suffix}`
Parameters
----------
slide : Slide
Slide from which to extract the tiles
"""
if self.level not in slide.levels:
raise LevelError(
f"Level {self.level} not available. Number of available levels: "
f"{len(slide.levels)}"
)
grid_tiles = self._grid_tiles_generator(slide)
tiles_counter = 0
for tiles_counter, (tile, tile_wsi_coords) in enumerate(grid_tiles):
tile_filename = self._tile_filename(tile_wsi_coords, tiles_counter)
tile.save(tile_filename)
print(f"\t Tile {tiles_counter} saved: {tile_filename}")
print(f"{tiles_counter} Grid Tiles have been saved.")
def _grid_coordinates_from_bbox_coordinates(
self, bbox_coordinates: CoordinatePair, slide: Slide
) -> CoordinatePair:
"""Generate Coordinates at level 0 of grid tiles within a tissue box.
Parameters
----------
bbox_coordinates: CoordinatePair
Coordinates of the tissue box from which to calculate the coordinates.
slide : Slide
Slide from which to calculate the coordinates.
Yields
-------
Iterator[CoordinatePair]
Iterator of tiles' CoordinatePair
"""
tile_w_lvl, tile_h_lvl = self.tile_size
n_tiles_row = self._n_tiles_row(bbox_coordinates)
n_tiles_column = self._n_tiles_column(bbox_coordinates)
x_ul_lvl_offset = bbox_coordinates.x_ul
y_ul_lvl_offset = bbox_coordinates.y_ul
for i in range(n_tiles_row):
for j in range(n_tiles_column):
x_ul_lvl = x_ul_lvl_offset + tile_w_lvl * j - self.pixel_overlap
y_ul_lvl = y_ul_lvl_offset + tile_h_lvl * i - self.pixel_overlap
x_ul_lvl = np.clip(x_ul_lvl, x_ul_lvl_offset, None)
y_ul_lvl = np.clip(y_ul_lvl, y_ul_lvl_offset, None)
x_br_lvl = x_ul_lvl + tile_w_lvl
y_br_lvl = y_ul_lvl + tile_h_lvl
tile_wsi_coords = scale_coordinates(
reference_coords=CoordinatePair(
x_ul_lvl, y_ul_lvl, x_br_lvl, y_br_lvl
),
reference_size=slide.level_dimensions(level=self.level),
target_size=slide.level_dimensions(level=0),
)
yield tile_wsi_coords
def _grid_coordinates_generator(self, slide: Slide) -> CoordinatePair:
"""Generate Coordinates at level 0 of grid tiles within the tissue.
Parameters
----------
slide : Slide
Slide from which to calculate the coordinates. Needed to calculate the
tissue area.
Yields
-------
Iterator[CoordinatePair]
Iterator of tiles' CoordinatePair
"""
box_mask_thumb = self.box_mask_thumb(slide)
regions = regions_from_binary_mask(box_mask_thumb)
for region in regions: # at the moment there is only one region
bbox_coordinates_thumb = region_coordinates(region)
bbox_coordinates = scale_coordinates(
bbox_coordinates_thumb,
box_mask_thumb.shape[::-1],
slide.level_dimensions(self.level),
)
yield from self._grid_coordinates_from_bbox_coordinates(
bbox_coordinates, slide
)
def _grid_tiles_generator(self, slide: Slide) -> Tuple[Tile, CoordinatePair]:
"""Generator of tiles arranged in a grid.
Parameters
----------
slide : Slide
Slide from which to extract the tiles
Yields
-------
Tile
Extracted tile
CoordinatePair
Coordinates of the slide at level 0 from which the tile has been extracted
"""
grid_coordinates_generator = self._grid_coordinates_generator(slide)
for coords in grid_coordinates_generator:
try:
tile = slide.extract_tile(coords, self.level)
except ValueError:
continue
if not self.check_tissue or tile.has_enough_tissue():
yield tile, coords
def _n_tiles_column(self, bbox_coordinates: CoordinatePair) -> int:
"""Return the number of tiles which can be extracted in a column.
Parameters
----------
bbox_coordinates : CoordinatePair
Coordinates of the tissue box
Returns
-------
int
Number of tiles which can be extracted in a column.
"""
return (bbox_coordinates.y_br - bbox_coordinates.y_ul) // (
self.tile_size[1] - self.pixel_overlap
)
def _n_tiles_row(self, bbox_coordinates: CoordinatePair) -> int:
"""Return the number of tiles which can be extracted in a row.
Parameters
----------
bbox_coordinates : CoordinatePair
Coordinates of the tissue box
Returns
-------
int
Number of tiles which can be extracted in a row.
"""
return (bbox_coordinates.x_br - bbox_coordinates.x_ul) // (
self.tile_size[0] - self.pixel_overlap
)
class RandomTiler(Tiler):
"""Extractor of random tiles from a Slide, at the given level, with the given size.
Arguments
---------
tile_size : Tuple[int, int]
(width, height) of the extracted tiles.
n_tiles : int
Maximum number of tiles to extract.
level : int, optional
Level from which extract the tiles. Default is 0.
seed : int, optional
Seed for RandomState. Must be convertible to 32 bit unsigned integers. Default
is 7.
check_tissue : bool, optional
Whether to check if the tile has enough tissue to be saved. Default is True.
prefix : str, optional
Prefix to be added to the tile filename. Default is an empty string.
suffix : str, optional
Suffix to be added to the tile filename. Default is '.png'
max_iter : int, optional
Maximum number of iterations performed when searching for eligible (if
``check_tissue=True``) tiles. Must be grater than or equal to ``n_tiles``.
"""
def __init__(
self,
tile_size: Tuple[int, int],
n_tiles: int,
level: int = 0,
seed: int = 7,
check_tissue: bool = True,
prefix: str = "",
suffix: str = ".png",
max_iter: int = 1e4,
):
super().__init__()
self.tile_size = tile_size
self.n_tiles = n_tiles
self.max_iter = max_iter
self.level = level
self.seed = seed
self.check_tissue = check_tissue
self.prefix = prefix
self.suffix = suffix
@property
def tile_size(self) -> Tuple[int, int]:
return self._valid_tile_size
@tile_size.setter
def tile_size(self, tile_size_: Tuple[int, int]):
if tile_size_[0] < 1 or tile_size_[1] < 1:
raise ValueError(f"Tile size must be greater than 0 ({tile_size_})")
self._valid_tile_size = tile_size_
@property
def level(self) -> int:
return self._valid_level
@level.setter
def level(self, level_: int):
if level_ < 0:
raise LevelError(f"Level cannot be negative ({level_})")
self._valid_level = level_
@property
def max_iter(self) -> int:
return self._valid_max_iter
@max_iter.setter
def max_iter(self, max_iter_: int = 1e4):
if max_iter_ < self.n_tiles:
raise ValueError(
f"The maximum number of iterations ({max_iter_}) must be grater than or "
f"equal to the maximum number of tiles ({self.n_tiles})."
)
self._valid_max_iter = max_iter_
def extract(self, slide: Slide):
"""Extract random tiles and save them to disk, following this filename pattern:
`{prefix}tile_{tiles_counter}_level{level}_{x_ul_wsi}-{y_ul_wsi}-{x_br_wsi}-{y_br_wsi}{suffix}`
Parameters
----------
slide : Slide
Slide from which to extract the tiles
"""
np.random.seed(self.seed)
random_tiles = self._random_tiles_generator(slide)
tiles_counter = 0
for tiles_counter, (tile, tile_wsi_coords) in enumerate(random_tiles):
tile_filename = self._tile_filename(tile_wsi_coords, tiles_counter)
tile.save(tile_filename)
print(f"\t Tile {tiles_counter} saved: {tile_filename}")
print(f"{tiles_counter+1} Random Tiles have been saved.")
def _random_tile_coordinates(self, slide: Slide) -> CoordinatePair:
"""Return 0-level Coordinates of a tile picked at random within the box.
Parameters
----------
slide : Slide
Slide from which calculate the coordinates. Needed to calculate the box.
Returns
-------
CoordinatePair
Random tile Coordinates at level 0
"""
box_mask_thumb = self.box_mask_thumb(slide)
tile_w_lvl, tile_h_lvl = self.tile_size
x_ul_lvl = np.random.choice(np.where(box_mask_thumb)[1])
y_ul_lvl = np.random.choice(np.where(box_mask_thumb)[0])
# Scale tile dimensions to thumbnail dimensions
tile_w_thumb = (
tile_w_lvl * box_mask_thumb.shape[1] / slide.level_dimensions(self.level)[0]
)
tile_h_thumn = (
tile_h_lvl * box_mask_thumb.shape[0] / slide.level_dimensions(self.level)[1]
)
x_br_lvl = x_ul_lvl + tile_w_thumb
y_br_lvl = y_ul_lvl + tile_h_thumn
tile_wsi_coords = scale_coordinates(
reference_coords=CoordinatePair(x_ul_lvl, y_ul_lvl, x_br_lvl, y_br_lvl),
reference_size=box_mask_thumb.shape[::-1],
target_size=slide.dimensions,
)
return tile_wsi_coords
def _random_tiles_generator(self, slide: Slide) -> Tuple[Tile, CoordinatePair]:
"""Generate Random Tiles within a slide box.
Stops if:
* the number of extracted tiles is equal to ``n_tiles`` OR
* the maximum number of iterations ``max_iter`` is reached
Parameters
----------
slide : Slide
The Whole Slide Image from which to extract the tiles.
Yields
------
tile : Tile
The extracted Tile
coords : CoordinatePair
The level-0 coordinates of the extracted tile
"""
iteration = valid_tile_counter = 0
while True:
tile_wsi_coords = self._random_tile_coordinates(slide)
try:
tile = slide.extract_tile(tile_wsi_coords, self.level)
except ValueError:
iteration -= 1
continue
if not self.check_tissue or tile.has_enough_tissue():
yield tile, tile_wsi_coords
valid_tile_counter += 1
iteration += 1
if self.max_iter and iteration >= self.max_iter:
break
if valid_tile_counter >= self.n_tiles:
break