File size: 4,564 Bytes
ecf08bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#    Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
#    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.

import nibabel as nib
from nibabel import io_orientation
from batchgenerators.utilities.file_and_folder_operations import *
import numpy as np
import os
from multiprocessing import Pool
import SimpleITK as sitk


def print_shapes(folder: str) -> None:
    for i in subfiles(folder, suffix='.nii.gz'):
        tmp = sitk.ReadImage(i)
        print(sitk.GetArrayFromImage(tmp).shape, tmp.GetSpacing())


def reorient_to_ras(image: str) -> None:
    """
    Will overwrite image!!!
    :param image:
    :return:
    """
    assert image.endswith('.nii.gz')
    origaffine_pkl = image[:-7] + '_originalAffine.pkl'
    if not isfile(origaffine_pkl):
        img = nib.load(image)
        original_affine = img.affine
        original_axcode = nib.aff2axcodes(img.affine)
        img = img.as_reoriented(io_orientation(img.affine))
        new_axcode = nib.aff2axcodes(img.affine)
        print(image.split('/')[-1], 'original axcode', original_axcode, 'now (should be ras)', new_axcode)
        nib.save(img, image)
        save_pickle((original_affine, original_axcode), origaffine_pkl)


def revert_reorientation(image: str) -> None:
    assert image.endswith('.nii.gz')
    expected_pkl = image[:-7] + '_originalAffine.pkl'
    assert isfile(expected_pkl), 'Must have a file with the original affine, as created by ' \
                                 'reorient_to_ras. Expected filename: %s' % \
                                 expected_pkl
    original_affine, original_axcode = load_pickle(image[:-7] + '_originalAffine.pkl')
    img = nib.load(image)
    before_revert = nib.aff2axcodes(img.affine)
    img = img.as_reoriented(io_orientation(original_affine))
    after_revert = nib.aff2axcodes(img.affine)
    print('before revert', before_revert, 'after revert', after_revert)
    restored_affine = img.affine
    assert np.all(np.isclose(original_affine, restored_affine)), 'restored affine does not match original affine, ' \
                                                                 'aborting!'
    nib.save(img, image)
    os.remove(expected_pkl)


def reorient_all_images_in_folder_to_ras(folder: str, num_processes: int = 8):
    p = Pool(num_processes)
    nii_files = subfiles(folder, suffix='.nii.gz', join=True)
    p.map(reorient_to_ras, nii_files)
    p.close()
    p.join()


def revert_orientation_on_all_images_in_folder(folder: str, num_processes: int = 8):
    p = Pool(num_processes)
    nii_files = subfiles(folder, suffix='.nii.gz', join=True)
    p.map(revert_reorientation, nii_files)
    p.close()
    p.join()


if __name__ == '__main__':
    """nib.as_closest_canonical()
    test_img = '/home/fabian/data/la_005_0000.nii.gz'
    test_img_reorient = test_img[:-7] + '_reorient.nii.gz'
    test_img_restored = test_img[:-7] + '_restored.nii.gz'

    img = nib.load(test_img)
    print('loaded original')
    print('shape', img.shape)
    print('affine', img.affine)
    original_affine = img.affine
    original_axcode = nib.aff2axcodes(img.affine)
    print('orientation', nib.aff2axcodes(img.affine))

    print('reorienting...')
    img = img.as_reoriented(io_orientation(img.affine))
    nib.save(img, test_img_reorient)

    print('now loading the reoriented img')
    img = nib.load(test_img_reorient)
    print('loaded original')
    print('shape', img.shape)
    print('affine', img.affine)
    reorient_affine = img.affine
    reorient_axcode = nib.aff2axcodes(img.affine)
    print('orientation', nib.aff2axcodes(img.affine))

    print('restoring original geometry')
    img = img.as_reoriented(io_orientation(original_affine))
    restored_affine = img.affine
    nib.save(img, test_img_restored)

    print('now loading the restored img')
    img = nib.load(test_img_restored)
    print('loaded original')
    print('shape', img.shape)
    print('affine', img.affine)
    print('orientation', nib.aff2axcodes(img.affine))"""