1
+ import os
1
2
import tempfile
2
3
from pathlib import Path
3
4
import gzip
@@ -11,16 +12,53 @@ def get_image(
11
12
data : np .ndarray = None ,
12
13
vox_sizes = (1.0 , 1.0 , 1.0 ),
13
14
qform = (1 , 2 , 3 , 1 ),
14
- compressed = False ,
15
+ compressed = None ,
15
16
) -> Path :
16
- """Create a random Nifti file to satisfy BIDS parsers"""
17
+ """Create a random Nifti file to satisfy BIDS parsers
18
+
19
+ Parameters
20
+ ----------
21
+ out_file : Path
22
+
23
+
24
+ """
17
25
if out_file is None :
18
26
out_file = Path (tempfile .mkdtemp ()) / "sample.nii"
27
+ out_file = Path (out_file )
28
+
29
+ suffix = "" .join (out_file .suffixes ) if out_file .suffixes else ""
30
+ out_stem = out_file .parent / out_file .name [:- len (suffix )]
31
+ if not suffix :
32
+ if compressed is None :
33
+ raise RuntimeError (
34
+ f"Must either specify the suffix of the 'out_file' ('{ out_file } ') or the "
35
+ "compression type ('compressed' option)"
36
+ )
37
+ elif compressed :
38
+ suffix = ".nii.gz"
39
+ else :
40
+ suffix = ".nii"
41
+ elif compressed is None :
42
+ compressed = suffix == ".nii.gz"
43
+ elif suffix == ".nii" :
44
+ if compressed :
45
+ raise RuntimeError (
46
+ f"Suffix '{ suffix } ' doesn't match the compressed being True"
47
+ )
48
+ elif suffix == ".nii.gz" :
49
+ if not compressed :
50
+ raise RuntimeError (
51
+ f"Suffix '{ suffix } ' doesn't match the compressed being True"
52
+ )
53
+ else :
54
+ raise RuntimeError (
55
+ f"Unrecognised suffix for nifti file, '{ suffix } '"
56
+ )
19
57
20
58
if data is None :
21
59
data = np .random .randint (0 , 1 , size = [10 , 10 , 10 ])
22
60
23
- uncompressed = out_file .with_suffix ('.nii' )
61
+ uncompressed = out_stem .with_suffix ('.nii' )
24
62
25
63
hdr = nb .Nifti1Header ()
26
64
hdr .set_data_shape (data .shape )
@@ -37,11 +75,12 @@ def get_image(
37
75
)
38
76
39
77
if compressed :
40
- out_file = out_file .with_suffix ('.nii.gz' )
78
+ out_path = out_stem .with_suffix ('.nii.gz' )
41
79
with open (uncompressed , 'rb' ) as f_in :
42
- with gzip .open (out_file , 'wb' ) as f_out :
80
+ with gzip .open (out_path , 'wb' ) as f_out :
43
81
shutil .copyfileobj (f_in , f_out )
82
+ os .unlink (uncompressed )
44
83
else :
45
- out_file = uncompressed
84
+ out_path = uncompressed
46
85
47
- return out_file
86
+ return out_path
0 commit comments