-
Notifications
You must be signed in to change notification settings - Fork 5
/
group.py
457 lines (397 loc) · 14.1 KB
/
group.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
# Copyright 2021, 2022, 2023 SECTRA AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import defaultdict
from typing import Dict, Iterable, List, Optional, Set, Tuple
from PIL.Image import Image
from pydicom.uid import UID
from wsidicom.config import settings
from wsidicom.errors import (
WsiDicomMatchError,
WsiDicomNoResolutionError,
WsiDicomNotFoundError,
WsiDicomOutOfBoundsError,
)
from wsidicom.geometry import Point, Region, RegionMm, Size, SizeMm
from wsidicom.instance import (
ImageData,
ImageType,
WsiDataset,
WsiInstance,
)
from wsidicom.metadata import ImageCoordinateSystem
from wsidicom.stringprinting import dict_pretty_str
from wsidicom.uid import SlideUids
class Group:
"""Represents a group of instances having the same size, but possibly
different z coordinate and/or optical path."""
def __init__(self, instances: Iterable[WsiInstance]):
"""Create a group of WsiInstances. Instances should match in the common
uids, wsi type, and tile size.
Parameters
----------
instances: Sequence[WsiInstance]
Instances to build the group.
"""
self._instances = { # key is identifier (Uid)
instance.identifier: instance for instance in instances
}
self._validate_group()
base_instance = next(iter(self._instances.values()))
self._image_type = base_instance.image_type
self._uids = base_instance.uids
self._size = base_instance.size
self._pixel_spacing = base_instance.pixel_spacing
self._default_instance_uid: UID = base_instance.identifier
def __repr__(self) -> str:
return f"{type(self).__name__}({self.instances.values()})"
def __str__(self) -> str:
return self.pretty_str()
def pretty_str(self, indent: int = 0, depth: Optional[int] = None) -> str:
string = f"Image: size: {self.size} px, mpp: {self.mpp} um/px"
if depth is not None:
depth -= 1
if depth < 0:
return string
string += " Instances: " + dict_pretty_str(self.instances, indent, depth)
return string
def __getitem__(self, index: UID) -> WsiInstance:
return self.instances[index]
@property
def uids(self) -> SlideUids:
"""Return uids"""
return self._uids
@property
def image_type(self) -> ImageType:
"""Return wsi type"""
return self._image_type
@property
def size(self) -> Size:
"""Return image size in pixels"""
return self._size
@property
def mpp(self) -> Optional[SizeMm]:
"""Return pixel spacing in um/pixel"""
if self.pixel_spacing is None:
return None
return self.pixel_spacing * 1000.0
@property
def pixel_spacing(self) -> Optional[SizeMm]:
"""Return pixel spacing in mm/pixel"""
return self._pixel_spacing
@property
def instances(self) -> Dict[UID, WsiInstance]:
"""Return contained instances"""
return self._instances
@property
def default_instance(self) -> WsiInstance:
"""Return default instance"""
return self.instances[self._default_instance_uid]
@property
def datasets(self) -> List[WsiDataset]:
"""Return contained datasets."""
instance_datasets = [instance.datasets for instance in self.instances.values()]
return [dataset for sublist in instance_datasets for dataset in sublist]
@property
def optical_paths(self) -> List[str]:
return list(
{
path
for instance in self.instances.values()
for path in instance.optical_paths
}
)
@property
def focal_planes(self) -> List[float]:
return list(
{
focal_plane
for innstance in self.instances.values()
for focal_plane in innstance.focal_planes
}
)
@property
def image_coordinate_system(self) -> Optional[ImageCoordinateSystem]:
return self.default_instance.image_coordinate_system
def matches(self, other_group: "Group") -> bool:
"""Check if group matches other group. If strict common Uids should
match. Wsi type should always match.
Parameters
----------
other_group: Group
Other group to match against.
Returns
-------
bool
True if other group matches.
"""
return (
self.uids.matches(other_group.uids)
and other_group.image_type == self.image_type
)
def valid_pixels(self, region: Region) -> bool:
"""Check if pixel region is within the size of the group image size.
Parameters
----------
region: Region
Pixel region to check
Returns
-------
bool
True if pixel position and size is within image
"""
# Return true if inside pixel plane.
image_region = Region(Point(0, 0), self.size)
return region.is_inside(image_region)
def get_instance(
self, z: Optional[float] = None, path: Optional[str] = None
) -> WsiInstance:
"""Search for instance fulfilling the parameters.
The behavior when z and/or path is none could be made more
clear.
Parameters
----------
z: Optional[float] = None
Z coordinate of the searched instance
path: Optional[str] = None
Optical path of the searched instance
Returns
-------
WsiInstance
The instance containing selected path and z coordinate
"""
if z is None and path is None:
return self.default_instance
# Sort instances by number of focal planes (prefer simplest instance)
sorted_instances = sorted(
list(self._instances.values()), key=lambda i: len(i.focal_planes)
)
try:
if z is None:
# Select the instance with selected optical path
return next(
instance
for instance in sorted_instances
if path in instance.optical_paths
)
if path is None:
# Select the instance with selected z
return next(
instance
for instance in sorted_instances
if z in instance.focal_planes
)
# Select by both path and z
return next(
instance
for instance in sorted_instances
if (z in instance.focal_planes and path in instance.optical_paths)
)
except StopIteration as exception:
raise WsiDicomNotFoundError(
f"Instance for path: {path}, z: {z}", "group"
) from exception
def get_default_full(self) -> Image:
"""Read full image using default z coordinate and path.
Returns
-------
Image
Full image of the group.
"""
instance = self.default_instance
z = instance.default_z
path = instance.default_path
region = Region(position=Point(x=0, y=0), size=self.size)
image = self.get_region(region, z, path)
return image
def get_region(
self,
region: Region,
z: Optional[float] = None,
path: Optional[str] = None,
threads: int = 1,
) -> Image:
"""Read region defined by pixels.
Parameters
----------
location: int, int
Upper left corner of region in pixels
size: int
Size of region in pixels
z: Optional[float] = None
Z coordinate, optional
path: Optional[str] = None
optical path, optional
threads: int = 1
Number of threads to use for read.
Returns
-------
Image
Region as image
"""
instance = self.get_instance(z, path)
if z is None:
z = instance.default_z
if path is None:
path = instance.default_path
image = instance.image_data.stitch_tiles(region, path, z, threads)
return image
def get_region_mm(
self,
region: RegionMm,
z: Optional[float] = None,
path: Optional[str] = None,
slide_origin: bool = False,
threads: int = 1,
) -> Image:
"""Read region defined by mm.
Parameters
----------
region: RegionMm
Region defining upper left corner and size in mm.
z: Optional[float] = None
Z coordinate, optional.
path: Optional[str] = None
optical path, optional.
slide_origin: bool = False.
If to use the slide origin instead of image origin.
threads: int = 1
Number of threads to use for read.
Returns
-------
Image
Region as image
"""
to_coordinate_system = None
if slide_origin:
if self.image_coordinate_system is None:
raise ValueError(
"Can't map to slide region as image coordinate "
"system is not defined."
)
to_coordinate_system = self.image_coordinate_system
region = to_coordinate_system.slide_to_image(region)
pixel_region = self.mm_to_pixel(region)
image = self.get_region(pixel_region, z, path, threads)
if to_coordinate_system:
image = image.rotate(
to_coordinate_system.rotation,
resample=settings.pillow_resampling_filter,
expand=True,
)
return image
def get_tile(
self, tile: Point, z: Optional[float] = None, path: Optional[str] = None
) -> Image:
"""Return tile at tile coordinate x, y as image.
Parameters
----------
tile: Point
Tile x, y coordinate
z: Optional[float] = None
Z coordinate
path: Optional[str] = None
Optical path
Returns
-------
Image
The tile as image
"""
instance = self.get_instance(z, path)
if z is None:
z = instance.default_z
if path is None:
path = instance.default_path
return instance.image_data.get_tile(tile, z, path)
def get_encoded_tile(
self, tile: Point, z: Optional[float] = None, path: Optional[str] = None
) -> bytes:
"""Return tile at tile coordinate x, y as bytes.
Parameters
----------
tile: Point
Tile x, y coordinate
z: Optional[float] = None
Z coordinate
path: Optional[str] = None
Optical path
Returns
-------
bytes
The tile as bytes
"""
instance = self.get_instance(z, path)
if z is None:
z = instance.default_z
if path is None:
path = instance.default_path
return instance.image_data.get_encoded_tile(tile, z, path)
def mm_to_pixel(self, region: RegionMm) -> Region:
"""Convert region in mm to pixel region.
Parameters
----------
region: RegionMm
Region in mm
Returns
-------
Region
Region in pixels
"""
if self.pixel_spacing is None:
raise WsiDicomNoResolutionError()
pixel_region = Region(
position=region.position // self.pixel_spacing,
size=region.size // self.pixel_spacing,
)
if not self.valid_pixels(pixel_region):
raise WsiDicomOutOfBoundsError(
f"Region {region}", f"level size {self.size}"
)
return pixel_region
def _validate_group(self):
"""Check that no file or instance in group is duplicate, and if strict
instances in group matches. Raises WsiDicomMatchError otherwise.
"""
instances = list(self.instances.values())
base_instance = instances[0]
for instance in instances[1:]:
if not base_instance.matches(instance):
raise WsiDicomMatchError(str(instance), str(self))
WsiDataset.check_duplicate_dataset(self.datasets, self)
WsiInstance.check_duplicate_instance(instances, self)
@staticmethod
def _get_frame_information(
data: Dict[Tuple[str, float], ImageData]
) -> Tuple[List[float], List[str], Size]:
"""Return optical_paths, focal planes, and tiled size."""
focal_planes_by_optical_path: Dict[str, Set[float]] = defaultdict(set)
all_focal_planes: Set[float] = set()
tiled_sizes: Set[Size] = set()
for (optical_path, focal_plane), image_data in data.items():
focal_planes_by_optical_path[optical_path].add(focal_plane)
all_focal_planes.add(focal_plane)
tiled_sizes.add(image_data.tiled_size)
focal_planes_sparse_by_optical_path = any(
optical_path_focal_planes != all_focal_planes
for optical_path_focal_planes in focal_planes_by_optical_path.values()
)
if focal_planes_sparse_by_optical_path:
raise ValueError("Each optical path must have the same focal planes.")
if len(tiled_sizes) != 1:
raise ValueError("Expected only one tiled size")
tiled_size = list(tiled_sizes)[0]
return (
sorted(list(all_focal_planes)),
sorted(list(focal_planes_by_optical_path.keys())),
tiled_size,
)