|
a |
|
b/ants/utils/sitk_to_ants.py |
|
|
1 |
import numpy as np |
|
|
2 |
import ants |
|
|
3 |
|
|
|
4 |
|
|
|
5 |
def from_sitk(sitk_image: "SimpleITK.Image") -> ants.ANTsImage: |
|
|
6 |
""" |
|
|
7 |
Converts a given SimpleITK image into an ANTsPy image |
|
|
8 |
|
|
|
9 |
Parameters |
|
|
10 |
---------- |
|
|
11 |
img: SimpleITK.Image |
|
|
12 |
|
|
|
13 |
Returns |
|
|
14 |
------- |
|
|
15 |
ants_image: ANTsImage |
|
|
16 |
""" |
|
|
17 |
import SimpleITK as sitk |
|
|
18 |
|
|
|
19 |
ndim = sitk_image.GetDimension() |
|
|
20 |
|
|
|
21 |
if ndim < 3: |
|
|
22 |
print("Dimensionality is less than 3.") |
|
|
23 |
return None |
|
|
24 |
|
|
|
25 |
direction = np.asarray(sitk_image.GetDirection()).reshape((3, 3)) |
|
|
26 |
spacing = list(sitk_image.GetSpacing()) |
|
|
27 |
origin = list(sitk_image.GetOrigin()) |
|
|
28 |
|
|
|
29 |
data = sitk.GetArrayViewFromImage(sitk_image) |
|
|
30 |
|
|
|
31 |
ants_img: ants.ANTsImage = ants.from_numpy( |
|
|
32 |
data=data.ravel(order="F").reshape(data.shape[::-1]), |
|
|
33 |
origin=origin, |
|
|
34 |
spacing=spacing, |
|
|
35 |
direction=direction, |
|
|
36 |
) |
|
|
37 |
|
|
|
38 |
return ants_img |
|
|
39 |
|
|
|
40 |
|
|
|
41 |
def to_sitk(ants_image: ants.ANTsImage) -> "SimpleITK.Image": |
|
|
42 |
""" |
|
|
43 |
Converts a given ANTsPy image into an SimpleITK image |
|
|
44 |
|
|
|
45 |
Parameters |
|
|
46 |
---------- |
|
|
47 |
ants_image: ANTsImage |
|
|
48 |
|
|
|
49 |
Returns |
|
|
50 |
------- |
|
|
51 |
img: SimpleITK.Image |
|
|
52 |
""" |
|
|
53 |
|
|
|
54 |
import SimpleITK as sitk |
|
|
55 |
|
|
|
56 |
data = ants_image.view() |
|
|
57 |
shape = ants_image.shape |
|
|
58 |
|
|
|
59 |
sitk_img = sitk.GetImageFromArray(data.ravel(order="F").reshape(shape[::-1])) |
|
|
60 |
sitk_img.SetOrigin(ants_image.origin) |
|
|
61 |
sitk_img.SetSpacing(ants_image.spacing) |
|
|
62 |
sitk_img.SetDirection(ants_image.direction.flatten()) |
|
|
63 |
return sitk_img |