uncbiag / mermaid

Image registration using pytorch
Other
178 stars 29 forks source link

How to write to nifti file? #148

Closed colddie closed 2 years ago

colddie commented 2 years ago

Hi,

How can write the registration result to a nifti file?

Thank you

hbgtjxzbbx commented 2 years ago

Hi colddie Thanks for your interest. We implemented some visualization and analysis code for saving intermediate results. but it need some extra settings. here is an easy workaround to get results out of simple_interface, which are in the format of torch tensor, and then you can save results via any toolkit you are familiar with. @marcniethammer do we have a more decent way to save the result?

si.register_images(blablabla...)
warped_images = si.get_warped_image()
transformation_maps = si.opt.optimizer.ssOpt.get_map()

an example on saving a warped image, e.g., warped_images[0,0], remember the first dimension refers to batch, second dim refer to channel (1 for gray image, 3 for transformation map). The reference image_path usually is set as the target image path.

def save_image(img_tensor, reference_image_path,output_path):
    img_np = img_tensor.detach().cpu().numpy()
    img_ref = sitk.ReadImage(reference_image_path)
    spacing_ref = img_ref.GetSpacing()
    direc_ref = img_ref.GetDirection()
    orig_ref = img_ref.GetOrigin()
    img_itk = sitk.GetImageFromArray(img_np)
    img_itk.SetSpacing(spacing_ref)
    img_itk.SetDirection(direc_ref)
    img_itk.SetOrigin(orig_ref)
    sitk.WriteImage(img_itk,output_path)
marcniethammer commented 2 years ago

This should all be handled via the fileio class. It Uses itk to write out files.

https://github.com/uncbiag/mermaid/blob/master/mermaid/fileio.py