ANTsX / ANTsPy

A fast medical imaging analysis library in Python with algorithms for registration, segmentation, and more.
https://antspyx.readthedocs.io
Apache License 2.0
627 stars 161 forks source link

Support for HDF5/NWB #683

Open DeanTM opened 1 month ago

DeanTM commented 1 month ago

I'm looking to save transforms in the same HDF5 file that contains my data, but in a different data group (so I can keep them together, share it as a single file, etc.).

Currently I'm building a workaround similar to that descibed in issue 318 but with nibabel in the middle

import ants, h5py, nibabel
reg=ants.registration( ants.image_read( ants.get_data("r16" ) ),  ants.image_read( ants.get_data("r16" ) ), 'SyN')

# Saving Transform
elastic_ni = nibabel.load(reg['fwdtransforms'][0])
with h5py.File("mydata.h5", "a") as my_h5:
    transform_group = my_h5.create_group("ants_transforms")
    elastic_group = transform_group.create_group('elastic')
    elastic_group.create_dataset("fdata", data=elastic_ni..get_fdata())
    elastic_group.create_dataset("affine", data=elastic_ni.affine)
    # EDIT: Some extra stuff needs to come in for the header too...

## Loading Transform
# instead of image_read, I can use nibabel to create a spatial image 
# warp=ants.image_read( reg['fwdtransforms'][0] )  # image not transform
with h5.File("mydata.h5", "r") as my_h5:
    nibabel_header = nibabel.Nifti1Header()
    for key in nibabel_header.keys():
        # ... populate header here
    warp = ants.from_nibabel(
            nibabel.spatialimages.SpatialImage(
                dataobj=my_h5['ants_transforms']['elastic']['fdata'],
                affine=my_h5['ants_transforms']['elastic']['affine'],
                header=nibabel_header))
warptx = ants.transform_from_displacement_field( warp )

However,

I also need to do a similar, but different, procedure for saving and loading the .mat affine transforms.

Would it be possible to save transforms as HDF5 file groups and load them directly? Something like,

## Saving Transform
with h5py.File("mydata.h5", "a") as my_h5:
    transform_group = my_h5.create_group("ants_transforms")
    _ = transform_group.create_group('elastic')
    warptx = save_transform_to_h5(my_h5, group='elastic')

## Loading Transform
with h5py.File("mydata.h5", "r") as my_h5:
    warptx = load_transform_from_h5(my_h5, group="elastic")
cookpa commented 1 month ago

I don't know if ITK supports image data and warps being in the same file. I would ask on the ITK discourse