@@ -38,23 +38,28 @@ def nifti1img_to_hdf(fname, spatial_img, h5path='/img', append=True):
38
38
append: bool
39
39
True if you don't want to erase the content of the file
40
40
if it already exists, False otherwise.
41
+
42
+ @note:
43
+ HDF5 open modes
44
+ >>> 'r' Readonly, file must exist
45
+ >>> 'r+' Read/write, file must exist
46
+ >>> 'w' Create file, truncate if exists
47
+ >>> 'w-' Create file, fail if exists
48
+ >>> 'a' Read/write if exists, create otherwise (default)
41
49
"""
42
50
mode = 'w'
43
51
if append :
44
- mode = 'r+'
45
-
46
- f = h5py .File (fname , mode )
47
-
48
- h5img = f .create_group (h5path )
49
- h5img ['data' ] = spatial_img .get_data ()
50
- h5img ['extra' ] = spatial_img .get_extra ()
51
- h5img ['affine' ] = spatial_img .get_affine ()
52
+ mode = 'a'
52
53
53
- hdr = spatial_img .get_header ()
54
- for k in hdr .keys ():
55
- h5img ['data' ].attrs [k ] = hdr [k ]
54
+ with h5py .File (fname , mode ) as f :
55
+ h5img = f .create_group (h5path )
56
+ h5img ['data' ] = spatial_img .get_data ()
57
+ h5img ['extra' ] = spatial_img .get_extra ()
58
+ h5img ['affine' ] = spatial_img .get_affine ()
56
59
57
- f .close ()
60
+ hdr = spatial_img .get_header ()
61
+ for k in hdr .keys ():
62
+ h5img ['data' ].attrs [k ] = hdr [k ]
58
63
59
64
60
65
def hdfgroup_to_nifti1image (fname , h5path ):
@@ -69,16 +74,13 @@ def hdfgroup_to_nifti1image(fname, h5path):
69
74
70
75
@return: nibabel Nifti1Image
71
76
"""
72
- f = h5py .File (fname , 'r' )
73
-
74
- h5img = f [h5path ]
75
- data = h5img ['data' ].value
76
- extra = h5img ['extra' ].value
77
- affine = h5img ['affine' ].value
78
-
79
- header = get_nifti1hdr_from_h5attrs (h5img ['data' ].attrs )
77
+ with h5py .File (fname , 'r' ) as f :
78
+ h5img = f [h5path ]
79
+ data = h5img ['data' ][()]
80
+ extra = h5img ['extra' ][()]
81
+ affine = h5img ['affine' ][()]
80
82
81
- f . close ( )
83
+ header = get_nifti1hdr_from_h5attrs ( h5img [ 'data' ]. attrs )
82
84
83
85
img = Nifti1Image (data , affine , header = header , extra = extra )
84
86
0 commit comments