Created
April 20, 2024 11:47
-
-
Save TheBojda/bed8f5f0a191d1995769dc6f2dfd57e3 to your computer and use it in GitHub Desktop.
Export DICOM medical images (MR, CT, X-Ray, etc.) to PNG files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import pydicom | |
from PIL import Image | |
import sys | |
def save_image(pixel_array, output_path): | |
if pixel_array.dtype != 'uint8': | |
pixel_array = ((pixel_array - pixel_array.min()) / (pixel_array.max() - pixel_array.min()) * 255).astype('uint8') | |
img = Image.fromarray(pixel_array) | |
img.save(output_path) | |
print(f"Saved image to {output_path}") | |
def process_dicom_directory(dicomdir_path, save_directory): | |
if not os.path.exists(save_directory): | |
os.makedirs(save_directory) | |
dicomdir = pydicom.dcmread(dicomdir_path) | |
for patient_record in dicomdir.patient_records: | |
if 'PatientName' in patient_record: | |
print(f"Patient: {patient_record.PatientName}") | |
for study_record in patient_record.children: | |
if 'StudyDate' in study_record: | |
print(f"Study: {study_record.StudyDate}") | |
for series_record in study_record.children: | |
for image_record in series_record.children: | |
if 'ReferencedFileID' in image_record: | |
file_id = list(map(str, image_record.ReferencedFileID)) | |
file_id_path = os.path.join(*file_id) | |
print(f"Image: {file_id_path}") | |
image_path = os.path.join(os.path.dirname(dicomdir_path), file_id_path) | |
modified_filename = '_'.join(file_id) + '.png' | |
image_save_path = os.path.join(save_directory, modified_filename) | |
try: | |
img_data = pydicom.dcmread(image_path) | |
print("DICOM image loaded successfully.") | |
save_image(img_data.pixel_array, image_save_path) | |
except FileNotFoundError as e: | |
print(f"Failed to read DICOM file at {image_path}: {e}") | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
if __name__ == "__main__": | |
if len(sys.argv) < 3: | |
print("Usage: python dicom2png.py <path_to_DICOMDIR> <path_to_save_images>") | |
sys.exit(1) | |
dicomdir_path = sys.argv[1] | |
save_directory = sys.argv[2] | |
process_dicom_directory(dicomdir_path, save_directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment