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