inout.py 13.3 KB
Newer Older
inhuszar's avatar
inhuszar committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env fslpython
# -*- coding: utf-8 -*-

#   _______   _____   _____    _
#  |__   __| |_   _| |  __ \  | |
#     | |      | |   | |__) | | |
#     | |      | |   |  _  /  | |
#     | |     _| |_  | | \ \  | |____
#     |_|    |_____| |_|  \_\ |______|
#
# Copyright (C) 2018-2020 University of Oxford
# Part of the FMRIB Software Library (FSL)
# Author: Istvan N. Huszar
# Date: 21 June 2020


# SHBASECOPYRIGHT


inhuszar's avatar
inhuszar committed
20
21
22
__version__ = "2020.6.0"


inhuszar's avatar
inhuszar committed
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
# DEPENDENCIES

import logging
from attrdict import AttrMap


# TIRL IMPORTS

from tirl import settings as ts


# DEFINITIONS

from tirl.constants import *

logger = logging.getLogger("tirl.scripts.mnd.io")

DEFAULT_IMAGEINPUT_MODULE = {
    "file": "",
    "storage": "mem",
    "dtype": "<f4",
    "mask": {
        "file": None,
        "normalise": True,
        "function": None,
        "automask": {
            "thr": 0.0,
            "uthr": 1.0
        }
    },
    "resolution": 0.05,
    "actions": [],
    "preview": False,
    "export": True,
    "snapshot": True
}

DEFAULT_VOLUMEINPUT_MODULE = {
    "file": "",
    "storage": MEM,
    "dtype": ts.DEFAULT_FLOAT_TYPE,
    "usesqform": True,
    "mask": {
        "file": None,
        "normalise": True,
        "function": None,
        "automask": {
            "thr": 0.0,
            "uthr": 1.0
        }
    },
    "resolution": None,
    "actions": [],
    "preview": False,
    "export": True
}


# IMPLEMENTATION

def export(tirlobject, exportattr, default=None):
    """
    Saves a TIRLObject to file. If exportattr is a str, it is used as the file
    name, which will be overwritten. If exportattr is False, the default
    location is used. In case the default is None, it is the TWD directory of
    TIRL. If exportattr is False, the object is not saved.

    """
    from tirl.tirlobject import TIRLObject
    assert isinstance(tirlobject, TIRLObject), "Input is not a TIRLObject."

    if isinstance(exportattr, str):
        tirlobject.save(exportattr, overwrite=True)

    elif exportattr is True:
        import os
        from tirl import settings as ts
        if default is None:
            default = os.path.join(
                ts.TWD, tirlobject.name + ts.EXTENSIONS["TIRLObject"])
        tirlobject.save(default, overwrite=True)

    elif exportattr is False:
        pass

    else:
        raise TypeError(f"Invalid export attribute: {exportattr}")


def snapshot(timg, exportattr, default=None):
    """
    Same as the export, however the file is not a TImage dump, but a regular
    PNG image file.

    """
    from tirl.timage import TImage
    assert isinstance(timg, TImage), "Input is not a TImage."

    if isinstance(exportattr, str):
        timg.snapshot(exportattr, overwrite=True)

    elif exportattr is True:
        import os
        from tirl import settings as ts
        if default is None:
            default = os.path.join(ts.TWD, timg.name + ".png")
        timg.snapshot(default, overwrite=True)

    elif exportattr is False:
        pass

    else:
        raise TypeError(f"Invalid export attribute: {exportattr}")


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
def load_histology(**imageinputmodule):
    """
    Loads histology slide from file as TImage.

    :param q: configurations related to the histology input
    :type q: AttrMap

    """
    # Inintialise import parameters
    q = DEFAULT_IMAGEINPUT_MODULE.copy()
    q.update(imageinputmodule)
    q = AttrMap(q)

    import os
    from tirl.timage import TImage

    # Load image
    if q.file is None:
        raise FileNotFoundError("No histology image file was specified.")

    elif isinstance(q.file, str):
        if not os.path.isfile(q.file):
            raise FileNotFoundError(
                f"Histology image file does not exist: {q.file}")

        if q.file.lower().endswith(
                (ts.EXTENSIONS["TImage"], ts.EXTENSIONS["TIRLObject"])):
            img = load_timage(q.file)
            logger.info(f"Loaded histology image from {q.file}: {img}")
            return img

        elif q.file.lower().endswith(".svs"):
            import tirl.loader
            img = TImage.fromfile(q.file, storage=q.storage, dtype=q.dtype,
                                    loader=tirl.loader.OpenSlideLoader,
                                    loader_kwargs={"level": 2})
            logger.info(f"Loaded histology image from {q.file}: {img}")
        else:
            try:
                img = TImage.fromfile(q.file, storage=q.storage, dtype=q.dtype)
                logger.info(f"Loaded histology image from {q.file}: {img}")
            except Exception as exc:
                logger.error(exc.args)
                logger.error("Error while trying to load {}.")
                raise

    else:
        raise TypeError(f"Invalid image file specification: {q.file}")

    # ------------------------------------------------------------------------ #
    # The operations below are only carried out if the image was loaded from
    # an "ordinary" image file, not a TImage file.
    # ------------------------------------------------------------------------ #

    # Set resolution based on user input
    img.resolution = q.resolution
    logger.info(f"Pixel size of the histology image was set per user "
                f"specification to {q.resolution} [a.u./px].")

    # Set mask
    from tirl.scripts.mnd.image import set_mask
    set_mask(img, scope=dict(q).get("scope", globals()), **q.mask)

    # Perform operations
    from tirl.scripts.mnd.image import perform_image_operations
    perform_image_operations(img, *q.actions,
        scope=dict(q).get("scope", globals()), other=None)

    # Preview
    if q.preview is True:
        img.preview()

    # Export
    export(img, q.export, default=None)

    # Snapshot
    snapshot(img, q.snapshot, default=None)

    return img


inhuszar's avatar
inhuszar committed
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
def load_image(**imageinputmodule):
    """
    Loads 2D image as a TImage. If the input is a TImage file, it is loaded as
    is, without further operations performed. If the input is an image file,
    the function sets the mask, data type, resolution, and performs a
    prespecified set of operations on the image. Preview and export

    :param q: configurations related to the slice image input
    :type q: AttrMap

    """
    # Inintialise import parameters
    q = DEFAULT_IMAGEINPUT_MODULE.copy()
    q.update(imageinputmodule)
    q = AttrMap(q)

    import os
    from tirl.timage import TImage

    # Load image
    if q.file is None:
        raise FileNotFoundError("No image file was specified.")

    elif isinstance(q.file, str):
        if not os.path.isfile(q.file):
            raise FileNotFoundError(f"Image file does not exist: {q.file}")

        if q.file.lower().endswith(
                (ts.EXTENSIONS["TImage"], ts.EXTENSIONS["TIRLObject"])):
            img = load_timage(q.file)
            logger.info(f"Loaded image from {q.file}: {img}")
            return img

        else:
            try:
                img = TImage.fromfile(q.file, storage=q.storage, dtype=q.dtype)
                logger.info(f"Loaded volume from {q.file}: {img}")
            except Exception as exc:
                logger.error(exc.args)
                logger.error("Error while trying to load {}.")
                raise

    else:
262
        raise TypeError(f"Invalid image file specification: {q.file}")
inhuszar's avatar
inhuszar committed
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

    # ------------------------------------------------------------------------ #
    # The operations below are only carried out if the image was loaded from
    # an "ordinary" image file, not a TImage file.
    # ------------------------------------------------------------------------ #

    # Set resolution based on user input
    img.resolution = q.resolution
    logger.info(f"Pixel size of the brain slice photograph was set per user "
                f"specification to {q.resolution} [a.u./px].")

    # Set mask
    from tirl.scripts.mnd.image import set_mask
    set_mask(img, scope=dict(q).get("scope", globals()), **q.mask)

    # Perform operations
    from tirl.scripts.mnd.image import perform_image_operations
    perform_image_operations(img, *q.actions,
        scope=dict(q).get("scope", globals()), other=None)

    # Preview
    if q.preview is True:
        img.preview()

    # Export
    export(img, q.export, default=None)

    # Snapshot
    snapshot(img, q.snapshot, default=None)

    return img


def load_volume(**volumeinputmodule):
    """
    Loads image volume from file as TImage. If the input is a TImage, it is
    returned as it is. If the input is a NIfTI file, the resolution of the
    volume is initialised by user input. If the resolution is not specified by
    the user, by default, the volume is initialised by its best affine as
    specified in its NIfTI header. This default may be disabled
    (usesqform=False). If usesqform is False and no resolution is provided,
    only the voxel sizes will be imported from the NIfTI header to set the
    resolution.

    IMPORTANT NOTICE ABOUT ORIENTATION: as opposed to FSL, no flipping is
    performed in the volume that would enforce radiological orientation. As a
    result, all transformations calculated for the volume will be ambiguous
    without knowing the orientation of the volume.

    :param volumeinputmodule: configurations related to the volume input
    :type volumeinputmodule: AttrMap

    """
    import os
    import tirl
    from tirl.timage import TImage

    # Initialise module parameters
    q = DEFAULT_VOLUMEINPUT_MODULE.copy()
    q.update(volumeinputmodule)
    q = AttrMap(q)

    # Load image
    if q.file is None:
        raise FileNotFoundError("No volume file was specified.")

    elif isinstance(q.file, str):
        if not os.path.isfile(q.file):
            raise FileNotFoundError(f"Volume file does not exist: {q.file}")

        if q.file.lower().endswith((".nii", ".nii.gz")):
            volume = TImage.fromfile(q.file, storage=q.storage, dtype=q.dtype)
            logger.info(f"Loaded volume from {q.file}: {volume}")

        elif q.file.lower().endswith(
                (ts.EXTENSIONS["TImage"], ts.EXTENSIONS["TIRLObject"])):
            volume = load_timage(q.file)
            logger.info(f"Loaded volume from {q.file}: {volume}")
            return volume

        else:
            raise TypeError(f"Unsupported file type: {q.file}")

    else:
        raise TypeError(f"Invalid volume file specification: {q.file}")

    # ------------------------------------------------------------------------ #
    # The operations below are only carried out if the MRI was loaded from
    # a NIfTI file.
    # ------------------------------------------------------------------------ #

    # Set resolution based on user input and/or NIfTI header (if available)
    # User input overrides the header information. If the NIfTI header is used,
    # the volume is loaded with the best available affine, i.e. sform > qform
    # > Analyze convention.
    if q.resolution is not None:
        # Set resolution based on user input
        volume.resolution = q.resolution
        logger.info(f"Voxel size of the volume was set per user "
                    f"specification to {q.resolution} [a.u./vx].")
        return volume

    # "Fall back" to NIfTI header (if exists)
    # Note: normally the NIfTI header is way more accurate providing resolution
    # information than the users. Moreover, the NIfTI also specifies the
    # orientation, so falling back on this usually more specifc information
    # does not imply poorer quality. However, preference is given to the user
    # input for obvious reasons.
    try:
        hdr = volume.header["meta"]
        hdr.get_best_affine()
    except (KeyError, AttributeError):
        logger.warning("The voxel size of the volume was not specified and "
                       "a NIfTI header was not found either. Assuming "
                       "1 a.u./voxel isotropic resolution.")
        return volume

    # Get best affine from NIfTI header
    if (hdr.get_sform("code")[1] > 0) and q.usesqform:
        from tirl.transformations.linear.affine import TxAffine
        sform = hdr.get_sform()
        volume.resolution = 1
        volume.domain.chain.append(TxAffine(sform, name="sform"))
        logger.info(f"The volume was initialised with the following NIfTI "
                    f"sform affine: \n{sform}")

    elif (hdr.get_qform("code")[1] > 0) and q.usesqform:
        from tirl.transformations.linear.affine import TxAffine
        qform = hdr.get_qform()
        volume.resolution = 1
        volume.domain.chain.append(TxAffine(qform, name="qform"))
        logger.info(f"The volume was initialised with the following NIfTI "
                    f"qform affine: \n{qform}")

    else:
        zooms = hdr.get_zooms()
        volume.resolution = zooms
        logger.info(f"No qform/sform in NIfTI header. The resolution of the "
                    f"MRI volume was set to {tuple(zooms)} a.u./voxel.")

    # Set mask
    from tirl.scripts.mnd.image import set_mask
    set_mask(volume, scope=dict(q).get("scope", globals()), **q.mask)

    # Perform operations
    from tirl.scripts.mnd.image import perform_image_operations
    perform_image_operations(
        volume, *q.actions, scope=dict(q).get("scope", globals()), other=None)

    # Preview
    if q.preview is True:
        volume.preview()

    # Export
    export(volume, q.export, default=None)

    return volume


def load_timage(timgfile):
    import tirl
    timg = tirl.load(timgfile)
    from tirl.timage import TImage
    assert isinstance(timg, TImage)
    return timg