简体   繁体   English

如何将 nift 文件夹转换为 png 图像?

[英]how to convert a nift folder to png images?

* library *图书馆

there is a mostly known library imported from NumPy and imageio import NumPy as np import os import nibabel as nib import imageio // method where I have I write code to convert a nift to png有一个从 NumPy 和 imageio import NumPy as np import os import nibabel as nib import imageio // 方法我写代码将 nift 转换为 png
Method convert a nift(.nii) image to png image def nii_to_image(niifile): filenames = os.listdir(filepath) #read nii folder slice_trans = [] #filename is the path of nii image Method convert a nift(.nii) image to png image def nii_to_image(niifile): filenames = os.listdir(filepath) #read nii folder slice_trans = [] #filename是nii image的路径

  for f in filenames:
                          #Start reading nii files
                   img_path = os.path.join(filepath, f)
                   img = nib.load(img_path) #read nii
                   img_fdata = img.get_fdata()
                   fname = f.replace('.nii','') 
# Remove the nickname of nii
                   img_f_path = os.path.join(imgfile, fname)
                          #Create a folder corresponding to the image of nii
                   if not os.path.exists(img_f_path):
                     os.mkdir(img_f_path) #New folder
          
                          #  to image
                   (x,y,z) = img.shape
                   for i in range(z): #x is the sequence of images
                     silce = img_fdata[i, :, :] #Select which direction the slice can be
                     imageio.imwrite(os.path.join(img_f_path,'{}.png'.format(i)), silce) #Save image
     #main function where fill path was gived
   

main主要的

 if __name__ == '__main__':
             filepath = '/content/drive/MyDrive/sem 8/dataset/pr' 
             imgfile = '/content/drive/MyDrive/sem 8/dataset/propi'
             nii_to_image(filepath)

After you load the nifti file as NumPy array as you did, run on every slice (z from img.shape) and then save the array to png.像您一样将 nifti 文件加载为 NumPy 数组后,在每个切片(来自 img.shape 的 z)上运行,然后将数组保存到 png。

Make sure that when you run on each slice you save only the existing one (the z_slice_number):确保在每个切片上运行时只保存现有切片(z_slice_number):

    slice = img_fdata[:, :, z_slice_numer]

And to save this slice you can do as follow (or another way from here ):要保存此切片,您可以执行以下操作(或此处的其他方式):

    matplotlib.image.imsave('name.png', slice)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM