Skip to content

Instantly share code, notes, and snippets.

@airalcorn2
Last active September 14, 2023 11:08
Show Gist options
  • Save airalcorn2/2bdf6b316c232eb25d113d4d7d8873a9 to your computer and use it in GitHub Desktop.
Save airalcorn2/2bdf6b316c232eb25d113d4d7d8873a9 to your computer and use it in GitHub Desktop.
Convert DICOM data to GIFs.
# Derived from: https://github.com/pydicom/pydicom/blob/master/examples/input_output/plot_read_dicom_directory.py.
import imageio
import matplotlib.pyplot as plt
import numpy as np
import pydicom
from os import mkdir
from os.path import join
from PIL import Image
from pydicom.filereader import read_dicomdir
dicom_dir = read_dicomdir("DICOMDIR")
out_names = {}
try:
mkdir("gifs")
except FileExistsError:
pass
for patient_record in dicom_dir.patient_records:
if hasattr(patient_record, "PatientID") and hasattr(patient_record, "PatientName"):
print(f"Patient: {patient_record.PatientID}: {patient_record.PatientName}")
studies = patient_record.children
for study in studies:
indent = 4 * " "
print(
f"{indent}Study {study.StudyID}: {study.StudyDate}: {study.StudyDescription}"
)
all_series = study.children
for series in all_series:
image_count = len(series.children)
plural = ("", "s")[image_count > 1]
if "SeriesDescription" not in series:
series.SeriesDescription = "N/A"
indent = 8 * " "
print(
f"{indent}Series {series.SeriesNumber}: {series.Modality}: {series.SeriesDescription} ({image_count} image{plural})"
)
indent = 12 * " "
print(f"{indent}Reading images...")
image_records = series.children
out_name = "".join(
[x if x.isalnum() else "_" for x in series.SeriesDescription]
)
out_names[out_name] = out_names.get(out_name, 0) + 1
out_name += "_" + str(out_names[out_name]).zfill(2)
gif_f = f"gifs/{out_name}.gif"
writer = imageio.get_writer(gif_f, mode="I")
for image_rec in image_records:
image_f = join(*image_rec.ReferencedFileID)
ds = pydicom.dcmread(image_f)
fig = plt.imshow(ds.pixel_array, cmap=plt.cm.bone)
plt.axis("off")
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig("tmp.png", bbox_inches="tight", pad_inches=0)
image = Image.open("tmp.png")
writer.append_data(np.array(image))
writer.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment