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

``

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)
posted @ 2024-06-17 09:41  cupwym  阅读(165)  评论(0)    收藏  举报