首页 > 其他分享 >nii转dicom,需要一个同序列dicom图像模板作为参考

nii转dicom,需要一个同序列dicom图像模板作为参考

时间:2024-06-17 09:45:09浏览次数:29  
标签:slice nifti dicom nii dir file path 模板

``

import nibabel
import numpy as np
import pydicom
import os
from tqdm import tqdm


def convertNsave(arr, file_dir, index=0, slice_thickness=1.0, pixel_spacing=(1.0, 1.0)):
    """
    `arr`: parameter will take a numpy array that represents only one slice.
    `file_dir`: parameter will take the path to save the slices
    `index`: parameter will represent the index of the slice, so this parameter will be used to put
    the name of each slice while using a for loop to convert all the slices
    `slice_thickness`: parameter for slice thickness in mm
    `pixel_spacing`: parameter for pixel spacing in mm
    """

    # Read a template DICOM file
    dicom_file = pydicom.dcmread('D:\\edge download\\lunao\\CHI_SHENG_TAI\\T2\\DICOM\\IM_0001')
    arr = arr.astype('uint16')

    # Rotate the image 90 degrees clockwise
    arr = np.rot90(arr, -1)

    # Update the necessary DICOM metadata
    dicom_file.Rows = arr.shape[0]
    dicom_file.Columns = arr.shape[1]
    dicom_file.PhotometricInterpretation = "MONOCHROME2"
    dicom_file.SamplesPerPixel = 1
    dicom_file.BitsStored = 16
    dicom_file.BitsAllocated = 16
    dicom_file.HighBit = 15
    dicom_file.PixelRepresentation = 1
    dicom_file.InstanceNumber = index + 1
    dicom_file.SliceLocation = index * slice_thickness
    dicom_file.SliceThickness = slice_thickness
    dicom_file.SpacingBetweenSlices = slice_thickness
    dicom_file.PixelSpacing = [str(pixel_spacing[0]), str(pixel_spacing[1])]

    # Update the Image Position (Patient) and Image Orientation (Patient) if necessary
    dicom_file.ImagePositionPatient = [0, 0, index * slice_thickness]
    dicom_file.ImageOrientationPatient = [1, 0, 0, 0, 1, 0]

    # Convert numpy array to bytes
    dicom_file.PixelData = arr.tobytes()

    # Save the new DICOM file
    dicom_file.save_as(os.path.join(file_dir, f'slice{index:04d}.dcm'))


def nifti2dicom_1file(nifti_dir, out_dir):
    """
    This function is to convert only one nifti file into dicom series

    `nifti_dir`: the path to the one nifti file
    `out_dir`: the path to output
    """

    # Load the NIfTI file
    nifti_file = nibabel.load(nifti_dir)
    nifti_array = nifti_file.get_fdata()
    number_slices = nifti_array.shape[2]

    # Get pixel spacing and slice thickness from the NIfTI header if available
    pixel_spacing = nifti_file.header.get_zooms()[:2]
    slice_thickness = nifti_file.header.get_zooms()[2]

    # Convert each slice to DICOM
    for slice_ in tqdm(range(number_slices)):
        convertNsave(nifti_array[:, :, slice_], out_dir, slice_, slice_thickness, pixel_spacing)


def nifti2dicom_mfiles(nifti_dir, out_dir=''):
    """
    This function is to convert multiple nifti files into dicom files

    `nifti_dir`: You enter the global path to all of the nifti files here.
    `out_dir`: Put the path to where you want to save all the dicoms here.

    PS: Each nifti file's folders will be created automatically, so you do not need to create an empty folder for each patient.
    """

    files = os.listdir(nifti_dir)
    for file in files:
        in_path = os.path.join(nifti_dir, file)
        out_path = os.path.join(out_dir, file)
        os.makedirs(out_path, exist_ok=True)
        nifti2dicom_1file(in_path, out_path)


if __name__ == '__main__':
    # Convert a single NIfTI file to a DICOM series
    input_image = "C:\\Users\\wangyanming3\\Desktop\\nnUNet-2.4.1\\input\\BraTS_0001.nii.gz"
    output_path = "C:\\Users\\wangyanming3\\Desktop\\nnUNet-2.4.1\\output\\0001"
    os.makedirs(output_path, exist_ok=True)
    nifti2dicom_1file(input_image, output_path)

标签:slice,nifti,dicom,nii,dir,file,path,模板
From: https://www.cnblogs.com/cupwym/p/18251779

相关文章

  • [转]32th@探索C++的模板元编程:揭秘零运行时开销的高性能编程技术@20240616
    C++的模板元编程是一种强大的编程技术,它能够在编译时进行计算,生成高效的代码,而且不需要任何运行时开销。这种技术被广泛应用于高性能计算、游戏开发、金融等领域,是C++程序员必须掌握的技能之一。本文将深入探讨C++模板元编程的原理和实现方式,并通过代码案例来展示其强大的功能。相......
  • 设计模式-模板方法模式
    模板方法模式模板方法模式(TemplateMethodPattern),又叫模板模式,是指定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构即可重新定义该算法的默写特定步骤,属于行为型设计模式。模板方法的本质是抽象封装流程,该流程由几个步骤组成,具体步骤可......
  • 首途第三十三套清新简约卡片风格蓝紫渐变色短视频模板 | 苹果CMSV10主题
    下载地址:首途第三十三套清新简约卡片风格蓝紫渐变色短视频模板|苹果CMSV10主题首途第三十三套清新简约卡片风格蓝紫渐变色短视频模板|苹果CMSV10主题我们的简约风格,以纯洁的白色和深邃的紫色为主色调,为您提供了一种清新、时尚的浏览体验。在这个简洁而美丽的界面中,您可以......
  • 自用Beamer模板(英文版)
    \documentclass[aspectratio=43]{beamer}\usetheme{CambridgeUS}\usepackage[fontsize=10pt]{fontsize}%更好看的数学字母\usefonttheme{professionalfonts}%把enumerate前的圆球(bullet)去掉,也就是设置成默认符号就行\setbeamertemplate{enumerateitems}[defaul......
  • 基础算法模板
    目录基础算法整数二分浮点数二分归并排序蒙哥马利快速幂取模算法前缀和基础算法整数二分boolcheck(intx)//检查x是否满足某种性质intl=1,r=n,ans=0;while(l<=r){intmid=(l+r)>>1;if(check(mid)){ans=mid;r=mid-1;}elsel=mid+1;......
  • 本地搭建halo模板和插件开发简要步骤
    1.新建local配置文件,加载本地插件工程目录halo:plugin:runtime-mode:developmentfixed-plugin-path:#配置为插件绝对路径#-D:\myproject\hellodev\plugin-ylpro-D:\myproject\hellodev\plugin-links2.插件工程编写好处理模板的代码3.编......
  • 模板
    #include<cstdio>#include<cstring>#include<iostream>#include<algorithm>usingnamespacestd;constintN=100010,INF=1e8;intn;structNode{intl,r;intkey,val;intcnt,size;}tr[N];introot,idx;......
  • flask路由系统、偏函数、CBV、模板、请求响应、session、请求扩展
    路由系统1代码演示23fromflaskimportFlask45app=Flask(__name__)67app.debug=True8#路由基本使用9#@app.route('/',methods=['GET'])10#@app.get()11#@app.post()12defindex(name):13print(name)14return&......
  • 【前端求助帖】关于使用element-plus select 模板嵌套popover中使用select选择后,上一
    先看下效果主页代码如下项目使用的是Vue3+vite,下载后,直接pnpm i安装依赖, pnpmdev就是可以跑起来<el-buttontype="warning"round@click="openDia">打开弹框</el-button><el-dialogv-model="dialogTableVisible"title="业务"width=......
  • 清新优雅&高颜值!一个基于Vue3实现的后台管理模板
    大家好,我是Java陈序员。今天,给大家介绍一个高颜值的开源后台管理模板,已经收获了8k+Star!关注微信公众号:【Java陈序员】,获取开源项目分享、AI副业分享、超200本经典计算机电子书籍等。项目介绍SoybeanAdmin——一个清新优雅、高颜值且功能强大的后台管理模板。基于最新的......