-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
utils.py
2055 lines (1746 loc) · 79.5 KB
/
utils.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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) MONAI Consortium
# 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 __future__ import annotations
import itertools
import random
import warnings
from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
from contextlib import contextmanager
from functools import lru_cache, wraps
from inspect import getmembers, isclass
from typing import Any
import numpy as np
import torch
import monai
from monai.config import DtypeLike, IndexSelection
from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor
from monai.networks.layers import GaussianFilter
from monai.networks.utils import meshgrid_ij
from monai.transforms.compose import Compose
from monai.transforms.transform import MapTransform, Transform, apply_transform
from monai.transforms.utils_pytorch_numpy_unification import (
any_np_pt,
ascontiguousarray,
cumsum,
isfinite,
nonzero,
ravel,
searchsorted,
unique,
unravel_index,
where,
)
from monai.utils import (
GridSampleMode,
GridSamplePadMode,
InterpolateMode,
NdimageMode,
NumpyPadMode,
PostFix,
PytorchPadMode,
SplineMode,
TraceKeys,
TraceStatusKeys,
deprecated_arg_default,
ensure_tuple,
ensure_tuple_rep,
ensure_tuple_size,
fall_back_tuple,
get_equivalent_dtype,
issequenceiterable,
look_up_option,
min_version,
optional_import,
pytorch_after,
)
from monai.utils.enums import TransformBackends
from monai.utils.type_conversion import convert_data_type, convert_to_cupy, convert_to_dst_type, convert_to_tensor
measure, has_measure = optional_import("skimage.measure", "0.14.2", min_version)
morphology, has_morphology = optional_import("skimage.morphology")
ndimage, _ = optional_import("scipy.ndimage")
cp, has_cp = optional_import("cupy")
cp_ndarray, _ = optional_import("cupy", name="ndarray")
exposure, has_skimage = optional_import("skimage.exposure")
__all__ = [
"allow_missing_keys_mode",
"check_boundaries",
"compute_divisible_spatial_size",
"convert_applied_interp_mode",
"copypaste_arrays",
"check_non_lazy_pending_ops",
"create_control_grid",
"create_grid",
"create_rotate",
"create_scale",
"create_shear",
"create_translate",
"extreme_points_to_image",
"fill_holes",
"Fourier",
"generate_label_classes_crop_centers",
"generate_pos_neg_label_crop_centers",
"generate_spatial_bounding_box",
"get_extreme_points",
"get_largest_connected_component_mask",
"remove_small_objects",
"img_bounds",
"in_bounds",
"is_empty",
"is_positive",
"map_binary_to_indices",
"map_classes_to_indices",
"map_spatial_axes",
"rand_choice",
"rescale_array",
"rescale_array_int_max",
"rescale_instance_array",
"resize_center",
"weighted_patch_samples",
"zero_margins",
"equalize_hist",
"get_number_image_type_conversions",
"get_transform_backends",
"print_transform_backends",
"convert_pad_mode",
"convert_to_contiguous",
"get_unique_labels",
"scale_affine",
"attach_hook",
"sync_meta_info",
"reset_ops_id",
"resolves_modes",
"has_status_keys",
]
def rand_choice(prob: float = 0.5) -> bool:
"""
Returns True if a randomly chosen number is less than or equal to `prob`, by default this is a 50/50 chance.
"""
return bool(random.random() <= prob)
def img_bounds(img: np.ndarray):
"""
Returns the minimum and maximum indices of non-zero lines in axis 0 of `img`, followed by that for axis 1.
"""
ax0 = np.any(img, axis=0)
ax1 = np.any(img, axis=1)
return np.concatenate((np.where(ax0)[0][[0, -1]], np.where(ax1)[0][[0, -1]]))
def in_bounds(x: float, y: float, margin: float, maxx: float, maxy: float) -> bool:
"""
Returns True if (x,y) is within the rectangle (margin, margin, maxx-margin, maxy-margin).
"""
return bool(margin <= x < (maxx - margin) and margin <= y < (maxy - margin))
def is_empty(img: np.ndarray | torch.Tensor) -> bool:
"""
Returns True if `img` is empty, that is its maximum value is not greater than its minimum.
"""
return not (img.max() > img.min()) # use > instead of <= so that an image full of NaNs will result in True
def is_positive(img):
"""
Returns a boolean version of `img` where the positive values are converted into True, the other values are False.
"""
return img > 0
def zero_margins(img: np.ndarray, margin: int) -> bool:
"""
Returns True if the values within `margin` indices of the edges of `img` in dimensions 1 and 2 are 0.
"""
if np.any(img[:, :, :margin]) or np.any(img[:, :, -margin:]):
return False
return not np.any(img[:, :margin, :]) and not np.any(img[:, -margin:, :])
def rescale_array(
arr: NdarrayOrTensor,
minv: float | None = 0.0,
maxv: float | None = 1.0,
dtype: DtypeLike | torch.dtype = np.float32,
) -> NdarrayOrTensor:
"""
Rescale the values of numpy array `arr` to be from `minv` to `maxv`.
If either `minv` or `maxv` is None, it returns `(a - min_a) / (max_a - min_a)`.
Args:
arr: input array to rescale.
minv: minimum value of target rescaled array.
maxv: maxmum value of target rescaled array.
dtype: if not None, convert input array to dtype before computation.
"""
if dtype is not None:
arr, *_ = convert_data_type(arr, dtype=dtype)
mina = arr.min()
maxa = arr.max()
if mina == maxa:
return arr * minv if minv is not None else arr
norm = (arr - mina) / (maxa - mina) # normalize the array first
if (minv is None) or (maxv is None):
return norm
return (norm * (maxv - minv)) + minv # rescale by minv and maxv, which is the normalized array by default
def rescale_instance_array(
arr: np.ndarray, minv: float | None = 0.0, maxv: float | None = 1.0, dtype: DtypeLike = np.float32
) -> np.ndarray:
"""
Rescale each array slice along the first dimension of `arr` independently.
"""
out: np.ndarray = np.zeros(arr.shape, dtype or arr.dtype)
for i in range(arr.shape[0]):
out[i] = rescale_array(arr[i], minv, maxv, dtype)
return out
def rescale_array_int_max(arr: np.ndarray, dtype: DtypeLike = np.uint16) -> np.ndarray:
"""
Rescale the array `arr` to be between the minimum and maximum values of the type `dtype`.
"""
info: np.iinfo = np.iinfo(dtype or arr.dtype)
return np.asarray(rescale_array(arr, info.min, info.max), dtype=dtype or arr.dtype)
def copypaste_arrays(
src_shape, dest_shape, srccenter: Sequence[int], destcenter: Sequence[int], dims: Sequence[int | None]
) -> tuple[tuple[slice, ...], tuple[slice, ...]]:
"""
Calculate the slices to copy a sliced area of array in `src_shape` into array in `dest_shape`.
The area has dimensions `dims` (use 0 or None to copy everything in that dimension),
the source area is centered at `srccenter` index in `src` and copied into area centered at `destcenter` in `dest`.
The dimensions of the copied area will be clipped to fit within the
source and destination arrays so a smaller area may be copied than expected. Return value is the tuples of slice
objects indexing the copied area in `src`, and those indexing the copy area in `dest`.
Example
.. code-block:: python
src_shape = (6,6)
src = np.random.randint(0,10,src_shape)
dest = np.zeros_like(src)
srcslices, destslices = copypaste_arrays(src_shape, dest.shape, (3, 2),(2, 1),(3, 4))
dest[destslices] = src[srcslices]
print(src)
print(dest)
>>> [[9 5 6 6 9 6]
[4 3 5 6 1 2]
[0 7 3 2 4 1]
[3 0 0 1 5 1]
[9 4 7 1 8 2]
[6 6 5 8 6 7]]
[[0 0 0 0 0 0]
[7 3 2 4 0 0]
[0 0 1 5 0 0]
[4 7 1 8 0 0]
[0 0 0 0 0 0]
[0 0 0 0 0 0]]
"""
s_ndim = len(src_shape)
d_ndim = len(dest_shape)
srcslices = [slice(None)] * s_ndim
destslices = [slice(None)] * d_ndim
for i, ss, ds, sc, dc, dim in zip(range(s_ndim), src_shape, dest_shape, srccenter, destcenter, dims):
if dim:
# dimension before midpoint, clip to size fitting in both arrays
d1 = np.clip(dim // 2, 0, min(sc, dc))
# dimension after midpoint, clip to size fitting in both arrays
d2 = np.clip(dim // 2 + 1, 0, min(ss - sc, ds - dc))
srcslices[i] = slice(sc - d1, sc + d2)
destslices[i] = slice(dc - d1, dc + d2)
return tuple(srcslices), tuple(destslices)
def resize_center(img: np.ndarray, *resize_dims: int | None, fill_value: float = 0.0, inplace: bool = True):
"""
Resize `img` by cropping or expanding the image from the center. The `resize_dims` values are the output dimensions
(or None to use original dimension of `img`). If a dimension is smaller than that of `img` then the result will be
cropped and if larger padded with zeros, in both cases this is done relative to the center of `img`. The result is
a new image with the specified dimensions and values from `img` copied into its center.
"""
resize_dims = fall_back_tuple(resize_dims, img.shape)
half_img_shape = (np.asarray(img.shape) // 2).tolist()
half_dest_shape = (np.asarray(resize_dims) // 2).tolist()
srcslices, destslices = copypaste_arrays(img.shape, resize_dims, half_img_shape, half_dest_shape, resize_dims)
if not inplace:
dest = np.full(resize_dims, fill_value, img.dtype) # type: ignore
dest[destslices] = img[srcslices]
return dest
return img[srcslices]
def check_non_lazy_pending_ops(
input_array: NdarrayOrTensor, name: None | str = None, raise_error: bool = False
) -> None:
"""
Check whether the input array has pending operations, raise an error or warn when it has.
Args:
input_array: input array to be checked.
name: an optional name to be included in the error message.
raise_error: whether to raise an error, default to False, a warning message will be issued instead.
"""
if isinstance(input_array, monai.data.MetaTensor) and input_array.pending_operations:
msg = (
"The input image is a MetaTensor and has pending operations,\n"
f"but the function {name or ''} assumes non-lazy input, result may be incorrect."
)
if raise_error:
raise ValueError(msg)
warnings.warn(msg)
def map_binary_to_indices(
label: NdarrayOrTensor, image: NdarrayOrTensor | None = None, image_threshold: float = 0.0
) -> tuple[NdarrayOrTensor, NdarrayOrTensor]:
"""
Compute the foreground and background of input label data, return the indices after fattening.
For example:
``label = np.array([[[0, 1, 1], [1, 0, 1], [1, 1, 0]]])``
``foreground indices = np.array([1, 2, 3, 5, 6, 7])`` and ``background indices = np.array([0, 4, 8])``
Args:
label: use the label data to get the foreground/background information.
image: if image is not None, use ``label = 0 & image > image_threshold``
to define background. so the output items will not map to all the voxels in the label.
image_threshold: if enabled `image`, use ``image > image_threshold`` to
determine the valid image content area and select background only in this area.
"""
check_non_lazy_pending_ops(label, name="map_binary_to_indices")
# Prepare fg/bg indices
if label.shape[0] > 1:
label = label[1:] # for One-Hot format data, remove the background channel
label_flat = ravel(any_np_pt(label, 0)) # in case label has multiple dimensions
fg_indices = nonzero(label_flat)
if image is not None:
check_non_lazy_pending_ops(image, name="map_binary_to_indices")
img_flat = ravel(any_np_pt(image > image_threshold, 0))
img_flat, *_ = convert_to_dst_type(img_flat, label, dtype=bool)
bg_indices = nonzero(img_flat & ~label_flat)
else:
bg_indices = nonzero(~label_flat)
# no need to save the indices in GPU, otherwise, still need to move to CPU at runtime when crop by indices
fg_indices, *_ = convert_data_type(fg_indices, device=torch.device("cpu"))
bg_indices, *_ = convert_data_type(bg_indices, device=torch.device("cpu"))
return fg_indices, bg_indices
def map_classes_to_indices(
label: NdarrayOrTensor,
num_classes: int | None = None,
image: NdarrayOrTensor | None = None,
image_threshold: float = 0.0,
max_samples_per_class: int | None = None,
) -> list[NdarrayOrTensor]:
"""
Filter out indices of every class of the input label data, return the indices after fattening.
It can handle both One-Hot format label and Argmax format label, must provide `num_classes` for
Argmax label.
For example:
``label = np.array([[[0, 1, 2], [2, 0, 1], [1, 2, 0]]])`` and `num_classes=3`, will return a list
which contains the indices of the 3 classes:
``[np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7])]``
Args:
label: use the label data to get the indices of every class.
num_classes: number of classes for argmax label, not necessary for One-Hot label.
image: if image is not None, only return the indices of every class that are within the valid
region of the image (``image > image_threshold``).
image_threshold: if enabled `image`, use ``image > image_threshold`` to
determine the valid image content area and select class indices only in this area.
max_samples_per_class: maximum length of indices in each class to reduce memory consumption.
Default is None, no subsampling.
"""
check_non_lazy_pending_ops(label, name="map_classes_to_indices")
img_flat: NdarrayOrTensor | None = None
if image is not None:
check_non_lazy_pending_ops(image, name="map_classes_to_indices")
img_flat = ravel((image > image_threshold).any(0))
# assuming the first dimension is channel
channels = len(label)
num_classes_: int = channels
if channels == 1:
if num_classes is None:
raise ValueError("channels==1 indicates not using One-Hot format label, must provide ``num_classes``.")
num_classes_ = num_classes
indices: list[NdarrayOrTensor] = []
for c in range(num_classes_):
if channels > 1:
label_flat = ravel(convert_data_type(label[c], dtype=bool)[0])
else:
label_flat = ravel(label == c)
if img_flat is not None:
label_flat = img_flat & label_flat
# no need to save the indices in GPU, otherwise, still need to move to CPU at runtime when crop by indices
output_type = torch.Tensor if isinstance(label, monai.data.MetaTensor) else None
cls_indices: NdarrayOrTensor = convert_data_type(
nonzero(label_flat), output_type=output_type, device=torch.device("cpu")
)[0]
if max_samples_per_class and len(cls_indices) > max_samples_per_class and len(cls_indices) > 1:
sample_id = np.round(np.linspace(0, len(cls_indices) - 1, max_samples_per_class)).astype(int)
indices.append(cls_indices[sample_id])
else:
indices.append(cls_indices)
return indices
def weighted_patch_samples(
spatial_size: int | Sequence[int],
w: NdarrayOrTensor,
n_samples: int = 1,
r_state: np.random.RandomState | None = None,
) -> list:
"""
Computes `n_samples` of random patch sampling locations, given the sampling weight map `w` and patch `spatial_size`.
Args:
spatial_size: length of each spatial dimension of the patch.
w: weight map, the weights must be non-negative. each element denotes a sampling weight of the spatial location.
0 indicates no sampling.
The weight map shape is assumed ``(spatial_dim_0, spatial_dim_1, ..., spatial_dim_n)``.
n_samples: number of patch samples
r_state: a random state container
Returns:
a list of `n_samples` N-D integers representing the spatial sampling location of patches.
"""
check_non_lazy_pending_ops(w, name="weighted_patch_samples")
if w is None:
raise ValueError("w must be an ND array, got None.")
if r_state is None:
r_state = np.random.RandomState()
img_size = np.asarray(w.shape, dtype=int)
win_size = np.asarray(fall_back_tuple(spatial_size, img_size), dtype=int)
s = tuple(slice(w // 2, m - w + w // 2) if m > w else slice(m // 2, m // 2 + 1) for w, m in zip(win_size, img_size))
v = w[s] # weight map in the 'valid' mode
v_size = v.shape
v = ravel(v) # always copy
if (v < 0).any():
v -= v.min() # shifting to non-negative
v = cumsum(v)
if not v[-1] or not isfinite(v[-1]) or v[-1] < 0: # uniform sampling
idx = r_state.randint(0, len(v), size=n_samples)
else:
r, *_ = convert_to_dst_type(r_state.random(n_samples), v)
idx = searchsorted(v, r * v[-1], right=True) # type: ignore
idx, *_ = convert_to_dst_type(idx, v, dtype=torch.int) # type: ignore
# compensate 'valid' mode
diff = np.minimum(win_size, img_size) // 2
diff, *_ = convert_to_dst_type(diff, v) # type: ignore
return [unravel_index(i, v_size) + diff for i in idx]
def correct_crop_centers(
centers: list[int],
spatial_size: Sequence[int] | int,
label_spatial_shape: Sequence[int],
allow_smaller: bool = False,
) -> tuple[Any]:
"""
Utility to correct the crop center if the crop size and centers are not compatible with the image size.
Args:
centers: pre-computed crop centers of every dim, will correct based on the valid region.
spatial_size: spatial size of the ROIs to be sampled.
label_spatial_shape: spatial shape of the original label data to compare with ROI.
allow_smaller: if `False`, an exception will be raised if the image is smaller than
the requested ROI in any dimension. If `True`, any smaller dimensions will be set to
match the cropped size (i.e., no cropping in that dimension).
"""
spatial_size = fall_back_tuple(spatial_size, default=label_spatial_shape)
if any(np.subtract(label_spatial_shape, spatial_size) < 0):
if not allow_smaller:
raise ValueError(
"The size of the proposed random crop ROI is larger than the image size, "
f"got ROI size {spatial_size} and label image size {label_spatial_shape} respectively."
)
spatial_size = tuple(min(l, s) for l, s in zip(label_spatial_shape, spatial_size))
# Select subregion to assure valid roi
valid_start = np.floor_divide(spatial_size, 2)
# add 1 for random
valid_end = np.subtract(label_spatial_shape + np.array(1), spatial_size / np.array(2)).astype(np.uint16)
# int generation to have full range on upper side, but subtract unfloored size/2 to prevent rounded range
# from being too high
for i, valid_s in enumerate(valid_start):
# need this because np.random.randint does not work with same start and end
if valid_s == valid_end[i]:
valid_end[i] += 1
valid_centers = []
for c, v_s, v_e in zip(centers, valid_start, valid_end):
center_i = min(max(c, v_s), v_e - 1)
valid_centers.append(int(center_i))
return ensure_tuple(valid_centers) # type: ignore
def generate_pos_neg_label_crop_centers(
spatial_size: Sequence[int] | int,
num_samples: int,
pos_ratio: float,
label_spatial_shape: Sequence[int],
fg_indices: NdarrayOrTensor,
bg_indices: NdarrayOrTensor,
rand_state: np.random.RandomState | None = None,
allow_smaller: bool = False,
) -> tuple[tuple]:
"""
Generate valid sample locations based on the label with option for specifying foreground ratio
Valid: samples sitting entirely within image, expected input shape: [C, H, W, D] or [C, H, W]
Args:
spatial_size: spatial size of the ROIs to be sampled.
num_samples: total sample centers to be generated.
pos_ratio: ratio of total locations generated that have center being foreground.
label_spatial_shape: spatial shape of the original label data to unravel selected centers.
fg_indices: pre-computed foreground indices in 1 dimension.
bg_indices: pre-computed background indices in 1 dimension.
rand_state: numpy randomState object to align with other modules.
allow_smaller: if `False`, an exception will be raised if the image is smaller than
the requested ROI in any dimension. If `True`, any smaller dimensions will be set to
match the cropped size (i.e., no cropping in that dimension).
Raises:
ValueError: When the proposed roi is larger than the image.
ValueError: When the foreground and background indices lengths are 0.
"""
if rand_state is None:
rand_state = np.random.random.__self__ # type: ignore
centers = []
fg_indices = np.asarray(fg_indices) if isinstance(fg_indices, Sequence) else fg_indices
bg_indices = np.asarray(bg_indices) if isinstance(bg_indices, Sequence) else bg_indices
if len(fg_indices) == 0 and len(bg_indices) == 0:
raise ValueError("No sampling location available.")
if len(fg_indices) == 0 or len(bg_indices) == 0:
pos_ratio = 0 if len(fg_indices) == 0 else 1
warnings.warn(
f"Num foregrounds {len(fg_indices)}, Num backgrounds {len(bg_indices)}, "
f"unable to generate class balanced samples, setting `pos_ratio` to {pos_ratio}."
)
for _ in range(num_samples):
indices_to_use = fg_indices if rand_state.rand() < pos_ratio else bg_indices
random_int = rand_state.randint(len(indices_to_use))
idx = indices_to_use[random_int]
center = unravel_index(idx, label_spatial_shape).tolist()
# shift center to range of valid centers
centers.append(correct_crop_centers(center, spatial_size, label_spatial_shape, allow_smaller))
return ensure_tuple(centers) # type: ignore
def generate_label_classes_crop_centers(
spatial_size: Sequence[int] | int,
num_samples: int,
label_spatial_shape: Sequence[int],
indices: Sequence[NdarrayOrTensor],
ratios: list[float | int] | None = None,
rand_state: np.random.RandomState | None = None,
allow_smaller: bool = False,
warn: bool = True,
) -> tuple[tuple]:
"""
Generate valid sample locations based on the specified ratios of label classes.
Valid: samples sitting entirely within image, expected input shape: [C, H, W, D] or [C, H, W]
Args:
spatial_size: spatial size of the ROIs to be sampled.
num_samples: total sample centers to be generated.
label_spatial_shape: spatial shape of the original label data to unravel selected centers.
indices: sequence of pre-computed foreground indices of every class in 1 dimension.
ratios: ratios of every class in the label to generate crop centers, including background class.
if None, every class will have the same ratio to generate crop centers.
rand_state: numpy randomState object to align with other modules.
allow_smaller: if `False`, an exception will be raised if the image is smaller than
the requested ROI in any dimension. If `True`, any smaller dimensions will be set to
match the cropped size (i.e., no cropping in that dimension).
warn: if `True` prints a warning if a class is not present in the label.
"""
if rand_state is None:
rand_state = np.random.random.__self__ # type: ignore
if num_samples < 1:
raise ValueError(f"num_samples must be an int number and greater than 0, got {num_samples}.")
ratios_: list[float | int] = list(ensure_tuple([1] * len(indices) if ratios is None else ratios))
if len(ratios_) != len(indices):
raise ValueError(
f"random crop ratios must match the number of indices of classes, got {len(ratios_)} and {len(indices)}."
)
if any(i < 0 for i in ratios_):
raise ValueError(f"ratios should not contain negative number, got {ratios_}.")
for i, array in enumerate(indices):
if len(array) == 0:
ratios_[i] = 0
if warn:
warnings.warn(f"no available indices of class {i} to crop, set the crop ratio of this class to zero.")
centers = []
classes = rand_state.choice(len(ratios_), size=num_samples, p=np.asarray(ratios_) / np.sum(ratios_))
for i in classes:
# randomly select the indices of a class based on the ratios
indices_to_use = indices[i]
random_int = rand_state.randint(len(indices_to_use))
center = unravel_index(indices_to_use[random_int], label_spatial_shape).tolist()
# shift center to range of valid centers
centers.append(correct_crop_centers(center, spatial_size, label_spatial_shape, allow_smaller))
return ensure_tuple(centers) # type: ignore
def create_grid(
spatial_size: Sequence[int],
spacing: Sequence[float] | None = None,
homogeneous: bool = True,
dtype: DtypeLike | torch.dtype = float,
device: torch.device | None = None,
backend=TransformBackends.NUMPY,
) -> NdarrayOrTensor:
"""
compute a `spatial_size` mesh.
- when ``homogeneous=True``, the output shape is (N+1, dim_size_1, dim_size_2, ..., dim_size_N)
- when ``homogeneous=False``, the output shape is (N, dim_size_1, dim_size_2, ..., dim_size_N)
Args:
spatial_size: spatial size of the grid.
spacing: same len as ``spatial_size``, defaults to 1.0 (dense grid).
homogeneous: whether to make homogeneous coordinates.
dtype: output grid data type, defaults to `float`.
device: device to compute and store the output (when the backend is "torch").
backend: APIs to use, ``numpy`` or ``torch``.
"""
_backend = look_up_option(backend, TransformBackends)
_dtype = dtype or float
if _backend == TransformBackends.NUMPY:
return _create_grid_numpy(spatial_size, spacing, homogeneous, _dtype) # type: ignore
if _backend == TransformBackends.TORCH:
return _create_grid_torch(spatial_size, spacing, homogeneous, _dtype, device) # type: ignore
raise ValueError(f"backend {backend} is not supported")
def _create_grid_numpy(
spatial_size: Sequence[int],
spacing: Sequence[float] | None = None,
homogeneous: bool = True,
dtype: DtypeLike | torch.dtype = float,
):
"""
compute a `spatial_size` mesh with the numpy API.
"""
spacing = spacing or tuple(1.0 for _ in spatial_size)
ranges = [np.linspace(-(d - 1.0) / 2.0 * s, (d - 1.0) / 2.0 * s, int(d)) for d, s in zip(spatial_size, spacing)]
coords = np.asarray(np.meshgrid(*ranges, indexing="ij"), dtype=get_equivalent_dtype(dtype, np.ndarray))
if not homogeneous:
return coords
return np.concatenate([coords, np.ones_like(coords[:1])])
def _create_grid_torch(
spatial_size: Sequence[int],
spacing: Sequence[float] | None = None,
homogeneous: bool = True,
dtype=torch.float32,
device: torch.device | None = None,
):
"""
compute a `spatial_size` mesh with the torch API.
"""
spacing = spacing or tuple(1.0 for _ in spatial_size)
ranges = [
torch.linspace(
-(d - 1.0) / 2.0 * s,
(d - 1.0) / 2.0 * s,
int(d),
device=device,
dtype=get_equivalent_dtype(dtype, torch.Tensor),
)
for d, s in zip(spatial_size, spacing)
]
coords = meshgrid_ij(*ranges)
if not homogeneous:
return torch.stack(coords)
return torch.stack([*coords, torch.ones_like(coords[0])])
def create_control_grid(
spatial_shape: Sequence[int],
spacing: Sequence[float],
homogeneous: bool = True,
dtype: DtypeLike = float,
device: torch.device | None = None,
backend=TransformBackends.NUMPY,
):
"""
control grid with two additional point in each direction
"""
torch_backend = look_up_option(backend, TransformBackends) == TransformBackends.TORCH
ceil_func: Callable = torch.ceil if torch_backend else np.ceil # type: ignore
grid_shape = []
for d, s in zip(spatial_shape, spacing):
d = torch.as_tensor(d, device=device) if torch_backend else int(d) # type: ignore
if d % 2 == 0:
grid_shape.append(ceil_func((d - 1.0) / (2.0 * s) + 0.5) * 2.0 + 2.0)
else:
grid_shape.append(ceil_func((d - 1.0) / (2.0 * s)) * 2.0 + 3.0)
return create_grid(
spatial_size=grid_shape, spacing=spacing, homogeneous=homogeneous, dtype=dtype, device=device, backend=backend
)
def create_rotate(
spatial_dims: int,
radians: Sequence[float] | float,
device: torch.device | None = None,
backend: str = TransformBackends.NUMPY,
) -> NdarrayOrTensor:
"""
create a 2D or 3D rotation matrix
Args:
spatial_dims: {``2``, ``3``} spatial rank
radians: rotation radians
when spatial_dims == 3, the `radians` sequence corresponds to
rotation in the 1st, 2nd, and 3rd dim respectively.
device: device to compute and store the output (when the backend is "torch").
backend: APIs to use, ``numpy`` or ``torch``.
Raises:
ValueError: When ``radians`` is empty.
ValueError: When ``spatial_dims`` is not one of [2, 3].
"""
_backend = look_up_option(backend, TransformBackends)
if _backend == TransformBackends.NUMPY:
return _create_rotate(
spatial_dims=spatial_dims, radians=radians, sin_func=np.sin, cos_func=np.cos, eye_func=np.eye
)
if _backend == TransformBackends.TORCH:
return _create_rotate(
spatial_dims=spatial_dims,
radians=radians,
sin_func=lambda th: torch.sin(torch.as_tensor(th, dtype=torch.float32, device=device)),
cos_func=lambda th: torch.cos(torch.as_tensor(th, dtype=torch.float32, device=device)),
eye_func=lambda rank: torch.eye(rank, device=device),
)
raise ValueError(f"backend {backend} is not supported")
def _create_rotate(
spatial_dims: int,
radians: Sequence[float] | float,
sin_func: Callable = np.sin,
cos_func: Callable = np.cos,
eye_func: Callable = np.eye,
) -> NdarrayOrTensor:
radians = ensure_tuple(radians)
if spatial_dims == 2:
if len(radians) >= 1:
sin_, cos_ = sin_func(radians[0]), cos_func(radians[0])
out = eye_func(3)
out[0, 0], out[0, 1] = cos_, -sin_
out[1, 0], out[1, 1] = sin_, cos_
return out # type: ignore
raise ValueError("radians must be non empty.")
if spatial_dims == 3:
affine = None
if len(radians) >= 1:
sin_, cos_ = sin_func(radians[0]), cos_func(radians[0])
affine = eye_func(4)
affine[1, 1], affine[1, 2] = cos_, -sin_
affine[2, 1], affine[2, 2] = sin_, cos_
if len(radians) >= 2:
sin_, cos_ = sin_func(radians[1]), cos_func(radians[1])
if affine is None:
raise ValueError("Affine should be a matrix.")
_affine = eye_func(4)
_affine[0, 0], _affine[0, 2] = cos_, sin_
_affine[2, 0], _affine[2, 2] = -sin_, cos_
affine = affine @ _affine
if len(radians) >= 3:
sin_, cos_ = sin_func(radians[2]), cos_func(radians[2])
if affine is None:
raise ValueError("Affine should be a matrix.")
_affine = eye_func(4)
_affine[0, 0], _affine[0, 1] = cos_, -sin_
_affine[1, 0], _affine[1, 1] = sin_, cos_
affine = affine @ _affine
if affine is None:
raise ValueError("radians must be non empty.")
return affine # type: ignore
raise ValueError(f"Unsupported spatial_dims: {spatial_dims}, available options are [2, 3].")
def create_shear(
spatial_dims: int,
coefs: Sequence[float] | float,
device: torch.device | None = None,
backend=TransformBackends.NUMPY,
) -> NdarrayOrTensor:
"""
create a shearing matrix
Args:
spatial_dims: spatial rank
coefs: shearing factors, a tuple of 2 floats for 2D, a tuple of 6 floats for 3D),
take a 3D affine as example::
[
[1.0, coefs[0], coefs[1], 0.0],
[coefs[2], 1.0, coefs[3], 0.0],
[coefs[4], coefs[5], 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
]
device: device to compute and store the output (when the backend is "torch").
backend: APIs to use, ``numpy`` or ``torch``.
Raises:
NotImplementedError: When ``spatial_dims`` is not one of [2, 3].
"""
_backend = look_up_option(backend, TransformBackends)
if _backend == TransformBackends.NUMPY:
return _create_shear(spatial_dims=spatial_dims, coefs=coefs, eye_func=np.eye)
if _backend == TransformBackends.TORCH:
return _create_shear(
spatial_dims=spatial_dims, coefs=coefs, eye_func=lambda rank: torch.eye(rank, device=device)
)
raise ValueError(f"backend {backend} is not supported")
def _create_shear(spatial_dims: int, coefs: Sequence[float] | float, eye_func=np.eye) -> NdarrayOrTensor:
if spatial_dims == 2:
coefs = ensure_tuple_size(coefs, dim=2, pad_val=0.0)
out = eye_func(3)
out[0, 1], out[1, 0] = coefs[0], coefs[1]
return out # type: ignore
if spatial_dims == 3:
coefs = ensure_tuple_size(coefs, dim=6, pad_val=0.0)
out = eye_func(4)
out[0, 1], out[0, 2] = coefs[0], coefs[1]
out[1, 0], out[1, 2] = coefs[2], coefs[3]
out[2, 0], out[2, 1] = coefs[4], coefs[5]
return out # type: ignore
raise NotImplementedError("Currently only spatial_dims in [2, 3] are supported.")
def create_scale(
spatial_dims: int,
scaling_factor: Sequence[float] | float,
device: torch.device | str | None = None,
backend=TransformBackends.NUMPY,
) -> NdarrayOrTensor:
"""
create a scaling matrix
Args:
spatial_dims: spatial rank
scaling_factor: scaling factors for every spatial dim, defaults to 1.
device: device to compute and store the output (when the backend is "torch").
backend: APIs to use, ``numpy`` or ``torch``.
"""
_backend = look_up_option(backend, TransformBackends)
if _backend == TransformBackends.NUMPY:
return _create_scale(spatial_dims=spatial_dims, scaling_factor=scaling_factor, array_func=np.diag)
if _backend == TransformBackends.TORCH:
return _create_scale(
spatial_dims=spatial_dims,
scaling_factor=scaling_factor,
array_func=lambda x: torch.diag(torch.as_tensor(x, device=device)),
)
raise ValueError(f"backend {backend} is not supported")
def _create_scale(spatial_dims: int, scaling_factor: Sequence[float] | float, array_func=np.diag) -> NdarrayOrTensor:
scaling_factor = ensure_tuple_size(scaling_factor, dim=spatial_dims, pad_val=1.0)
return array_func(scaling_factor[:spatial_dims] + (1.0,)) # type: ignore
def create_translate(
spatial_dims: int,
shift: Sequence[float] | float,
device: torch.device | None = None,
backend=TransformBackends.NUMPY,
) -> NdarrayOrTensor:
"""
create a translation matrix
Args:
spatial_dims: spatial rank
shift: translate pixel/voxel for every spatial dim, defaults to 0.
device: device to compute and store the output (when the backend is "torch").
backend: APIs to use, ``numpy`` or ``torch``.
"""
_backend = look_up_option(backend, TransformBackends)
spatial_dims = int(spatial_dims)
if _backend == TransformBackends.NUMPY:
return _create_translate(spatial_dims=spatial_dims, shift=shift, eye_func=np.eye, array_func=np.asarray)
if _backend == TransformBackends.TORCH:
return _create_translate(
spatial_dims=spatial_dims,
shift=shift,
eye_func=lambda x: torch.eye(torch.as_tensor(x), device=device), # type: ignore
array_func=lambda x: torch.as_tensor(x, device=device),
)
raise ValueError(f"backend {backend} is not supported")
def _create_translate(
spatial_dims: int, shift: Sequence[float] | float, eye_func=np.eye, array_func=np.asarray
) -> NdarrayOrTensor:
shift = ensure_tuple(shift)
affine = eye_func(spatial_dims + 1)
for i, a in enumerate(shift[:spatial_dims]):
affine[i, spatial_dims] = a
return array_func(affine) # type: ignore
@deprecated_arg_default("allow_smaller", old_default=True, new_default=False, since="1.2", replaced="1.3")
def generate_spatial_bounding_box(
img: NdarrayOrTensor,
select_fn: Callable = is_positive,
channel_indices: IndexSelection | None = None,
margin: Sequence[int] | int = 0,
allow_smaller: bool = True,
) -> tuple[list[int], list[int]]:
"""
Generate the spatial bounding box of foreground in the image with start-end positions (inclusive).
Users can define arbitrary function to select expected foreground from the whole image or specified channels.
And it can also add margin to every dim of the bounding box.
The output format of the coordinates is:
[1st_spatial_dim_start, 2nd_spatial_dim_start, ..., Nth_spatial_dim_start],
[1st_spatial_dim_end, 2nd_spatial_dim_end, ..., Nth_spatial_dim_end]
This function returns [0, 0, ...], [0, 0, ...] if there's no positive intensity.
Args:
img: a "channel-first" image of shape (C, spatial_dim1[, spatial_dim2, ...]) to generate bounding box from.
select_fn: function to select expected foreground, default is to select values > 0.
channel_indices: if defined, select foreground only on the specified channels
of image. if None, select foreground on the whole image.
margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims.
allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the
final box edges. If `True`, the bounding boxes edges are aligned with the input image edges, if `False`,
the bounding boxes edges are aligned with the final box edges. Default to `True`.
"""
check_non_lazy_pending_ops(img, name="generate_spatial_bounding_box")
spatial_size = img.shape[1:]
data = img[list(ensure_tuple(channel_indices))] if channel_indices is not None else img
data = select_fn(data).any(0)
ndim = len(data.shape)
margin = ensure_tuple_rep(margin, ndim)
for m in margin:
if m < 0:
raise ValueError(f"margin value should not be negative number, got {margin}.")
box_start = [0] * ndim
box_end = [0] * ndim
for di, ax in enumerate(itertools.combinations(reversed(range(ndim)), ndim - 1)):
dt = data
if len(ax) != 0:
dt = any_np_pt(dt, ax)
if not dt.any():
# if no foreground, return all zero bounding box coords
return [0] * ndim, [0] * ndim