python如何将DICOM格式转为JPG格式图片??
import os
import numpy as np
import pydicom
from PIL import Image
from os import listdir
def dicom_to_jpeg(dicom_path, output_path):
ds = pydicom.dcmread(dicom_path)
pixel_array = ds.pixel_array
image = Image.fromarray(pixel_array).convert("L")
image.save(output_path)
def dicom_to_rgb(dicom_path, output_path):
ds = pydicom.dcmread(dicom_path)
pixel_array = ds.pixel_array.astype(float)
image_temp = (np.maximum(pixel_array,0)/pixel_array.max())*255
image = np.uint8(image_temp)
image = Image.fromarray(image)
image.save(output_path)
if __name__ == "__main__":
dicom_file = rf'E:\Python\PSMA\data\DCM'
jepg_file = rf'E:\Python\PSMA\data\RGB'
temp_list = listdir(dicom_file)
for filename in temp_list:
try:
print(filename)
image_list = listdir(os.path.join(dicom_file, filename))
if os.path.exists(os.path.join(jepg_file, filename)):
pass
else:
os.makedirs(os.path.join(jepg_file, filename))
for image in image_list:
print(image)
if image[-3:] != 'DCM' :
pass
else:
dicom_path = os.path.join(dicom_file, filename, image)
jepg_path = os.path.join(jepg_file, filename, image[:-3] + 'JPG')
dicom_to_rgb(dicom_path, jepg_path)
except Exception as e:
print(e)