Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Save SpatialImages into HDF5 files. #215

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
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 [()].
alexsavio committed Nov 28, 2013
commit c99264943e8468f9d13abdb8c24664a2d9e3df95
44 changes: 23 additions & 21 deletions nibabel/hdfloadsave.py
Original file line number Diff line number Diff line change
@@ -38,23 +38,28 @@ def nifti1img_to_hdf(fname, spatial_img, h5path='/img', append=True):
append: bool
True if you don't want to erase the content of the file
if it already exists, False otherwise.

@note:
HDF5 open modes
>>> 'r' Readonly, file must exist
>>> 'r+' Read/write, file must exist
>>> 'w' Create file, truncate if exists
>>> 'w-' Create file, fail if exists
>>> 'a' Read/write if exists, create otherwise (default)
"""
mode = 'w'
if append:
mode = 'r+'

f = h5py.File(fname, mode)

h5img = f.create_group(h5path)
h5img['data'] = spatial_img.get_data()
h5img['extra'] = spatial_img.get_extra()
h5img['affine'] = spatial_img.get_affine()
mode = 'a'

hdr = spatial_img.get_header()
for k in hdr.keys():
h5img['data'].attrs[k] = hdr[k]
with h5py.File(fname, mode) as f:
h5img = f.create_group(h5path)
h5img['data'] = spatial_img.get_data()
h5img['extra'] = spatial_img.get_extra()
h5img['affine'] = spatial_img.get_affine()

f.close()
hdr = spatial_img.get_header()
for k in hdr.keys():
h5img['data'].attrs[k] = hdr[k]


def hdfgroup_to_nifti1image(fname, h5path):
@@ -69,16 +74,13 @@ def hdfgroup_to_nifti1image(fname, h5path):

@return: nibabel Nifti1Image
"""
f = h5py.File(fname, 'r')

h5img = f[h5path]
data = h5img['data'].value
extra = h5img['extra'].value
affine = h5img['affine'].value

header = get_nifti1hdr_from_h5attrs(h5img['data'].attrs)
with h5py.File(fname, 'r') as f:
h5img = f[h5path]
data = h5img['data'][()]
extra = h5img['extra'][()]
affine = h5img['affine'][()]

f.close()
header = get_nifti1hdr_from_h5attrs(h5img['data'].attrs)

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