-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
array.py
2860 lines (2373 loc) · 118 KB
/
array.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.
"""
A collection of "vanilla" transforms for intensity adjustment.
"""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Callable, Iterable, Sequence
from functools import partial
from typing import Any
from warnings import warn
import numpy as np
import torch
from monai.config import DtypeLike
from monai.config.type_definitions import NdarrayOrTensor, NdarrayTensor
from monai.data.meta_obj import get_track_meta
from monai.data.ultrasound_confidence_map import UltrasoundConfidenceMap
from monai.data.utils import get_random_patch, get_valid_patch_size
from monai.networks.layers import GaussianFilter, HilbertTransform, MedianFilter, SavitzkyGolayFilter
from monai.transforms.transform import RandomizableTransform, Transform
from monai.transforms.utils import Fourier, equalize_hist, is_positive, rescale_array, soft_clip
from monai.transforms.utils_pytorch_numpy_unification import clip, percentile, where
from monai.utils.enums import TransformBackends
from monai.utils.misc import ensure_tuple, ensure_tuple_rep, ensure_tuple_size, fall_back_tuple
from monai.utils.module import min_version, optional_import
from monai.utils.type_conversion import convert_data_type, convert_to_dst_type, convert_to_tensor, get_equivalent_dtype
skimage, _ = optional_import("skimage", "0.19.0", min_version)
__all__ = [
"RandGaussianNoise",
"RandRicianNoise",
"ShiftIntensity",
"RandShiftIntensity",
"StdShiftIntensity",
"RandStdShiftIntensity",
"RandBiasField",
"ScaleIntensity",
"RandScaleIntensity",
"ScaleIntensityFixedMean",
"RandScaleIntensityFixedMean",
"NormalizeIntensity",
"ThresholdIntensity",
"ScaleIntensityRange",
"ClipIntensityPercentiles",
"AdjustContrast",
"RandAdjustContrast",
"ScaleIntensityRangePercentiles",
"MaskIntensity",
"DetectEnvelope",
"SavitzkyGolaySmooth",
"MedianSmooth",
"GaussianSmooth",
"RandGaussianSmooth",
"GaussianSharpen",
"RandGaussianSharpen",
"RandHistogramShift",
"GibbsNoise",
"RandGibbsNoise",
"KSpaceSpikeNoise",
"RandKSpaceSpikeNoise",
"RandCoarseTransform",
"RandCoarseDropout",
"RandCoarseShuffle",
"HistogramNormalize",
"IntensityRemap",
"RandIntensityRemap",
"ForegroundMask",
"ComputeHoVerMaps",
"UltrasoundConfidenceMapTransform",
]
class RandGaussianNoise(RandomizableTransform):
"""
Add Gaussian noise to image.
Args:
prob: Probability to add Gaussian noise.
mean: Mean or “centre” of the distribution.
std: Standard deviation (spread) of distribution.
dtype: output data type, if None, same as input image. defaults to float32.
sample_std: If True, sample the spread of the Gaussian distribution uniformly from 0 to std.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
prob: float = 0.1,
mean: float = 0.0,
std: float = 0.1,
dtype: DtypeLike = np.float32,
sample_std: bool = True,
) -> None:
RandomizableTransform.__init__(self, prob)
self.mean = mean
self.std = std
self.dtype = dtype
self.noise: np.ndarray | None = None
self.sample_std = sample_std
def randomize(self, img: NdarrayOrTensor, mean: float | None = None) -> None:
super().randomize(None)
if not self._do_transform:
return None
std = self.R.uniform(0, self.std) if self.sample_std else self.std
noise = self.R.normal(self.mean if mean is None else mean, std, size=img.shape)
# noise is float64 array, convert to the output dtype to save memory
self.noise, *_ = convert_data_type(noise, dtype=self.dtype)
def __call__(self, img: NdarrayOrTensor, mean: float | None = None, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
if randomize:
self.randomize(img=img, mean=self.mean if mean is None else mean)
if not self._do_transform:
return img
if self.noise is None:
raise RuntimeError("please call the `randomize()` function first.")
img, *_ = convert_data_type(img, dtype=self.dtype)
noise, *_ = convert_to_dst_type(self.noise, img)
return img + noise
class RandRicianNoise(RandomizableTransform):
"""
Add Rician noise to image.
Rician noise in MRI is the result of performing a magnitude operation on complex
data with Gaussian noise of the same variance in both channels, as described in
`Noise in Magnitude Magnetic Resonance Images <https://doi.org/10.1002/cmr.a.20124>`_.
This transform is adapted from `DIPY <https://github.com/dipy/dipy>`_.
See also: `The rician distribution of noisy mri data <https://doi.org/10.1002/mrm.1910340618>`_.
Args:
prob: Probability to add Rician noise.
mean: Mean or "centre" of the Gaussian distributions sampled to make up
the Rician noise.
std: Standard deviation (spread) of the Gaussian distributions sampled
to make up the Rician noise.
channel_wise: If True, treats each channel of the image separately.
relative: If True, the spread of the sampled Gaussian distributions will
be std times the standard deviation of the image or channel's intensity
histogram.
sample_std: If True, sample the spread of the Gaussian distributions
uniformly from 0 to std.
dtype: output data type, if None, same as input image. defaults to float32.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
prob: float = 0.1,
mean: Sequence[float] | float = 0.0,
std: Sequence[float] | float = 1.0,
channel_wise: bool = False,
relative: bool = False,
sample_std: bool = True,
dtype: DtypeLike = np.float32,
) -> None:
RandomizableTransform.__init__(self, prob)
self.prob = prob
self.mean = mean
self.std = std
self.channel_wise = channel_wise
self.relative = relative
self.sample_std = sample_std
self.dtype = dtype
self._noise1: NdarrayOrTensor
self._noise2: NdarrayOrTensor
def _add_noise(self, img: NdarrayOrTensor, mean: float, std: float):
dtype_np = get_equivalent_dtype(img.dtype, np.ndarray)
im_shape = img.shape
_std = self.R.uniform(0, std) if self.sample_std else std
self._noise1 = self.R.normal(mean, _std, size=im_shape).astype(dtype_np, copy=False)
self._noise2 = self.R.normal(mean, _std, size=im_shape).astype(dtype_np, copy=False)
if isinstance(img, torch.Tensor):
n1 = torch.tensor(self._noise1, device=img.device)
n2 = torch.tensor(self._noise2, device=img.device)
return torch.sqrt((img + n1) ** 2 + n2**2)
return np.sqrt((img + self._noise1) ** 2 + self._noise2**2)
def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta(), dtype=self.dtype)
if randomize:
super().randomize(None)
if not self._do_transform:
return img
if self.channel_wise:
_mean = ensure_tuple_rep(self.mean, len(img))
_std = ensure_tuple_rep(self.std, len(img))
for i, d in enumerate(img):
img[i] = self._add_noise(d, mean=_mean[i], std=_std[i] * d.std() if self.relative else _std[i])
else:
if not isinstance(self.mean, (int, float)):
raise RuntimeError(f"If channel_wise is False, mean must be a float or int, got {type(self.mean)}.")
if not isinstance(self.std, (int, float)):
raise RuntimeError(f"If channel_wise is False, std must be a float or int, got {type(self.std)}.")
std = self.std * img.std().item() if self.relative else self.std
if not isinstance(std, (int, float)):
raise RuntimeError(f"std must be a float or int number, got {type(std)}.")
img = self._add_noise(img, mean=self.mean, std=std)
return img
class ShiftIntensity(Transform):
"""
Shift intensity uniformly for the entire image with specified `offset`.
Args:
offset: offset value to shift the intensity of image.
safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(self, offset: float, safe: bool = False) -> None:
self.offset = offset
self.safe = safe
def __call__(self, img: NdarrayOrTensor, offset: float | None = None) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
offset = self.offset if offset is None else offset
out = img + offset
out, *_ = convert_data_type(data=out, dtype=img.dtype, safe=self.safe)
return out
class RandShiftIntensity(RandomizableTransform):
"""
Randomly shift intensity with randomly picked offset.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self, offsets: tuple[float, float] | float, safe: bool = False, prob: float = 0.1, channel_wise: bool = False
) -> None:
"""
Args:
offsets: offset range to randomly shift.
if single number, offset value is picked from (-offsets, offsets).
safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`.
prob: probability of shift.
channel_wise: if True, shift intensity on each channel separately. For each channel, a random offset will be chosen.
Please ensure that the first dimension represents the channel of the image if True.
"""
RandomizableTransform.__init__(self, prob)
if isinstance(offsets, (int, float)):
self.offsets = (min(-offsets, offsets), max(-offsets, offsets))
elif len(offsets) != 2:
raise ValueError(f"offsets should be a number or pair of numbers, got {offsets}.")
else:
self.offsets = (min(offsets), max(offsets))
self._offset = self.offsets[0]
self.channel_wise = channel_wise
self._shifter = ShiftIntensity(self._offset, safe)
def randomize(self, data: Any | None = None) -> None:
super().randomize(None)
if not self._do_transform:
return None
if self.channel_wise:
self._offset = [self.R.uniform(low=self.offsets[0], high=self.offsets[1]) for _ in range(data.shape[0])] # type: ignore
else:
self._offset = self.R.uniform(low=self.offsets[0], high=self.offsets[1])
def __call__(self, img: NdarrayOrTensor, factor: float | None = None, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
Args:
img: input image to shift intensity.
factor: a factor to multiply the random offset, then shift.
can be some image specific value at runtime, like: max(img), etc.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
if randomize:
self.randomize(img)
if not self._do_transform:
return img
ret: NdarrayOrTensor
if self.channel_wise:
out = []
for i, d in enumerate(img):
out_channel = self._shifter(d, self._offset[i] if factor is None else self._offset[i] * factor) # type: ignore
out.append(out_channel)
ret = torch.stack(out) # type: ignore
else:
ret = self._shifter(img, self._offset if factor is None else self._offset * factor)
return ret
class StdShiftIntensity(Transform):
"""
Shift intensity for the image with a factor and the standard deviation of the image
by: ``v = v + factor * std(v)``.
This transform can focus on only non-zero values or the entire image,
and can also calculate the std on each channel separately.
Args:
factor: factor shift by ``v = v + factor * std(v)``.
nonzero: whether only count non-zero values.
channel_wise: if True, calculate on each channel separately. Please ensure
that the first dimension represents the channel of the image if True.
dtype: output data type, if None, same as input image. defaults to float32.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self, factor: float, nonzero: bool = False, channel_wise: bool = False, dtype: DtypeLike = np.float32
) -> None:
self.factor = factor
self.nonzero = nonzero
self.channel_wise = channel_wise
self.dtype = dtype
def _stdshift(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
ones: Callable
std: Callable
if isinstance(img, torch.Tensor):
ones = torch.ones
std = partial(torch.std, unbiased=False)
else:
ones = np.ones
std = np.std
slices = (img != 0) if self.nonzero else ones(img.shape, dtype=bool)
if slices.any():
offset = self.factor * std(img[slices])
img[slices] = img[slices] + offset
return img
def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta(), dtype=self.dtype)
if self.channel_wise:
for i, d in enumerate(img):
img[i] = self._stdshift(d) # type: ignore
else:
img = self._stdshift(img)
return img
class RandStdShiftIntensity(RandomizableTransform):
"""
Shift intensity for the image with a factor and the standard deviation of the image
by: ``v = v + factor * std(v)`` where the `factor` is randomly picked.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
factors: tuple[float, float] | float,
prob: float = 0.1,
nonzero: bool = False,
channel_wise: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
"""
Args:
factors: if tuple, the randomly picked range is (min(factors), max(factors)).
If single number, the range is (-factors, factors).
prob: probability of std shift.
nonzero: whether only count non-zero values.
channel_wise: if True, calculate on each channel separately.
dtype: output data type, if None, same as input image. defaults to float32.
"""
RandomizableTransform.__init__(self, prob)
if isinstance(factors, (int, float)):
self.factors = (min(-factors, factors), max(-factors, factors))
elif len(factors) != 2:
raise ValueError(f"factors should be a number or pair of numbers, got {factors}.")
else:
self.factors = (min(factors), max(factors))
self.factor = self.factors[0]
self.nonzero = nonzero
self.channel_wise = channel_wise
self.dtype = dtype
def randomize(self, data: Any | None = None) -> None:
super().randomize(None)
if not self._do_transform:
return None
self.factor = self.R.uniform(low=self.factors[0], high=self.factors[1])
def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta(), dtype=self.dtype)
if randomize:
self.randomize()
if not self._do_transform:
return img
shifter = StdShiftIntensity(
factor=self.factor, nonzero=self.nonzero, channel_wise=self.channel_wise, dtype=self.dtype
)
return shifter(img=img)
class ScaleIntensity(Transform):
"""
Scale the intensity of input image to the given value range (minv, maxv).
If `minv` and `maxv` not provided, use `factor` to scale image by ``v = v * (1 + factor)``.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
minv: float | None = 0.0,
maxv: float | None = 1.0,
factor: float | None = None,
channel_wise: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
"""
Args:
minv: minimum value of output data.
maxv: maximum value of output data.
factor: factor scale by ``v = v * (1 + factor)``. In order to use
this parameter, please set both `minv` and `maxv` into None.
channel_wise: if True, scale on each channel separately. Please ensure
that the first dimension represents the channel of the image if True.
dtype: output data type, if None, same as input image. defaults to float32.
"""
self.minv = minv
self.maxv = maxv
self.factor = factor
self.channel_wise = channel_wise
self.dtype = dtype
def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
Raises:
ValueError: When ``self.minv=None`` or ``self.maxv=None`` and ``self.factor=None``. Incompatible values.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
img_t = convert_to_tensor(img, track_meta=False)
ret: NdarrayOrTensor
if self.minv is not None or self.maxv is not None:
if self.channel_wise:
out = [rescale_array(d, self.minv, self.maxv, dtype=self.dtype) for d in img_t]
ret = torch.stack(out) # type: ignore
else:
ret = rescale_array(img_t, self.minv, self.maxv, dtype=self.dtype)
else:
ret = (img_t * (1 + self.factor)) if self.factor is not None else img_t
ret = convert_to_dst_type(ret, dst=img, dtype=self.dtype or img_t.dtype)[0]
return ret
class ScaleIntensityFixedMean(Transform):
"""
Scale the intensity of input image by ``v = v * (1 + factor)``, then shift the output so that the output image has the
same mean as the input.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
factor: float = 0,
preserve_range: bool = False,
fixed_mean: bool = True,
channel_wise: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
"""
Args:
factor: factor scale by ``v = v * (1 + factor)``.
preserve_range: clips the output array/tensor to the range of the input array/tensor
fixed_mean: subtract the mean intensity before scaling with `factor`, then add the same value after scaling
to ensure that the output has the same mean as the input.
channel_wise: if True, scale on each channel separately. `preserve_range` and `fixed_mean` are also applied
on each channel separately if `channel_wise` is True. Please ensure that the first dimension represents the
channel of the image if True.
dtype: output data type, if None, same as input image. defaults to float32.
"""
self.factor = factor
self.preserve_range = preserve_range
self.fixed_mean = fixed_mean
self.channel_wise = channel_wise
self.dtype = dtype
def __call__(self, img: NdarrayOrTensor, factor=None) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
Args:
img: the input tensor/array
factor: factor scale by ``v = v * (1 + factor)``
"""
factor = factor if factor is not None else self.factor
img = convert_to_tensor(img, track_meta=get_track_meta())
img_t = convert_to_tensor(img, track_meta=False)
ret: NdarrayOrTensor
if self.channel_wise:
out = []
for d in img_t:
if self.preserve_range:
clip_min = d.min()
clip_max = d.max()
if self.fixed_mean:
mn = d.mean()
d = d - mn
out_channel = d * (1 + factor)
if self.fixed_mean:
out_channel = out_channel + mn
if self.preserve_range:
out_channel = clip(out_channel, clip_min, clip_max)
out.append(out_channel)
ret = torch.stack(out)
else:
if self.preserve_range:
clip_min = img_t.min()
clip_max = img_t.max()
if self.fixed_mean:
mn = img_t.mean()
img_t = img_t - mn
ret = img_t * (1 + factor)
if self.fixed_mean:
ret = ret + mn
if self.preserve_range:
ret = clip(ret, clip_min, clip_max)
ret = convert_to_dst_type(ret, dst=img, dtype=self.dtype or img_t.dtype)[0]
return ret
class RandScaleIntensityFixedMean(RandomizableTransform):
"""
Randomly scale the intensity of input image by ``v = v * (1 + factor)`` where the `factor`
is randomly picked. Subtract the mean intensity before scaling with `factor`, then add the same value after scaling
to ensure that the output has the same mean as the input.
"""
backend = ScaleIntensityFixedMean.backend
def __init__(
self,
prob: float = 0.1,
factors: Sequence[float] | float = 0,
fixed_mean: bool = True,
preserve_range: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
"""
Args:
factors: factor range to randomly scale by ``v = v * (1 + factor)``.
if single number, factor value is picked from (-factors, factors).
preserve_range: clips the output array/tensor to the range of the input array/tensor
fixed_mean: subtract the mean intensity before scaling with `factor`, then add the same value after scaling
to ensure that the output has the same mean as the input.
channel_wise: if True, scale on each channel separately. `preserve_range` and `fixed_mean` are also applied
on each channel separately if `channel_wise` is True. Please ensure that the first dimension represents the
channel of the image if True.
dtype: output data type, if None, same as input image. defaults to float32.
"""
RandomizableTransform.__init__(self, prob)
if isinstance(factors, (int, float)):
self.factors = (min(-factors, factors), max(-factors, factors))
elif len(factors) != 2:
raise ValueError("factors should be a number or pair of numbers.")
else:
self.factors = (min(factors), max(factors))
self.factor = self.factors[0]
self.fixed_mean = fixed_mean
self.preserve_range = preserve_range
self.dtype = dtype
self.scaler = ScaleIntensityFixedMean(
factor=self.factor, fixed_mean=self.fixed_mean, preserve_range=self.preserve_range, dtype=self.dtype
)
def randomize(self, data: Any | None = None) -> None:
super().randomize(None)
if not self._do_transform:
return None
self.factor = self.R.uniform(low=self.factors[0], high=self.factors[1])
def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
if randomize:
self.randomize()
if not self._do_transform:
return convert_data_type(img, dtype=self.dtype)[0]
return self.scaler(img, self.factor)
class RandScaleIntensity(RandomizableTransform):
"""
Randomly scale the intensity of input image by ``v = v * (1 + factor)`` where the `factor`
is randomly picked.
"""
backend = ScaleIntensity.backend
def __init__(
self,
factors: tuple[float, float] | float,
prob: float = 0.1,
channel_wise: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
"""
Args:
factors: factor range to randomly scale by ``v = v * (1 + factor)``.
if single number, factor value is picked from (-factors, factors).
prob: probability of scale.
channel_wise: if True, scale on each channel separately. Please ensure
that the first dimension represents the channel of the image if True.
dtype: output data type, if None, same as input image. defaults to float32.
"""
RandomizableTransform.__init__(self, prob)
if isinstance(factors, (int, float)):
self.factors = (min(-factors, factors), max(-factors, factors))
elif len(factors) != 2:
raise ValueError(f"factors should be a number or pair of numbers, got {factors}.")
else:
self.factors = (min(factors), max(factors))
self.factor = self.factors[0]
self.channel_wise = channel_wise
self.dtype = dtype
def randomize(self, data: Any | None = None) -> None:
super().randomize(None)
if not self._do_transform:
return None
if self.channel_wise:
self.factor = [self.R.uniform(low=self.factors[0], high=self.factors[1]) for _ in range(data.shape[0])] # type: ignore
else:
self.factor = self.R.uniform(low=self.factors[0], high=self.factors[1])
def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
if randomize:
self.randomize(img)
if not self._do_transform:
return convert_data_type(img, dtype=self.dtype)[0]
ret: NdarrayOrTensor
if self.channel_wise:
out = []
for i, d in enumerate(img):
out_channel = ScaleIntensity(minv=None, maxv=None, factor=self.factor[i], dtype=self.dtype)(d) # type: ignore
out.append(out_channel)
ret = torch.stack(out) # type: ignore
else:
ret = ScaleIntensity(minv=None, maxv=None, factor=self.factor, dtype=self.dtype)(img)
return ret
class RandBiasField(RandomizableTransform):
"""
Random bias field augmentation for MR images.
The bias field is considered as a linear combination of smoothly varying basis (polynomial)
functions, as described in `Automated Model-Based Tissue Classification of MR Images of the Brain
<https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=811270>`_.
This implementation adapted from `NiftyNet
<https://github.com/NifTK/NiftyNet>`_.
Referred to `Longitudinal segmentation of age-related white matter hyperintensities
<https://www.sciencedirect.com/science/article/pii/S1361841517300257?via%3Dihub>`_.
Args:
degree: degree of freedom of the polynomials. The value should be no less than 1.
Defaults to 3.
coeff_range: range of the random coefficients. Defaults to (0.0, 0.1).
dtype: output data type, if None, same as input image. defaults to float32.
prob: probability to do random bias field.
"""
backend = [TransformBackends.NUMPY]
def __init__(
self,
degree: int = 3,
coeff_range: tuple[float, float] = (0.0, 0.1),
dtype: DtypeLike = np.float32,
prob: float = 0.1,
) -> None:
RandomizableTransform.__init__(self, prob)
if degree < 1:
raise ValueError(f"degree should be no less than 1, got {degree}.")
self.degree = degree
self.coeff_range = coeff_range
self.dtype = dtype
self._coeff = [1.0]
def _generate_random_field(self, spatial_shape: Sequence[int], degree: int, coeff: Sequence[float]):
"""
products of polynomials as bias field estimations
"""
rank = len(spatial_shape)
coeff_mat = np.zeros((degree + 1,) * rank)
coords = [np.linspace(-1.0, 1.0, dim, dtype=np.float32) for dim in spatial_shape]
if rank == 2:
coeff_mat[np.tril_indices(degree + 1)] = coeff
return np.polynomial.legendre.leggrid2d(coords[0], coords[1], coeff_mat)
if rank == 3:
pts: list[list[int]] = [[0, 0, 0]]
for i in range(degree + 1):
for j in range(degree + 1 - i):
for k in range(degree + 1 - i - j):
pts.append([i, j, k])
if len(pts) > 1:
pts = pts[1:]
np_pts = np.stack(pts)
coeff_mat[np_pts[:, 0], np_pts[:, 1], np_pts[:, 2]] = coeff
return np.polynomial.legendre.leggrid3d(coords[0], coords[1], coords[2], coeff_mat)
raise NotImplementedError("only supports 2D or 3D fields")
def randomize(self, img_size: Sequence[int]) -> None:
super().randomize(None)
if not self._do_transform:
return None
n_coeff = int(np.prod([(self.degree + k) / k for k in range(1, len(img_size) + 1)]))
self._coeff = self.R.uniform(*self.coeff_range, n_coeff).tolist()
def __call__(self, img: NdarrayOrTensor, randomize: bool = True) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
if randomize:
self.randomize(img_size=img.shape[1:])
if not self._do_transform:
return img
num_channels, *spatial_shape = img.shape
_bias_fields = np.stack(
[
self._generate_random_field(spatial_shape=spatial_shape, degree=self.degree, coeff=self._coeff)
for _ in range(num_channels)
],
axis=0,
)
img_np, *_ = convert_data_type(img, np.ndarray)
out: NdarrayOrTensor = img_np * np.exp(_bias_fields)
out, *_ = convert_to_dst_type(src=out, dst=img, dtype=self.dtype or img.dtype)
return out
class NormalizeIntensity(Transform):
"""
Normalize input based on the `subtrahend` and `divisor`: `(img - subtrahend) / divisor`.
Use calculated mean or std value of the input image if no `subtrahend` or `divisor` provided.
This transform can normalize only non-zero values or entire image, and can also calculate
mean and std on each channel separately.
When `channel_wise` is True, the first dimension of `subtrahend` and `divisor` should
be the number of image channels if they are not None.
Args:
subtrahend: the amount to subtract by (usually the mean).
divisor: the amount to divide by (usually the standard deviation).
nonzero: whether only normalize non-zero values.
channel_wise: if True, calculate on each channel separately, otherwise, calculate on
the entire image directly. default to False.
dtype: output data type, if None, same as input image. defaults to float32.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
subtrahend: Sequence | NdarrayOrTensor | None = None,
divisor: Sequence | NdarrayOrTensor | None = None,
nonzero: bool = False,
channel_wise: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
self.subtrahend = subtrahend
self.divisor = divisor
self.nonzero = nonzero
self.channel_wise = channel_wise
self.dtype = dtype
@staticmethod
def _mean(x):
if isinstance(x, np.ndarray):
return np.mean(x)
x = torch.mean(x.float())
return x.item() if x.numel() == 1 else x
@staticmethod
def _std(x):
if isinstance(x, np.ndarray):
return np.std(x)
x = torch.std(x.float(), unbiased=False)
return x.item() if x.numel() == 1 else x
def _normalize(self, img: NdarrayOrTensor, sub=None, div=None) -> NdarrayOrTensor:
img, *_ = convert_data_type(img, dtype=torch.float32)
if self.nonzero:
slices = img != 0
masked_img = img[slices]
if not slices.any():
return img
else:
slices = None
masked_img = img
_sub = sub if sub is not None else self._mean(masked_img)
if isinstance(_sub, (torch.Tensor, np.ndarray)):
_sub, *_ = convert_to_dst_type(_sub, img)
if slices is not None:
_sub = _sub[slices]
_div = div if div is not None else self._std(masked_img)
if np.isscalar(_div):
if _div == 0.0:
_div = 1.0
elif isinstance(_div, (torch.Tensor, np.ndarray)):
_div, *_ = convert_to_dst_type(_div, img)
if slices is not None:
_div = _div[slices]
_div[_div == 0.0] = 1.0
if slices is not None:
img[slices] = (masked_img - _sub) / _div
else:
img = (img - _sub) / _div
return img
def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
"""
Apply the transform to `img`, assuming `img` is a channel-first array if `self.channel_wise` is True,
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
dtype = self.dtype or img.dtype
if self.channel_wise:
if self.subtrahend is not None and len(self.subtrahend) != len(img):
raise ValueError(f"img has {len(img)} channels, but subtrahend has {len(self.subtrahend)} components.")
if self.divisor is not None and len(self.divisor) != len(img):
raise ValueError(f"img has {len(img)} channels, but divisor has {len(self.divisor)} components.")
for i, d in enumerate(img):
img[i] = self._normalize( # type: ignore
d,
sub=self.subtrahend[i] if self.subtrahend is not None else None,
div=self.divisor[i] if self.divisor is not None else None,
)
else:
img = self._normalize(img, self.subtrahend, self.divisor)
out = convert_to_dst_type(img, img, dtype=dtype)[0]
return out
class ThresholdIntensity(Transform):
"""
Filter the intensity values of whole image to below threshold or above threshold.
And fill the remaining parts of the image to the `cval` value.
Args:
threshold: the threshold to filter intensity values.
above: filter values above the threshold or below the threshold, default is True.
cval: value to fill the remaining parts of the image, default is 0.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(self, threshold: float, above: bool = True, cval: float = 0.0) -> None:
if not isinstance(threshold, (int, float)):
raise ValueError(f"threshold must be a float or int number, got {type(threshold)} {threshold}.")
self.threshold = threshold
self.above = above
self.cval = cval
def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
mask = img > self.threshold if self.above else img < self.threshold
res = where(mask, img, self.cval)
res, *_ = convert_data_type(res, dtype=img.dtype)
return res
class ScaleIntensityRange(Transform):
"""
Apply specific intensity scaling to the whole numpy array.
Scaling from [a_min, a_max] to [b_min, b_max] with clip option.
When `b_min` or `b_max` are `None`, `scaled_array * (b_max - b_min) + b_min` will be skipped.
If `clip=True`, when `b_min`/`b_max` is None, the clipping is not performed on the corresponding edge.
Args:
a_min: intensity original range min.
a_max: intensity original range max.
b_min: intensity target range min.
b_max: intensity target range max.
clip: whether to perform clip after scaling.
dtype: output data type, if None, same as input image. defaults to float32.
"""
backend = [TransformBackends.TORCH, TransformBackends.NUMPY]
def __init__(
self,
a_min: float,
a_max: float,
b_min: float | None = None,
b_max: float | None = None,
clip: bool = False,
dtype: DtypeLike = np.float32,
) -> None:
self.a_min = a_min
self.a_max = a_max
self.b_min = b_min
self.b_max = b_max
self.clip = clip
self.dtype = dtype
def __call__(self, img: NdarrayOrTensor) -> NdarrayOrTensor:
"""
Apply the transform to `img`.
"""
img = convert_to_tensor(img, track_meta=get_track_meta())
dtype = self.dtype or img.dtype
if self.a_max - self.a_min == 0.0:
warn("Divide by zero (a_min == a_max)", Warning)
if self.b_min is None:
return img - self.a_min
return img - self.a_min + self.b_min