首页 > 其他分享 >nii转dicom及修改dicom信息

nii转dicom及修改dicom信息

时间:2024-07-29 09:42:00浏览次数:9  
标签:nii nifti dicom 修改 slice file path dir

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\\T1\\IM_0001')
    arr = arr.astype('uint16')

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

    # 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])]

    # Generate and set a unique SOP Instance UID for each DICOM file每张dicom唯一DICOM文件中的0008 0018是指SOP Instance UID
    dicom_file.SOPInstanceUID = pydicom.uid.generate_uid()

    # 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]


    # Add or update the private tag (2001,100a) Slice Number MR
    tag = (0x2001, 0x100a)
    if tag in dicom_file:
        dicom_file[tag].value = index + 1
    else:
        dicom_file.add_new(tag, 'IS', index + 1)

        #无用修改
    tag1 = (0x2001, 0x1018)
    if tag1 in dicom_file:
        dicom_file[tag1].value = 155
    tag2 = (0x2001, 0x102d)
    if tag2 in dicom_file:
        dicom_file[tag2].value = 155
    tag3 = (0x2005, 0x1076)
    if tag3 in dicom_file:
        dicom_file[tag3].value = 155
    tag4 = (0x0018, 0x9232)
    if tag4 in dicom_file:
        dicom_file[tag4].value = 155


    # 修改序列描述
    dicom_file.SeriesDescription = 'FLAIR'  #T2WI_MV\FLAIR\T1-C+\sT1W_3D_TFE_NEW
    tag5 = (0x0008, 0x103e)
    # 序列描述
    if tag5 in dicom_file:
        dicom_file[tag5].value = 'FLAIR'
    # 修改 序列instance UID 每组序列唯一
    tag6 = (0x0020, 0x000e)
    if tag6 in dicom_file:
        dicom_file[tag6].value = '1.3.46.670589.11.42444.5.0.6584.2020071412474376369'
    # 窗位
    tag7 = (0x0028, 0x1050)
    if tag7 in dicom_file:
        dicom_file[tag7].value = 3598
    # 窗宽
    tag8 = (0x0028, 0x1051)
    if tag8 in dicom_file:
        dicom_file[tag8].value = 6005

    # SeriesNumber
    tag9 = (0x0020, 0x0011)
    if tag9 in dicom_file:
        dicom_file[tag9].value = 701

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

    # add
    # dicom_file.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian  # or ExplicitVRLittleEndian

    # 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_0003.nii.gz"
    output_path = "C:\\Users\\wangyanming3\\Desktop\\nnUNet-2.4.1\\output\\0003"
    os.makedirs(output_path, exist_ok=True)
    nifti2dicom_1file(input_image, output_path)

标签:nii,nifti,dicom,修改,slice,file,path,dir
From: https://www.cnblogs.com/cupwym/p/18329409

相关文章

  • 修改文件的md5码
    可选文件夹未按照文件类型匹配importosimportrandomimportsysimporthashlibfromtkinterimportfiledialogdefmd5_change(file_name):file=open(file_name,'a')file.write('###&&&')file.close()_FILE_SLIM=100*102......
  • 记录|C#批量修改文件后缀
    文章目录前言一、.CHK批量修改成.mp3更新时间前言针对昨天博文:记录|cmd方式恢复U盘中的数据中的文件修复为.CHK格式后,如果将大量的.CHK后缀改为.mp3后缀的问题进行了编写。主要是,现在网上的批量修改后缀的软件竟然要开会员,啊这。。。只怪我这个程序员没有这种致富......
  • 2024-07-27:用go语言,给定一个正整数数组,最开始可以对数组中的元素进行增加操作,每个元素
    2024-07-27:用go语言,给定一个正整数数组,最开始可以对数组中的元素进行增加操作,每个元素最多加1。然后从修改后的数组中选出一个或多个元素,使得这些元素排序后是连续的。要求找出最多可以选出的元素数量。输入:nums=[2,1,5,1,1]。输出:3。解释:我们将下标0和3处的元素增加1......
  • C# 获取修改了哪些属性
    publicclassProgram{staticpublicDictionary<string,Tuple<object,object>>GetChangedProperties<T>(Ta,Tb)whereT:class{if(a!=null&&b!=null){if(Object.Equals(a,b)){retu......
  • 如何极其快速地修改多维 numpy 数组的值?
    我正在开发一个项目,涉及跟踪(640,640)网格上的数千个点。跟踪这些点时,我将它们的运动以向量线性数组的格式存储,解释每个点的变化位置采用以下格式:v=[starting_x,starting_y,distance_x,distance_y]我(为了项目的缘故)必须创建一个与上述网格(640,640)大......
  • git--本地仓库修改同步到远程仓库
    尝试将本地分支推送到远程仓库时,出现一个非快速前进的错误。通常是因为远程仓库中的分支包含本地分支没有的提交。在推送之前,需要将远程仓库的更改合并到本地分支。解决步骤如下:切换到你的本地分支:确保处于想要推送的分支,例如xxxx:gitcheckoutxxxx拉取远程分支并进行......
  • 修改数据库的默认校对规则
    在Linux下,要修改MySQL服务器的默认字符集和校对规则,您需要按照以下步骤操作: ###1.查找MySQL配置文件 首先,您需要找到MySQL的配置文件。配置文件通常位于`/etc/mysql/my.cnf`或`/etc/my.cnf`。您可以使用`find`命令来查找它: ```bashsudofind/-namemy.cnf```......
  • 修改用户密码
    创建新用户时,新用户没有权限,所以自己无法修改成简单的密码(1)可以通过root用户给权限,让新用户自己修改:1.先进入root用户,mysql-uroot-p1234562.给新用户权限:grantallprivilegeson.to'新用户名'@'localhost'withgrantoption;(其中withgrantoption是让新用户拥有给其......
  • 修改 Visual Studio 程序集信息中的默认公司
    我们在使用VisualStudio创建项目时,会发现程序集信息中的默认公司是Microsoft我们可以通过修改项目文件来修改程序集信息中的默认公司。但是这种方式修改的是当前项目文件,后续创建的项目还是会使用默认的公司信息。我们可以通过注册表来修改默认公司,这样之后创建的项目都会......
  • 三星app移植修复(app反编译修改)
    工具:apktoolADT命令:反编译java-jarapktool.jardtest.apk重打包java-jarapktool.jarbtest签名使用ADTsmail语言粗略理解(其实对于修改来说,大概熟悉就就ok)类定义.classpublicLcom/example/MyClass;.superLjava/lang/Object;.class指定类名和修饰符......