如何获得一个.json文件从(nifti文件). nii.gz文件与python

von4xj4u  于 2022-11-26  发布在  Python
关注(0)|答案(2)|浏览(95)

我刚刚获得了一个82 nifti文件的数据集,格式为.nii.gz,对于每个文件,我想一个.JSON文件与每个nifti文件的相关元数据信息,我如何才能获得它?

wn9m85ua

wn9m85ua1#

可以使用SimpleITK读取Nifti文件的元数据字典,然后使用python的JSON library将其写出。
对于单个图像:

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)

对于单个文件夹中的每个图像:

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)

另请参阅this SimpleITK example

rjjhvcjd

rjjhvcjd2#

  • 您可以获取标题数据:
import nibabel as nib
image = nib.load('file.nii.gz')  # read image
print(image.header)
  • 如果您需要患者数据(元数据):年龄姓名。
patient_data=str(image.header.extensions)
print(patient_data)

相关问题