File size: 1,267 Bytes
2ae34e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) OpenMMLab. All rights reserved.
import gzip
import io
import pickle

import numpy as np


def datafrombytes(content: bytes, backend: str = 'numpy') -> np.ndarray:
    """Data decoding from bytes.

    Args:
        content (bytes): The data bytes got from files or other streams.
        backend (str): The data decoding backend type. Options are 'numpy',
            'nifti' and 'pickle'. Defaults to 'numpy'.

    Returns:
        numpy.ndarray: Loaded data array.
    """
    if backend == 'pickle':
        data = pickle.loads(content)
    else:
        with io.BytesIO(content) as f:
            if backend == 'nifti':
                f = gzip.open(f)
                try:
                    from nibabel import FileHolder, Nifti1Image
                except ImportError:
                    print('nifti files io depends on nibabel, please run'
                          '`pip install nibabel` to install it')
                fh = FileHolder(fileobj=f)
                data = Nifti1Image.from_file_map({'header': fh, 'image': fh})
                data = Nifti1Image.from_bytes(data.to_bytes()).get_fdata()
            elif backend == 'numpy':
                data = np.load(f)
            else:
                raise ValueError
    return data