how obtain a .json file from (nifti file) .nii.gz file with python

1.9k Views Asked by At

I've just obtain a datset of 82 nifti files in the format .nii.gz,for every file i would like a .JSON file with the relative metadata information for each nifti file, how can i obtain it?

2

There are 2 best solutions below

0
On

You can use SimpleITK to read the metadata dictionary of a Nifti file, and then use python's JSON library to write it out.

For a single image:

import json
import SimpleITK as sitk

image_path = "folder/image.nii.gz"  # change this with your file

 # read image
itk_image = sitk.ReadImage(image_path) 

# get metadata dict
header = {k: itk_image.GetMetaData(k) for k in itk_image.GetMetaDataKeys()}

# save dict in 'header.json'
with open("header.json", "w") as outfile:
    json.dump(header, outfile, indent=4)

For every image in a single folder:

import json
from pathlib import Path
import SimpleITK as sitk

# get list of .nii.gz files inside the given folder
folder = Path("folder")  # change this
image_paths = filter(lambda f: str(f).endswith(".nii.gz"), folder.iterdir())

for image_path in image_paths:
    # read image
    itk_image = sitk.ReadImage(image_path)

    # get metadata dict
    header = {k: itk_image.GetMetaData(k) for k in itk_image.GetMetaDataKeys()}

    # create unique name for header file
    header_json_file = f"{image_path.name.replace('.nii.gz','')}_header.json"

    # save dict in header file
    with open(header_json_file, "w") as outfile:
        json.dump(header, outfile, indent=4)

See also this SimpleITK example

0
On
  • you can obtain header data:
import nibabel as nib
image = nib.load('file.nii.gz')  # read image
print(image.header)
  • if you want patient data (meta-data): age , name...
patient_data=str(image.header.extensions)
print(patient_data)