Skip to content

Commit c992649

Browse files
committed
WIP: Save SpatialImages into HDF5 files.
Using a "with" statement to open the hdf files. To access the dataset values ".values" is old, changed to [()].
1 parent c507949 commit c992649

File tree

1 file changed

+23
-21
lines changed

1 file changed

+23
-21
lines changed

Diff for: nibabel/hdfloadsave.py

+23-21
Original file line numberDiff line numberDiff line change
@@ -38,23 +38,28 @@ def nifti1img_to_hdf(fname, spatial_img, h5path='/img', append=True):
3838
append: bool
3939
True if you don't want to erase the content of the file
4040
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)
4149
"""
4250
mode = 'w'
4351
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'
5253

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()
5659

57-
f.close()
60+
hdr = spatial_img.get_header()
61+
for k in hdr.keys():
62+
h5img['data'].attrs[k] = hdr[k]
5863

5964

6065
def hdfgroup_to_nifti1image(fname, h5path):
@@ -69,16 +74,13 @@ def hdfgroup_to_nifti1image(fname, h5path):
6974
7075
@return: nibabel Nifti1Image
7176
"""
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'][()]
8082

81-
f.close()
83+
header = get_nifti1hdr_from_h5attrs(h5img['data'].attrs)
8284

8385
img = Nifti1Image(data, affine, header=header, extra=extra)
8486

0 commit comments

Comments
 (0)