Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Extracting DICOM Data with pydicom

Recommended resources

Welcome back. In our last lesson, we traced the high-level data flow through a radiology department, seeing how standards like HL7 and DICOM orchestrate the journey from an exam order to a final diagnostic report. We established that the DICOM file format is the universal container for medical images produced by this workflow. Now, we're going to open that container and work with its contents directly.

Your learning outcome for this session is to extract metadata and pixel arrays from medical imaging DICOM files using the pydicom library. This is the first essential, hands-on skill for any medical computer vision task. It's the bridge that takes you from the raw data files sitting in a PACS archive to the numerical data—the NumPy arrays—that your machine learning models will consume.

Deconstructing the DICOM File

Before we write any code, it's important to understand that a DICOM file is not simply an image like a JPEG or PNG. It is a highly structured data object that bundles two fundamental types of information:

  1. Metadata Header: A rich collection of information about the patient, the equipment used, the imaging procedure, and more. This metadata is organized into a list of Data Elements. Each element has a unique identifier called a Tag (e.g., (0010,0020) for Patient ID), a name (e.g., "PatientID"), and a value. This is the information that originated from the RIS and was captured during the workflow we discussed previously.
  2. Pixel Data: The raw pixel values that form the actual image. This is stored as a multi-dimensional array.

For anyone with experience in telecommunications, you can think of the DICOM metadata header as being conceptually similar to the signaling information in a protocol like SIP, which carries caller ID, call type, and routing information, while the pixel data is analogous to the actual RTP voice stream. Both are essential for the payload to be correctly interpreted and used.

To handle this structure in Python, we use a specialized library called pydicom.


Getting Started with pydicom

pydicom is the de facto standard library for parsing and manipulating DICOM files in Python. It elegantly abstracts away the low-level details of the DICOM file format, allowing you to interact with files as intuitive Python objects.

The video below provides a practical walkthrough of setting up your environment and using pydicom to perform the exact tasks of this lesson. We will work through it step-by-step.

1. Dicom In Python

The video "Dicom In Python" by Arbois Code Media will be our guide. It clearly demonstrates what a DICOM file is and how to use pydicom to access its contents.

We'll break down the process into reading metadata and then extracting and visualizing the image.

First, let's get a feel for the structure of a DICOM file and the role pydicom plays.

1. Dicom In Python

This first segment introduces the DICOM format and covers the initial setup. Since you're an expert Python user, you can treat the virtual environment setup as a quick review. The key part is the installation of the pydicom library.

Watch the introduction from the beginning to see a visual example of a DICOM file's contents. Then, you can watch or skim the setup section from installing pydicom. The essential command is pip install pydicom.


Reading a DICOM File and Accessing Metadata

Once pydicom is installed, the first step is to read a DICOM file from disk. The library makes this incredibly simple. The function pydicom.dcmread() parses the entire file and returns a FileDataset object. This object contains all the Data Elements (the metadata) as attributes.

Let's see how this works in practice. The next part of the video demonstrates reading a file and inspecting its contents.

1. Dicom In Python

This clip shows the core process of reading a DICOM file and accessing the metadata within it.

Watch from this section. Pay attention to how pydicom.dcmread() is used and how simply printing the resulting object displays the metadata header.

As shown in the video, reading the file is a one-liner:

import pydicom

# The path to your DICOM file
dicom_file_path = 'path/to/your/file.dcm'

# Read and parse the DICOM file
ds = pydicom.dcmread(dicom_file_path)

# Print the full metadata header
print(ds)

The ds object now holds all the information. You can access specific metadata attributes using their standard DICOM keywords, just like you would access any other Python object attribute.

For example:

  • ds.PatientName
  • ds.PatientID
  • ds.StudyDate
  • ds.Modality (e.g., 'CT', 'MR', 'DX')
  • ds.StudyDescription

This provides a clean, programmatic way to extract the contextual information that is critical for organizing data, linking it to clinical outcomes, or filtering it for specific cohorts in your AI projects.


Extracting and Visualizing the Pixel Array

Now for the most important part for computer vision: getting the image itself. pydicom makes this just as easy. The pixel data is exposed as a special attribute called pixel_array.

The crucial point here is that ds.pixel_array is a NumPy array. This is the bridge from the medical imaging world to the machine learning world. Once you have the data as a NumPy array, you are on familiar ground. You can feed this array directly into frameworks like TensorFlow, Keras, or, as we will learn later in this course, PyTorch.

To confirm we have the correct data, we can visualize it. The standard library for this is matplotlib. The final segment of the video demonstrates this process.

1. Dicom In Python

This part of the video covers installing matplotlib, accessing the pixel_array attribute, and displaying the image.

Watch from this segment. Notice how plt.imshow() is used to render the pixel_array. The use of a grayscale colormap (cmap='gray') is standard practice for most medical images.


Putting It All Together

Let's consolidate everything into a single, complete script. This example reads a DICOM file, prints some key metadata, extracts the pixel data, prints its dimensions, and displays the image.

import pydicom
import matplotlib.pyplot as plt
import numpy as np # pydicom returns a NumPy array

# --- 1. Load the DICOM file ---
# Replace with the actual path to a DICOM file
dicom_file_path = 'path/to/your/file.dcm' 
try:
    ds = pydicom.dcmread(dicom_file_path)
except FileNotFoundError:
    print(f"Error: The file was not found at {dicom_file_path}")
    # In a real script, you might exit or handle this more gracefully
    exit()

# --- 2. Extract and Print Metadata ---
print("--- Key Metadata ---")
# Use hasattr to safely check if an attribute exists before accessing it
if hasattr(ds, 'PatientID'):
    print(f"Patient ID: {ds.PatientID}")
if hasattr(ds, 'StudyDescription'):
    print(f"Study Description: {ds.StudyDescription}")
if hasattr(ds, 'Modality'):
    print(f"Modality: {ds.Modality}")
if hasattr(ds, 'Rows') and hasattr(ds, 'Columns'):
    print(f"Image Dimensions (from metadata): {ds.Rows} x {ds.Columns}")

# --- 3. Extract Pixel Array ---
print("\n--- Pixel Data ---")
if hasattr(ds, 'pixel_array'):
    # pixel_array is the image data as a NumPy array
    pixel_array = ds.pixel_array
    print(f"Pixel array type: {type(pixel_array)}")
    print(f"Pixel array dimensions (from NumPy): {pixel_array.shape}")
    print(f"Pixel data type: {pixel_array.dtype}")

    # --- 4. Visualize the Image ---
    plt.figure(figsize=(8, 8))
    # Use a grayscale colormap
    plt.imshow(pixel_array, cmap=plt.cm.gray)
    plt.title('Medical Image from DICOM')
    plt.axis('off') # Hide axes for a cleaner look
    plt.show()
else:
    print("This DICOM file does not contain pixel data.")

This script is a template you can adapt for nearly any task involving single DICOM files. You now have the fundamental tools to load and inspect the primary data type used in medical imaging.


Conclusion

In this lesson, we transitioned from theory to practice, diving into the structure of DICOM files and using the pydicom library to programmatically access their contents.

Here are the key takeaways:

  • DICOM as a Container: A DICOM file is a structured object containing both a metadata header and the image's pixel data.
  • pydicom is Essential: The pydicom library is the primary tool in Python for reading and parsing DICOM files.
  • Reading Files: pydicom.dcmread() loads a DICOM file into a FileDataset object.
  • Accessing Data: Metadata is accessed via object attributes (e.g., ds.PatientID), and the image is extracted as a NumPy array using the ds.pixel_array attribute. This conversion to a NumPy array is the key step for any downstream AI/ML application.

You've just acquired the foundational skill for handling medical images in Python. However, accessing this data comes with significant responsibility. The metadata we just printed, such as PatientID, is protected health information (PHI). In our next lesson, we will address this directly by learning to identify key data protection requirements of the HIPAA Security Rule applicable to AI systems. Understanding how to handle this sensitive data legally and ethically is just as important as knowing how to process it technically.