-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnii_wrapper.py
More file actions
executable file
·2946 lines (2549 loc) · 135 KB
/
Copy pathnii_wrapper.py
File metadata and controls
executable file
·2946 lines (2549 loc) · 135 KB
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
from __future__ import annotations
import math
import traceback
import warnings
import zlib
from collections import deque
from collections.abc import Sequence
from enum import Enum
from math import ceil, floor
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, TypeVar, Union
import nibabel as nib
import nibabel.orientations as nio
import numpy as np
from nibabel import Nifti1Header, Nifti1Image # type: ignore
from skimage.measure import marching_cubes
from typing_extensions import Self
from TPTBox.core import bids_files
from TPTBox.core.compat import zip_strict
from TPTBox.core.internal.nii_help import _resample_from_to, secure_save
from TPTBox.core.nii_poi_abstract import Has_Grid
from TPTBox.core.nii_wrapper_math import NII_Math
from TPTBox.core.np_utils import (
_pad_to_parameters,
np_bbox_binary,
np_calc_boundary_mask,
np_calc_convex_hull,
np_calc_overlapping_labels,
np_center_of_mass,
np_compute_surface,
np_connected_components,
np_connected_components_per_label,
np_dilate_msk,
np_dilate_msk_euclid,
np_erode_msk,
np_erode_msk_euclid,
np_extract_label,
np_fill_holes,
np_fill_holes_global_with_majority_voting,
np_filter_connected_components,
np_get_connected_components_center_of_mass,
np_is_empty,
np_isin,
np_map_labels,
np_map_labels_based_on_majority_label_mask_overlap,
np_point_coordinates,
np_smooth_gaussian_labelwise,
np_translate_arr,
np_unique,
np_unique_withoutzero,
np_volume,
)
from TPTBox.core.vert_constants import (
AFFINE,
AX_CODES,
COORDINATE,
DIRECTIONS,
LABEL_MAP,
LABEL_REFERENCE,
MODES,
SHAPE,
ZOOMS,
_same_direction,
log,
logging,
v_name2idx,
)
from TPTBox.logger.log_file import Log_Type
if TYPE_CHECKING:
from stl.mesh import Mesh
from torch import device
MODES = Literal["constant", "nearest", "reflect", "wrap"]
_unpacked_nii = tuple[np.ndarray, AFFINE, nib.nifti1.Nifti1Header]
_formatwarning = warnings.formatwarning
def formatwarning_tb(*args, **kwargs) -> str:
"""Custom warning formatter that appends the current call stack to the warning message."""
s = "####################################\n"
s += _formatwarning(*args, **kwargs)
tb = traceback.format_stack()[:-3]
s += "".join(tb[:-1])
s += "####################################\n"
return s
_dtype_max = {
"int8": 128,
"uint8": 256,
"int16": 32768,
"uint16": 65536,
"int32": 2147483647,
"uint32": 4294967294,
} # uint32 not supported by nifty
_dtype_u = {"uint8", "uint16"}
_dtype_non_u = {"int8", "int16"}
def _check_if_nifty_is_lying_about_its_dtype(self: NII):
"""Infers the correct dtype by inspecting the actual value range of the NIfTI dataobj."""
change_dtype = False
arr = self.nii.dataobj
dtype = self._nii.dataobj.dtype # type: ignore
dtype_s = str(self._nii.dataobj.dtype)
try:
mi = np.min(arr)
except Exception:
return np.float32
ma = np.max(arr)
has_neg = mi < 0
max_v = _dtype_max.get(str(dtype), 0)
positive = str(dtype) in _dtype_u
if has_neg and positive:
warnings.warn(
f"Loaded NIfTY: incorrect dtype detected: {dtype}, but has negative values; min={mi}",
stacklevel=3,
)
change_dtype = True
positive = False
if not has_neg and self.seg:
positive = True
if str(dtype) in _dtype_non_u:
change_dtype = True
if ma > max_v and "float" not in dtype_s:
change_dtype = True
warnings.warn(
f"Loaded NIfTY: incorrect dtype detected: {dtype}, but has larger max values; max={max_v}",
stacklevel=3,
)
out_dtype = dtype
if dtype == np.float16:
warnings.warn(
f"Loaded NIfTY: incorrect dtype detected: {dtype} is not supported",
stacklevel=3,
)
out_dtype = np.float32
if "float" in dtype_s and not change_dtype:
pass
elif positive and change_dtype:
if ma < 256:
out_dtype = np.uint8
elif ma < 65536:
out_dtype = np.uint16
else:
out_dtype = np.int32
elif change_dtype:
ma_abs = np.max(np.abs(arr))
if ma_abs < 128:
out_dtype = np.int8
elif ma_abs < 32768:
out_dtype = np.int16
else:
out_dtype = np.int32
# print("check", out_dtype, change_dtype, positive, has_neg)
return out_dtype
warnings.formatwarning = formatwarning_tb
N = TypeVar("N", bound="NII")
Image_Reference = Union[bids_files.BIDS_FILE, Nifti1Image, Path, str, N]
Interpolateable_Image_Reference = Union[
bids_files.BIDS_FILE,
tuple[Nifti1Image, bool],
tuple[Path, bool],
tuple[str, bool],
N,
]
Proxy = tuple[tuple[int, int, int], np.ndarray]
suppress_dtype_change_printout_in_set_array = False
# fmt: off
class NII(NII_Math):
"""The `NII` class represents a NIfTI image and provides various methods for manipulating and analyzing NIfTI images. It supports loading and saving NIfTI images, rescaling and reorienting images, applying operations on segmentation masks, and more.
Example Usage:
```python
# Create an instance of NII class
nii = NII(nib.load('image.nii.gz'),seg=False)
# Get the shape of the image
shape = nii.shape
# Rescale the image to a new voxel spacing
rescaled = nii.rescale(voxel_spacing=(1, 1, 1))
# Reorient the image to a new orientation
reoriented = nii.reorient(axcodes_to=("P", "I", "R"))
# Apply a segmentation mask to the image
masked = nii.apply_mask(mask)
# Save the image to a new file
nii.save('output.nii.gz')
```
Main functionalities:
- Loading and saving NIfTI images
- Rescaling and reorienting images
- Applying operations on segmentation masks
Methods:
- `load`: Loads a NIfTI image from a file
- `load_bids`: Loads a NIfTI image from a BIDS file
- `shape`: Returns the shape of the image
- `dtype`: Returns the data type of the image
- `header`: Returns the header of the image
- `affine`: Returns the affine transformation matrix of the image
- `orientation`: Returns the orientation of the image
- `zoom`: Returns the voxel sizes of the image
- `origin`: Returns the origin of the image
- `rotation`: Returns the rotation matrix of the image
- `reorient`: Reorients the image to a new orientation
- `rescale`: Rescales the image to a new voxel spacing
- `apply_mask`: Applies a segmentation mask to the image
- `save`: Saves the image to a file
Fields:
- `nii`: The NIfTI image object
- `seg`: A flag indicating whether the image is a segmentation mask
- `c_val`: The default value for the segmentation mask
Note: This class assumes that the input NIfTI images are in the NIfTI-1 format.
"""
def __init__(self, nii: Nifti1Image|_unpacked_nii, seg=False,c_val=None, desc:str|None=None, info=None) -> None:
assert nii is not None
self.__divergent = False
self._checked_dtype = False
self.nii = nii
self.seg:bool = seg
self.c_val:float|None=c_val # default c_vale if seg is None
self.__min = None
self.info = info if info is not None else {}
self.set_description(desc)
if seg:
self._unpack()
if isinstance(self.dtype,np.floating):
self.set_dtype_("smallest_uint")
@classmethod
def from_numpy(cls, arr: np.ndarray, affine: np.ndarray, seg=False, c_val=None, desc:str|None=None, info=None) -> Self:
"""Creates an NII instance from a numpy array and an affine matrix.
Args:
arr: The voxel data array (shape must match the spatial dimensions implied by affine).
affine: A (4, 4) affine transformation matrix mapping voxel indices to world coordinates.
seg: Whether the image is a segmentation mask (integer-labelled). Defaults to False.
c_val: Background / fill value used during resampling. Defaults to None (inferred
from data for images; 0 for segmentations).
desc: Optional description string stored in the NIfTI header ``descrip`` field.
info: Optional dict of arbitrary metadata attached to this instance.
Returns:
A new NII wrapping the given array and affine.
"""
nii = nib.nifti1.Nifti1Image(arr,affine)
return NII(nii=nii, seg=seg, c_val=c_val, desc=desc, info=info)
@classmethod
def load(cls, path: Image_Reference, seg: bool, c_val: float | None = None) -> Self:
"""Loads a NIfTI image from a file path or image reference.
Args:
path: File path (str or Path), an existing NII, a Nifti1Image, or a BIDS_FILE
pointing to the image to load.
seg: Whether the image is a segmentation mask. When True the array dtype is
coerced to the smallest unsigned integer type that can hold all values.
c_val: Background / fill value. Defaults to None.
Returns:
A new NII loaded from the given path.
"""
nii= to_nii(path,seg)
if seg:
nii = nii.set_dtype("smallest_uint")
nii.c_val = c_val
return nii
@classmethod
def load_nrrd(cls, path: str | Path, seg: bool,verbos=False):
"""Load an NRRD file and convert it into a Nifti1Image object.
Args:
path (str | Path): The file path to the NRRD file to be loaded.
seg (bool): A flag indicating if the data represents segmentation data.
Returns:
NII: An NII object containing the loaded Nifti1Image and the segmentation flag.
Raises:
ImportError: If the `pynrrd` package is not installed.
FileNotFoundError: If the specified NRRD file cannot be found.
Example:
>>> nii = cls.load_nrrd("example.nrrd", seg=True)
>>> print(nii)
"""
try:
import nrrd # pip install pynrrd, if pynrrd is not already installed
except ModuleNotFoundError:
raise ImportError("The `pynrrd` package is required but not installed. Install it with `pip install pynrrd`.") from None
from TPTBox.core.internal.slicer_nrrd import load_slicer_nrrd
return load_slicer_nrrd(path,seg,verbos=verbos)
@classmethod
def load_bids(cls, nii_bids: bids_files.BIDS_FILE) -> NII:
"""Loads an NII from a BIDS_FILE object, inferring seg and c_val from the format.
Supports ``.nii``, ``.nii.gz``, ``.nrrd``, and any format readable by SimpleITK.
The ``seg`` flag is set to True when the BIDS file's interpolation order is 0
(i.e., it is a label map). CT images default to ``c_val=-1024``; others to 0.
Args:
nii_bids: A BIDS_FILE whose ``file`` dict contains at least one of the
supported image format keys.
Returns:
A new NII loaded from the BIDS file.
Raises:
AssertionError: If no readable image format is found in ``nii_bids``.
"""
nifty = None
if "nii" in nii_bids.file:
path = nii_bids.file['nii']
nifty = nib.load(path)
elif "nii.gz" in nii_bids.file:
path = nii_bids.file['nii.gz']
nifty = nib.load(path)
elif "nrrd" in nii_bids.file:
path = nii_bids.file['nrrd']
nifty = NII.load_nrrd(path,seg=False)
else:
import SimpleITK as sitk # noqa: N813
from TPTBox.core.sitk_utils import sitk_to_nib
for f in nii_bids.file:
try:
img = sitk.ReadImage(nii_bids.file[f])
nifty = sitk_to_nib(img)
except Exception:
pass
break
if nii_bids.get_interpolation_order() == 0:
seg = True
c_val=0
else:
seg = False
c_val = -1024 if "ct" in nii_bids.format.lower() else 0
assert nifty is not None, f"could not find {nii_bids}"
return NII(nifty,seg,c_val) # type: ignore
def _unpack(self) -> None:
"""Materialises the lazy nibabel dataobj into an in-memory numpy array."""
try:
if self.__unpacked:
return
try:
#if arr.dtype.fields is not None: # structured dtype (RGB)
# arr = np.stack([arr[name] for name in arr.dtype.names], axis=-1)
if not self._checked_dtype or self.seg:
dtype = _check_if_nifty_is_lying_about_its_dtype(self)
#print("unpack-nii",f"{self.seg=}",dtype)
self._checked_dtype = True
self._arr = np.asanyarray(self.nii.dataobj, dtype=dtype).copy()
else:
self._arr = np.asanyarray(self.nii.dataobj, dtype=self.nii.dataobj.dtype).copy() #type: ignore
except np.exceptions.DTypePromotionError:
arr = np.asarray(self.nii.dataobj)
if arr.dtype.fields is not None: # structured dtype (RGB)
self._arr = np.stack([arr[name] for name in arr.dtype.names], axis=-1)
else:
raise np.exceptions.DTypePromotionError(f"The DTypes <class '{self.nii.dataobj.dtype}'> do not have a common numerical DType. {np.asarray(self.nii.dataobj)}") from None
self._aff = self.nii.affine
self._header:Nifti1Header = self.nii.header # type: ignore
self.__unpacked = True
except EOFError as e:
raise EOFError(f"{self.nii.get_filename()}: {e!s}\nThe file is probably brocken beyond repair, due killing a software during nifty saving.") from None
except zlib.error as e:
raise EOFError(f"{self.nii.get_filename()}: {e!s}\nThe file is probably brocken beyond repair, due killing a software during nifty saving.") from None
except OSError as e:
raise EOFError(f"{self.nii.get_filename()}: {e!s}\nThe file is probably brocken beyond repair, due killing a software during nifty saving.") from None
@property
def nii_abstract(self) -> Nifti1Image|_unpacked_nii:
"""Returns the internal representation without forcing reconstruction of the Nifti1Image.
If the data has been unpacked (loaded into memory), returns the ``(array, affine, header)``
tuple. Otherwise returns the raw ``Nifti1Image``.
"""
if self.__unpacked:
return self._arr,self.affine,self.header
return self._nii
@property
def nii(self) -> Nifti1Image:
"""Returns the underlying Nifti1Image, reconstructing it if the in-memory array has diverged.
The reconstruction synchronises the header dtype and slope/intercept values with the
current array. Use ``nii_abstract`` if you want to avoid this reconstruction overhead.
"""
if self.__divergent:
self._nii = Nifti1Image(self._arr,self.affine,self.header)
if self.dtype == self._arr.dtype: #type: ignore
nii = Nifti1Image(self._arr,self.affine,self.header)
else:
if not suppress_dtype_change_printout_in_set_array:
log.print(f"'set_array' with different dtype: from {self.dtype} to {self._arr.dtype}",verbose=True) #type: ignore
nii2 = Nifti1Image(self._arr,self.affine,self.header)
nii2.set_data_dtype(self._arr.dtype)
nii = Nifti1Image(self._arr,nii2.affine,nii2.header) # type: ignore
if all(a is None for a in self.header.get_slope_inter()):
nii.header.set_slope_inter(1,self.get_c_val()) # type: ignore
#if self.header is not None:
# self.header.set_sform(self.affine, code=1)
self._nii = nii
self.__divergent = False
return self._nii
@nii.setter
def nii(self,nii:Nifti1Image|_unpacked_nii):
if isinstance(nii,tuple):
assert len(nii) == 3, nii
self.__divergent = True
self.__unpacked = True
arr, aff, header = nii
n = aff.shape[0]-1
if header is None or n != header['dim'][0]:
header = None
if len(arr.shape) != n:
# is there a dimesion with size 1?
arr = arr.squeeze()
# TODO try to get back to a saveabel state, if this did not work
if arr.dtype == np.uint64:#throws error
arr = arr.astype(np.uint32)
if arr.dtype == np.int64:#throws error
arr = arr.astype(np.int32)
self._arr = arr
self._aff = aff
self._checked_dtype = True
if header is not None:
header = header.copy()
header.set_sform(aff, code='aligned')
header.set_qform(aff, code='unknown')
header.set_data_dtype(arr.dtype)
rotation_zoom = aff[:n, :n]
zoom = np.sqrt(np.sum(rotation_zoom * rotation_zoom, axis=0))
#print(aff.shape,arr.shape,zoom)
header.set_zooms(zoom)
self._header = header
return
else:
nii = Nifti1Image(arr,aff)
self.__unpacked = False
self.__divergent = False
self._nii = nii
@property
def shape(self) -> tuple[int, int, int]:
"""Spatial shape of the image array (x, y, z), or more dims for 4-D images."""
if self.__unpacked:
return tuple(self._arr.shape) # type: ignore
return self.nii.shape # type: ignore
@property
def dtype(self) -> type:
"""NumPy dtype of the voxel data array."""
if self.__unpacked:
return self._arr.dtype # type: ignore
return self.nii.dataobj.dtype #type: ignore
@dtype.setter
def dtype(self, dtype:type):
self.set_dtype_(dtype)
@property
def header(self) -> Nifti1Header:
"""NIfTI-1 header associated with this image."""
if self.__unpacked:
return self._header
return self.nii.header # type: ignore
@property
def affine(self) -> AFFINE:
"""(4, 4) affine matrix mapping voxel indices to world (mm) coordinates."""
if self.__unpacked:
return self._aff # type: ignore
return self.nii.affine # type: ignore
@affine.setter
def affine(self,affine:np.ndarray):
self._unpack()
self.__divergent = True
self._aff = affine
@property
def orientation(self) -> AX_CODES:
"""Axis codes describing the image orientation, e.g. ``('R', 'A', 'S')``."""
ort = nio.io_orientation(self.affine)
return nio.ornt2axcodes(ort) # type: ignore
@orientation.setter
def orientation(self, value: AX_CODES):
self.reorient_(value, verbose=False)
@property
def dims(self) -> int:
"""Number of spatial dimensions (typically 3 for a standard NIfTI volume)."""
self._unpack()
return self.affine.shape[0]-1
@property
def zoom(self) -> ZOOMS:
"""Voxel sizes in mm along each spatial axis, e.g. ``(1.0, 1.0, 1.5)``."""
n = self.dims
rotation_zoom = self.affine[:n, :n]
zoom = np.sqrt(np.sum(rotation_zoom * rotation_zoom, axis=0)) if self.__divergent else self.header.get_zooms()
z = tuple(np.round(zoom,7))
if len(z) >= n:
z = z[:n]
#assert len(z) == 3,z
return z # type: ignore
@zoom.setter
def zoom(self, value: tuple[float, float, float]):
self.rescale_(value, verbose=False)
@property
def origin(self) -> tuple[float, float, float]:
"""World-space coordinates (in mm) of voxel index (0, 0, 0)."""
n = self.dims
z = tuple(np.round(self.affine[:n,n],7))
assert len(z) == 3
return z # type: ignore
@origin.setter
def origin(self,x:tuple[float, float, float]):
n = self.dims
self._unpack()
self.__divergent = True
affine = self._aff
affine[:n,n] = np.array(x) # type: ignore
self._aff = affine
@property
def rotation(self) -> np.ndarray:
"""Pure rotation matrix extracted from the affine (affine upper-left block divided by zoom)."""
n = self.dims
rotation_zoom = self.affine[:n, :n]
zoom = np.array(self.zoom)
rotation = rotation_zoom / zoom
return rotation
@property
def direction(self) -> list:
"""Flattened rotation matrix as a list (row-major), compatible with ITK/SimpleITK conventions."""
direction_matrix = self.rotation
direction_flat = direction_matrix.flatten().tolist()
return direction_flat
@property
def direction_itk(self) -> list:
"""Flattened rotation matrix with ITK LPS sign convention (first two rows negated)."""
a = np.array(self.direction)
a[:len(a)//3*2]*=-1
return a.tolist()
def split_4D_image_to_3D(self) -> list[NII]:
"""Splits a 4-D NIfTI image into a list of 3-D NII objects, one per volume.
Returns:
A list of NII objects, each containing one 3-D volume from the 4-D image.
The affine, header, seg flag, and c_val are copied from the original.
Raises:
AssertionError: If the image is not 4-D.
"""
assert self.get_num_dims() == 4,self.get_num_dims()
arr_4d = self.get_array()
out:list[NII] = []
for i in range(self.shape[-1]):
arr = arr_4d[...,i]
out.append(NII(Nifti1Image(arr, self.affine, self.header.copy()),self.seg,self.c_val,self.header['descrip']))
return out
@property
def orientation_ornt(self) -> np.ndarray:
"""Nibabel orientation array (shape ``(ndim, 2)``) encoding axis permutation and flip."""
return nio.io_orientation(self.affine)
def set_description(self, v: str | None) -> None:
"""Writes a description string into the NIfTI header ``descrip`` field.
Args:
v: Description string. When None, defaults to ``"seg"`` for segmentations
and ``"img"`` for regular images.
"""
if v is None:
self.header['descrip'] = "seg" if self.seg else "img"
else:
self.header['descrip'] = v
def get_c_val(self, default: float | None = None) -> float:
"""Returns the background / fill value for this image.
For segmentations the fill value is always 0. For images it is resolved from
``self.c_val``, the ``default`` argument, or the minimum value of the array
(computed lazily and cached), in that order.
Args:
default: Fallback value if ``self.c_val`` is None. Defaults to None.
Returns:
The background fill value as a float.
"""
if self.seg:
return 0
if self.c_val is not None:
return self.c_val
if default is not None:
return default
if self.__min is None:
self.__min = self.min()
return self.__min
def get_seg_array(self) -> np.ndarray:
"""Returns a copy of the voxel array, emitting a warning if ``seg`` is False.
Returns:
A copy of the underlying numpy array interpreted as a segmentation mask.
"""
if not self.seg:
warnings.warn(
"requested a segmentation array, but NII is not set as a segmentation", UserWarning, stacklevel=5
)
self._unpack()
return self._arr.copy() #type: ignore
def get_array(self) -> np.ndarray:
"""Returns a copy of the voxel data array.
Delegates to ``get_seg_array`` when ``seg=True`` (which adds a warning if
the flag is inconsistent), otherwise returns a plain copy.
Returns:
A copy of the underlying numpy array.
"""
if self.seg:
return self.get_seg_array()
self._unpack()
return self._arr.copy()
def numpy(self, *_args) -> np.ndarray:
"""Returns a copy of the voxel data as a numpy array (alias for ``get_array``)."""
return self.get_array()
def set_array(self, arr: np.ndarray | Self, inplace=False, verbose: logging = False, seg=None) -> Self: # noqa: ARG002
"""Returns an NII whose voxel data is replaced by ``arr``, preserving affine and header.
Note: This function works out-of-place by default, like all other methods.
Args:
arr: New voxel data. May be a numpy array or another NII (in which case
``get_array()`` is called automatically). Boolean arrays are cast to
``uint8``; float16 to float32; floating arrays are cast to int32 when
``self.seg`` is True.
inplace: If True, modifies this NII in place and returns ``self``.
Defaults to False.
verbose: Controls verbosity of dtype-change log messages. Defaults to False.
seg: Override the ``seg`` flag on the returned/modified NII. Defaults to None
(keep the current value).
Returns:
The modified NII (``self`` when ``inplace=True``, a new NII otherwise).
"""
if hasattr(arr,"get_array"):
arr = arr.get_array() # type: ignore
if arr.dtype == bool:
arr = arr.astype(np.uint8)
if arr.dtype == np.float16:
arr = arr.astype(np.float32)
if self.seg and isinstance(arr, (np.floating, float)):
arr = arr.astype(np.int32)
#if self.dtype == arr.dtype: #type: ignore
nii:_unpacked_nii = (arr,self.affine,self.header.copy())
self.header.set_data_dtype(arr.dtype)
#else:
# if not suppress_dtype_change_printout_in_set_array:
# log.print(f"'set_array' with different dtype: from {self.nii.dataobj.dtype} to {arr.dtype}",verbose=verbose) #type: ignore
# nii2 = Nifti1Image(self.get_array(),self.affine,self.header)
# nii2.set_data_dtype(arr.dtype)
# nii = (arr,nii2.affine,nii2.header) # type: ignore
#if all(a is None for a in self.header.get_slope_inter()):
# nii.header.set_slope_inter(1,self.get_c_val()) # type: ignore
if inplace:
if seg is not None:
self.seg = seg
self.nii = nii
return self
else:
return self.copy(nii,seg=seg) # type: ignore
def set_array_(self, arr: np.ndarray, verbose: logging = True) -> Self:
"""In-place variant of `set_array`."""
return self.set_array(arr,inplace=True,verbose=verbose)
def set_dtype(self, dtype: type | Literal['smallest_int', 'smallest_uint'] = np.float32, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe", inplace=False) -> Self:
"""Returns an NII with the voxel array cast to a different dtype.
Args:
dtype: Target dtype. The special strings ``"smallest_uint"`` and
``"smallest_int"`` select the smallest unsigned or signed integer
type that can hold all values in the current array.
Defaults to ``np.float32``.
order: Memory layout order passed to ``ndarray.astype``. Defaults to ``"K"``.
casting: Casting rule passed to ``ndarray.astype``. Defaults to ``"unsafe"``.
inplace: If True, converts in place and returns ``self``. Defaults to False.
Returns:
The NII with the new dtype (``self`` when ``inplace=True``, a new NII otherwise).
"""
sel = self if inplace else self.copy()
if dtype == "smallest_uint":
arr = self.get_array()
if arr.max()<256:
dtype = np.uint8
elif arr.max()<65536:
dtype = np.uint16
else:
dtype = np.int32
elif dtype == "smallest_int":
arr = self.get_array()
if arr.max()<128:
dtype = np.int8
elif arr.max()<32768:
dtype = np.int16
else:
dtype = np.int32
if self.__unpacked:
self._unpack()
sel._arr = sel._arr.astype(dtype)
sel.header.set_data_dtype(dtype)
else:
sel.nii.set_data_dtype(dtype)
if sel.nii.get_data_dtype() != self.dtype: #type: ignore
sel.nii = Nifti1Image(self.get_array().astype(dtype,casting=casting,order=order),self.affine,self.header)
return sel
def set_dtype_(self, dtype: type | Literal['smallest_uint', 'smallest_int'] = np.float32, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe") -> Self:
"""In-place variant of `set_dtype`."""
return self.set_dtype(dtype=dtype,order=order,casting=casting, inplace=True)
def astype(self, dtype, order: Literal["C", "F", "A", "K"] = 'K', casting: Literal["no", "equiv", "safe", "same_kind", "unsafe"] = "unsafe", subok=True, copy=True) -> Self:
"""NumPy-compatible dtype conversion wrapper.
When ``subok=True`` (default), delegates to ``set_dtype`` and returns an NII.
When ``subok=False``, returns a plain numpy array.
Args:
dtype: Target dtype, forwarded to ``set_dtype`` or ``ndarray.astype``.
order: Memory layout order. Defaults to ``"K"``.
casting: Casting rule. Defaults to ``"unsafe"``.
subok: If True, returns an NII; if False, returns a numpy array.
Defaults to True.
copy: When ``subok=True`` this maps to ``inplace`` (copy=True → inplace=True).
Defaults to True.
Returns:
An NII or numpy array with the requested dtype.
"""
if subok:
c = self.set_dtype(dtype,order=order,casting=casting, inplace=copy)
return c
else:
return self.get_array().astype(dtype,order=order,casting=casting, subok=subok,copy=copy)
def reorient(self:Self, axcodes_to: AX_CODES|str|None = ("P", "I", "R"), verbose:logging=False, inplace=False)-> Self:
"""Reorients the input Nifti image to the desired orientation, specified by the axis codes.
Args:
axcodes_to (tuple): A tuple of three strings representing the desired axis codes. Default value is ("P", "I", "R").
verbose (bool): If True, prints a message indicating the orientation change. Default value is False.
inplace (bool): If True, modifies the input image in place. Default value is False.
Returns:
If inplace is True, returns None. Otherwise, returns a new instance of the NII class representing the reoriented image.
Note:
The nibabel axes codes describe the direction, not the origin, of axes. The direction "PIR+" corresponds to the origin "ASL".
"""
# Note: nibabel axes codes describe the direction not origin of axes
# direction PIR+ = origin ASL
if isinstance(axcodes_to,str):
axcodes_to = tuple(axcodes_to)
if axcodes_to is not None:
aff = self.affine
ornt_fr = self.orientation_ornt
arr = self.get_array()
ornt_to = nio.axcodes2ornt(axcodes_to)
ornt_trans = nio.ornt_transform(ornt_fr, ornt_to)
if (ornt_fr == ornt_to).all():
log.print("Image is already rotated to", axcodes_to,verbose=verbose)
if inplace:
return self
return self.copy() # type: ignore
arr = nio.apply_orientation(arr, ornt_trans)
aff_trans = nio.inv_ornt_aff(ornt_trans, arr.shape)
new_aff = np.matmul(aff, aff_trans)
### Reset origin ###
flip = ornt_trans[:, 1]
change = ((-flip) + 1) / 2 # 1 if flip else 0
change = tuple(a * (s-1) for a, s in zip(change, self.shape))
new_aff[:3, 3] = nib.affines.apply_affine(aff,change) # type: ignore
######
#if self.header is not None:
# self.header.set_sform(new_aff, code=1)
new_img = arr, new_aff,self.header
log.print("Image reoriented from", nio.ornt2axcodes(ornt_fr), "to", axcodes_to,verbose=verbose)
else:
return self if not inplace else self.copy()
if inplace:
self.nii = new_img
return self
return self.copy(new_img) # type: ignore
def reorient_(self: Self, axcodes_to: AX_CODES | None = ("P", "I", "R"), verbose: logging = False) -> Self:
"""In-place variant of `reorient`."""
if axcodes_to is None:
return self
return self.reorient(axcodes_to=axcodes_to, verbose=verbose,inplace=True)
def compute_crop(self,minimum: float=0, dist: float = 0, use_mm=False, other_crop:tuple[slice,...]|None=None, maximum_size:tuple[slice,...]|int|tuple[int,...]|None=None, raise_error=True)->tuple[slice,slice,slice]:
"""Computes the minimum slice that removes unused space from the image and returns the corresponding slice tuple along with the origin shift required for centroids.
Args:
minimum (int): The minimum value of the array (0 for MRI, -1024 for CT). Default value is 0.
dist (int): The amount of padding to be added to the cropped image. Default value is 0.
use_mm: dist will be mm instead of number of voxels
other_crop (tuple[slice,...], optional): A tuple of slice objects representing the slice of an other image to be combined with the current slice. Default value is None.
raise_error: if crop is empty a "ValueError: bbox_nd: img is empty, cannot calculate a bbox" is produced. When False return None instead.
Returns:
ex_slice: A tuple of slice objects that need to be applied to crop the image.
origin_shift: A tuple of integers representing the shift required to obtain the centroids of the cropped image.
Note:
- The computed slice removes the unused space from the image based on the minimum value.
- The padding is added to the computed slice.
- If the computed slice reduces the array size to zero, a ValueError is raised.
- If other_crop is not None, the computed slice is combined with the slice of another image to obtain a common region of interest.
- Only None slice is supported for combining slices.
"""
d = np.around(dist / np.asarray(self.zoom)).astype(int) if use_mm else (int(dist),int(dist),int(dist))
array = self.get_array() #+ minimum
ex_slice = list(np_bbox_binary(array > minimum, px_dist=d,raise_error=raise_error))
if other_crop is not None:
assert all((a.step is None) for a in other_crop), 'Only None slice is supported for combining x'
ex_slice = [slice(max(a.start, b.start), min(a.stop, b.stop)) for a, b in zip(ex_slice, other_crop)]
if maximum_size is not None:
if isinstance(maximum_size,int):
maximum_size = (maximum_size,maximum_size,maximum_size)
for i, min_w in enumerate(maximum_size):
if isinstance(min_w,slice):
min_w = min_w.stop - min_w.start # noqa: PLW2901
curr_w = ex_slice[i].stop - ex_slice[i].start
dif = min_w - curr_w
if min_w > 0 and dif > 0:
new_start = ex_slice[i].start - floor(dif/2)
new_goal = ex_slice[i].stop + ceil(dif/2)
if new_goal > self.shape[i]:
new_start -= new_goal - self.shape[i]
new_goal = self.shape[i]
if new_start < 0:
new_goal -= new_start
new_start = 0
ex_slice[i] = slice(new_start,new_goal)
#origin_shift = tuple([int(ex_slice[i].start) for i in range(len(ex_slice))])
return tuple(ex_slice)# type: ignore
def apply_center_crop(self, center_shape: tuple[int, int, int], inplace=False, verbose: bool = False) -> Self:
"""Crops (and pads if necessary) the image to the given shape, centred on the image.
Args:
center_shape: Desired output shape ``(x, y, z)``. Axes smaller than the
current image are cropped; axes larger are zero-padded first.
inplace: If True, modifies this NII in place. Defaults to False.
verbose: If True, prints the crop/pad operations. Defaults to False.
Returns:
The NII cropped/padded to ``center_shape``.
"""
shp_x, shp_y, shp_z = self.shape
crop_x, crop_y, crop_z = center_shape
arr = self.get_array()
if crop_x > shp_x or crop_y > shp_y or crop_z > shp_z:
padding_ltrb = [
((crop_x - shp_x +1) // 2 if crop_x > shp_x else 0,(crop_x - shp_x) // 2 if crop_x > shp_x else 0),
((crop_y - shp_y +1) // 2 if crop_y > shp_y else 0,(crop_y - shp_y) // 2 if crop_y > shp_y else 0),
((crop_z - shp_z +1) // 2 if crop_z > shp_z else 0,(crop_z - shp_z) // 2 if crop_z > shp_z else 0),
]
arr_padded = np.pad(arr, padding_ltrb, "constant", constant_values=0) # PIL uses fill value 0
log.print(f"Pad from {self.shape} to {arr_padded.shape}", verbose=verbose)
shp_x, shp_y, shp_z = arr_padded.shape
if crop_x == shp_x and crop_y == shp_y and crop_z == shp_z:
return self.set_array(arr_padded)
else:
arr_padded = arr
crop_rel_x = round((shp_x - crop_x) / 2.0)
crop_rel_y = round((shp_y - crop_y) / 2.0)
crop_rel_z = round((shp_z - crop_z) / 2.0)
crop_slices = (slice(crop_rel_x, crop_rel_x + crop_x),slice(crop_rel_y, crop_rel_y + crop_y),slice(crop_rel_z, crop_rel_z + crop_z))
arr_cropped = arr_padded[crop_slices]
log.print(f"Center cropped from {arr_padded.shape} to {arr_cropped.shape}", verbose=verbose)
shp_x, shp_y, shp_z = arr_cropped.shape
assert crop_x == shp_x and crop_y == shp_y and crop_z == shp_z
return self.set_array(arr_cropped, inplace=inplace)
#return self.apply_crop(crop_slices, inplace=inplace)
def apply_crop_slice(self, *args, **qargs) -> Self:
"""Deprecated alias for `apply_crop`."""
import warnings
warnings.warn("apply_crop_slice id deprecated use apply_crop instead",stacklevel=5) #TODO remove in version 1.0
return self.apply_crop(*args,**qargs)
def apply_crop_slice_(self, *args, **qargs) -> Self:
"""Deprecated alias for `apply_crop_`."""
import warnings
warnings.warn("apply_crop_slice_ id deprecated use apply_crop_ instead",stacklevel=5) #TODO remove in version 1.0
return self.apply_crop_(*args,**qargs)
def apply_crop(self,ex_slice:tuple[slice,slice,slice]|Sequence[slice]|None , inplace=False) -> Self:
"""The apply_crop_slice function applies a given slice to reduce the Nifti image volume. If a list of slices is provided, it computes the minimum volume of all slices and applies it.
Args:
ex_slice (tuple[slice,slice,slice] | list[tuple[slice,slice,slice]]): A tuple or a list of tuples, where each tuple represents a slice for each axis (x, y, z).
inplace (bool, optional): If True, it applies the slice to the original image and returns it. If False, it returns a new NII object with the sliced image.
Returns:
NII: A new NII object containing the sliced image if inplace=False. Otherwise, it returns the original NII object after applying the slice.
"""
nii = self.nii.slicer[tuple(ex_slice)] if ex_slice is not None else self.nii_abstract
if inplace:
self.nii = nii
return self
x= self.copy(nii)
return x
def apply_crop_(self, ex_slice: tuple[slice, slice, slice] | Sequence[slice]) -> Self:
"""In-place variant of `apply_crop`."""
return self.apply_crop(ex_slice=ex_slice,inplace=True)
def pad_to(self, target_shape: list[int] | tuple[int, int, int] | Self, mode: MODES = "constant", crop=False, inplace=False) -> Self:
"""Pads (and optionally crops) the image to match a target shape.
Args:
target_shape: Desired output shape ``(x, y, z)`` or another NII whose
shape is used as the target.
mode: Padding mode (``"constant"``, ``"nearest"``, ``"reflect"``,
or ``"wrap"``). Defaults to ``"constant"``.
crop: If True and the image is larger than ``target_shape`` along any
axis, that axis is cropped first. Defaults to False.
inplace: If True, modifies this NII in place. Defaults to False.
Returns:
The NII padded (and optionally cropped) to ``target_shape``.
"""
if isinstance(target_shape, NII):
target_shape = target_shape.shape
padding, crop, requires_crop = _pad_to_parameters(self.shape, target_shape)
s = self
if crop and requires_crop:
s = s.apply_crop(tuple(crop),inplace=inplace)
return s.apply_pad(padding,inplace=inplace,mode=mode)
def apply_pad(self, padd: Sequence[tuple[int | None, int | None]] | int | None, mode: MODES = "constant", inplace=False, verbose: logging = True,) -> Self:
"""Pads the image with explicit per-axis ``(before, after)`` amounts.
The affine is updated so that the world-space origin is preserved (i.e. the
new voxel (0, 0, 0) corresponds to the same world coordinate as before).
Args:
padd: A sequence of ``(before, after)`` integer tuples, one per spatial
dimension. ``None`` as the ``before`` value means no padding on that
side. Pass ``None`` for the whole argument to skip padding entirely.
mode: Padding mode forwarded to ``numpy.pad``. Defaults to ``"constant"``.
In ``"constant"`` mode the fill value is ``self.get_c_val()``.
inplace: If True, modifies this NII in place. Defaults to False.
verbose: If True, logs the padding parameters. Defaults to True.
Returns:
The padded NII.
"""
#TODO add other modes
#TODO add testcases and options for modes
if padd is None:
return self if inplace else self.copy()
if isinstance(padd, (int, float)):
padd = int(padd)