alterlab-pydicom
Reads, writes, and manipulates DICOM (Digital Imaging and Communications in Medicine) medical imaging files with the pydicom Python library. Use when reading/writing/modifying DICOM data, extracting pixel data from CT, MRI, X-ray, or ultrasound images, anonymizing DICOM files, wo
Install
npx skills add https://github.com/AlterLab-IEU/AlterLab-Academic-Skills/tree/main/skills/clinical-research/alterlab-pydicom
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install alterlab-ieu-alterlab-academic-skills@llmmart
git clone https://github.com/AlterLab-IEU/AlterLab-Academic-Skills.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole alterlab-ieu/alterlab-academic-skills collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Pydicom
Overview
Pydicom is a pure Python package for working with DICOM files, the standard format for medical imaging data. This skill provides guidance on reading, writing, and manipulating DICOM files, including working with pixel data, metadata, and various compression formats.
When to Use This Skill
Use this skill when working with:
- Medical imaging files (CT, MRI, X-ray, ultrasound, PET, etc.)
- DICOM datasets requiring metadata extraction or modification
- Pixel data extraction and image processing from medical scans
- DICOM anonymization for research or data sharing
- Converting DICOM files to standard image formats
- Compressed DICOM data requiring decompression
- DICOM sequences and structured reports
- Multi-slice volume reconstruction
- PACS (Picture Archiving and Communication System) integration
Does NOT Trigger
| Scenario | Use Instead |
|---|---|
| Finding and downloading public cancer imaging collections (NCI Imaging Data Commons) | alterlab-imaging-data-commons |
| Tiling or preprocessing whole-slide pathology images (H&E WSI) | alterlab-histolab |
| Training ML models on clinical imaging or EHR datasets | alterlab-pyhealth |
| Processing ECG/EEG/EDA physiological waveforms | alterlab-neurokit2 |
Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-imaging-data-commons) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.
Installation
Targets pydicom 3.x (current release 3.0.2 as of 2026-09; Python >= 3.10). 3.0 reorganized the pixel APIs — see the version note below. No install step: uv run resolves the packages per run (pin the interpreter; uv's default may be an older Python that gets older releases):
uv run --python ">=3.11" --with "pydicom>=3.0" --with numpy python script.py
# + --with pillow image export (PNG/JPEG) + --with matplotlib plots
For compressed DICOM, add the codec packages to the same command:
--with pylibjpeg --with pylibjpeg-libjpeg --with pylibjpeg-openjpeg # JPEG / JPEG 2000 decode; JPEG 2000 encode
--with pylibjpeg-rle # faster RLE encode/decode (pydicom's own RLE codec also works)
--with python-gdcm # alternative decoder for most compressed syntaxes
--with pyjpegls # JPEG-LS encode/decode
pydicom 3.0 API changes (important)
3.0 moved all pixel handling into the pydicom.pixels module and deprecated some long-standing APIs (the old names still work but emit warnings and are removed in 4.0):
from pydicom.pixel_data_handlers.util import apply_voi_lut→from pydicom.pixels import apply_voi_lut(same forconvert_color_space).pydicom.encoders→pydicom.pixels.encoders.ds.save_as(path, write_like_original=False)→ds.save_as(path, enforce_file_format=True)(write_like_original=True, the default, became implicit and is no longer needed).- New helpers:
ds.set_pixel_data(arr, photometric_interpretation, bits_stored)writes Pixel Data and the matching Image Pixel elements;ds.compress()/ds.decompress()convert between transfer syntaxes.
All examples below use the 3.x APIs.
Core Workflows
Reading DICOM Files
Read a DICOM file using pydicom.dcmread():
import pydicom
# Read a DICOM file
ds = pydicom.dcmread('path/to/file.dcm')
# Access metadata
print(f"Patient Name: {ds.PatientName}")
print(f"Study Date: {ds.StudyDate}")
print(f"Modality: {ds.Modality}")
# Display all elements
print(ds)
Key points:
dcmread()returns aDatasetobject- Access data elements using attribute notation (e.g.,
ds.PatientName) or tag notation (e.g.,ds[0x0010, 0x0010]) - Use
ds.file_metato access file metadata like Transfer Syntax UID - Handle missing attributes with
getattr(ds, 'AttributeName', default_value)orhasattr(ds, 'AttributeName')
Working with Pixel Data
Extract and manipulate image data from DICOM files:
import pydicom
import numpy as np
import matplotlib.pyplot as plt
# Read DICOM file
ds = pydicom.dcmread('image.dcm')
# Get pixel array (requires numpy)
pixel_array = ds.pixel_array
# Image information
print(f"Shape: {pixel_array.shape}")
print(f"Data type: {pixel_array.dtype}")
print(f"Rows: {ds.Rows}, Columns: {ds.Columns}")
# Apply windowing for display (CT/MRI)
if hasattr(ds, 'WindowCenter') and hasattr(ds, 'WindowWidth'):
from pydicom.pixels import apply_modality_lut, apply_voi_lut # pydicom 3.x location
# Window Center/Width are in modality units (HU for CT): rescale first
hu = apply_modality_lut(pixel_array, ds) # RescaleSlope/RescaleIntercept
windowed_image = apply_voi_lut(hu, ds, index=0) # index picks one of several windows
else:
windowed_image = pixel_array
# Display image
plt.imshow(windowed_image, cmap='gray')
plt.title(f"{ds.Modality} - {ds.StudyDescription}")
plt.axis('off')
plt.show()
Working with color images:
# RGB images have shape (rows, columns, 3)
if ds.PhotometricInterpretation == 'RGB':
rgb_image = ds.pixel_array
plt.imshow(rgb_image)
elif ds.PhotometricInterpretation == 'YBR_FULL':
from pydicom.pixels import convert_color_space # pydicom 3.x location
rgb_image = convert_color_space(ds.pixel_array, 'YBR_FULL', 'RGB')
plt.imshow(rgb_image)
Multi-frame images (videos/series):
# For multi-frame DICOM files
if hasattr(ds, 'NumberOfFrames') and ds.NumberOfFrames > 1:
frames = ds.pixel_array # Shape: (num_frames, rows, columns)
print(f"Number of frames: {frames.shape[0]}")
# Display specific frame
plt.imshow(frames[0], cmap='gray')
Converting DICOM to Image Formats
Use the provided dicom_to_image.py script or convert manually:
from PIL import Image
import pydicom
import numpy as np
ds = pydicom.dcmread('input.dcm')
pixel_array = ds.pixel_array
# Normalize to 0-255 range
if pixel_array.dtype != np.uint8:
pixel_array = ((pixel_array - pixel_array.min()) /
(pixel_array.max() - pixel_array.min()) * 255).astype(np.uint8)
# Save as PNG
image = Image.fromarray(pixel_array)
image.save('output.png')
Use the script: uv run --python ">=3.11" --with "pydicom>=3.0" --with pillow --with numpy python scripts/dicom_to_image.py input.dcm output.png
Modifying Metadata
Modify DICOM data elements:
import pydicom
from datetime import datetime
ds = pydicom.dcmread('input.dcm')
# Modify existing elements
ds.PatientName = "Doe^John"
ds.StudyDate = datetime.now().strftime('%Y%m%d')
ds.StudyDescription = "Modified Study"
# Add new elements
ds.SeriesNumber = 1
ds.SeriesDescription = "New Series"
# Remove elements
if hasattr(ds, 'PatientComments'):
delattr(ds, 'PatientComments')
# Or using del
if 'PatientComments' in ds:
del ds.PatientComments
# Save modified file
ds.save_as('modified.dcm')
Anonymizing DICOM Files
Remove or replace patient identifiable information:
import pydicom
from datetime import datetime
ds = pydicom.dcmread('input.dcm')
# Tags commonly containing PHI (Protected Health Information)
tags_to_anonymize = [
'PatientName', 'PatientID', 'PatientBirthDate',
'PatientSex', 'PatientAge', 'PatientAddress',
'InstitutionName', 'InstitutionAddress',
'ReferringPhysicianName', 'PerformingPhysicianName',
'OperatorsName', 'StudyDescription', 'SeriesDescription',
]
# Remove or replace sensitive data at every level: ds.walk() also visits items inside
# sequences, where IDs such as AccessionNumber are often repeated
def scrub(dataset, elem):
if elem.keyword in ('PatientName', 'PatientID'):
dataset[elem.tag].value = 'ANONYMOUS'
elif elem.keyword == 'PatientBirthDate':
dataset[elem.tag].value = '19000101'
elif elem.keyword in tags_to_anonymize + ['AccessionNumber']:
del dataset[elem.tag]
ds.walk(scrub)
# Vendor private tags frequently carry identifiers
ds.remove_private_tags()
# Replace dates consistently (e.g. one per-patient offset) to keep intervals meaningful
if hasattr(ds, 'StudyDate'):
ds.StudyDate = '20000101'
ds.PatientIdentityRemoved = 'YES'
# Keep pixel data intact
ds.save_as('anonymized.dcm')
Use the provided script (it walks sequences and warns when BurnedInAnnotation is YES): uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/anonymize_dicom.py input.dcm output.dcm
A tag list like this is a starting point, not a complete de-identification. Identifiers also hide in other date/time elements, UIDs, accession numbers, nested sequences, free-text fields, and text burned into the pixels (check BurnedInAnnotation and inspect ultrasound/secondary-capture images). For data leaving your institution, apply a profile based on DICOM PS3.15 Annex E (Basic Application Level Confidentiality Profile) with a dedicated tool such as deid (pydicom project) or dicognito, and have the output reviewed before release — the same standard your IRB or data use agreement will expect.
Writing DICOM Files
Create DICOM files from scratch:
import pydicom
from pydicom.dataset import Dataset, FileDataset, FileMetaDataset
from datetime import datetime
import numpy as np
# Create file meta information (use FileMetaDataset, not a bare Dataset)
file_meta = FileMetaDataset()
file_meta.MediaStorageSOPClassUID = pydicom.uid.CTImageStorage
file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid()
file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian
# Create the FileDataset instance
ds = FileDataset('new_dicom.dcm', {}, file_meta=file_meta, preamble=b"\0" * 128)
# Add required DICOM elements
ds.PatientName = "Test^Patient"
ds.PatientID = "123456"
ds.Modality = "CT"
ds.StudyDate = datetime.now().strftime('%Y%m%d')
ds.StudyTime = datetime.now().strftime('%H%M%S')
ds.ContentDate = ds.StudyDate
ds.ContentTime = ds.StudyTime
# Add image-specific elements
ds.SamplesPerPixel = 1
ds.PhotometricInterpretation = "MONOCHROME2"
ds.Rows = 512
ds.Columns = 512
ds.BitsAllocated = 16
ds.BitsStored = 16
ds.HighBit = 15
ds.PixelRepresentation = 0
# Create pixel data (pydicom >= 3.0 alternative for the block above and this one:
# ds.set_pixel_data(pixel_array, photometric_interpretation="MONOCHROME2", bits_stored=12))
pixel_array = np.random.randint(0, 4096, (512, 512), dtype=np.uint16)
ds.PixelData = pixel_array.tobytes()
# Add required UIDs
ds.SOPClassUID = pydicom.uid.CTImageStorage
ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID
ds.SeriesInstanceUID = pydicom.uid.generate_uid()
ds.StudyInstanceUID = pydicom.uid.generate_uid()
# Save the file
ds.save_as('new_dicom.dcm')
Compression and Decompression
Handle compressed DICOM files:
import pydicom
# Read compressed DICOM file
ds = pydicom.dcmread('compressed.dcm')
# Check transfer syntax
print(f"Transfer Syntax: {ds.file_meta.TransferSyntaxUID}")
print(f"Transfer Syntax Name: {ds.file_meta.TransferSyntaxUID.name}")
# Decompress and save as uncompressed (Transfer Syntax becomes Explicit VR LE)
ds.decompress()
ds.save_as('uncompressed.dcm', enforce_file_format=True)
# Or compress (RLE Lossless works with numpy alone)
ds_uncompressed = pydicom.dcmread('uncompressed.dcm')
ds_uncompressed.compress(pydicom.uid.RLELossless)
ds_uncompressed.save_as('compressed_rle.dcm')
pydicom 3.0 can encode only RLE Lossless (native, pylibjpeg-rle, or gdcm), JPEG-LS Lossless/Near-Lossless (pyjpegls), and JPEG 2000 Lossless/lossy (pylibjpeg-openjpeg). JPEG Baseline and JPEG Lossless are decode-only — compress() raises NotImplementedError for them.
Common transfer syntaxes:
ExplicitVRLittleEndian- Uncompressed, most commonJPEGBaseline8Bit- JPEG lossy compressionJPEGLossless- JPEG lossless compressionJPEG2000Lossless- JPEG 2000 losslessRLELossless- Run-Length Encoding lossless
See references/transfer_syntaxes.md for complete list.
Working with DICOM Sequences
Handle nested data structures:
import pydicom
ds = pydicom.dcmread('file.dcm')
# Access sequences
if 'ReferencedStudySequence' in ds:
for item in ds.ReferencedStudySequence:
print(f"Referenced SOP Instance UID: {item.ReferencedSOPInstanceUID}")
# Create a sequence
from pydicom.sequence import Sequence
sequence_item = Dataset()
sequence_item.ReferencedSOPClassUID = pydicom.uid.CTImageStorage
sequence_item.ReferencedSOPInstanceUID = pydicom.uid.generate_uid()
ds.ReferencedImageSequence = Sequence([sequence_item])
Processing DICOM Series
Work with multiple related DICOM files:
import pydicom
import numpy as np
from pathlib import Path
# Read all DICOM files in a directory
dicom_dir = Path('dicom_series/')
slices = []
for file_path in dicom_dir.glob('*.dcm'):
ds = pydicom.dcmread(file_path)
slices.append(ds)
# Sort by slice location or instance number
slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))
# Or: slices.sort(key=lambda x: int(x.InstanceNumber))
# Create 3D volume
volume = np.stack([s.pixel_array for s in slices])
print(f"Volume shape: {volume.shape}") # (num_slices, rows, columns)
# Get spacing information for proper scaling
pixel_spacing = slices[0].PixelSpacing # [row_spacing, col_spacing]
slice_thickness = slices[0].SliceThickness
print(f"Voxel size: {pixel_spacing[0]}x{pixel_spacing[1]}x{slice_thickness} mm")
Helper Scripts
This skill includes utility scripts in the scripts/ directory:
anonymize_dicom.py
Anonymize DICOM files by removing or replacing Protected Health Information (PHI).
uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/anonymize_dicom.py input.dcm output.dcm
dicom_to_image.py
Convert DICOM files to common image formats (PNG, JPEG, TIFF).
uv run --python ">=3.11" --with "pydicom>=3.0" --with pillow --with numpy python scripts/dicom_to_image.py input.dcm output.png
uv run --python ">=3.11" --with "pydicom>=3.0" --with pillow --with numpy python scripts/dicom_to_image.py input.dcm output.jpg --format JPEG
extract_metadata.py
Extract and display DICOM metadata in a readable format.
uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/extract_metadata.py file.dcm
uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/extract_metadata.py file.dcm --output metadata.txt
Reference Materials
Detailed reference information is available in the references/ directory:
- common_tags.md: Comprehensive list of commonly used DICOM tags organized by category (Patient, Study, Series, Image, etc.)
- transfer_syntaxes.md: Complete reference of DICOM transfer syntaxes and compression formats
Common Issues and Solutions
Issue: "Unable to decode pixel data"
- Solution: Add compression handlers to the run:
uv run --python ">=3.11" --with "pydicom>=3.0" --with pylibjpeg --with pylibjpeg-libjpeg --with pylibjpeg-openjpeg --with python-gdcm python script.py
Issue: "AttributeError" when accessing tags
- Solution: Check if attribute exists with
hasattr(ds, 'AttributeName')or useds.get('AttributeName', default)
Issue: Incorrect image display (too dark/bright)
- Solution: Apply the modality LUT, then the VOI LUT:
apply_voi_lut(apply_modality_lut(pixel_array, ds), ds), or window the rescaled values manually withWindowCenterandWindowWidth. Windowing raw stored values of a CT with RescaleIntercept -1024 shifts every window by 1024 HU
Issue: Memory issues with large series
- Solution: Process files iteratively, use memory-mapped arrays, or downsample images
Best Practices
- Always check for required attributes before accessing them using
hasattr()orget() - Preserve original encoding when modifying files: plain
ds.save_as(path)keeps the source layout (pydicom 3.x makes this the default); passenforce_file_format=Trueonly when you need a fully standard-compliant File Format output - Use Transfer Syntax UIDs to understand compression format before processing pixel data
- Handle exceptions when reading files from untrusted sources
- Apply proper windowing (VOI LUT) for medical image visualization
- Maintain spatial information (pixel spacing, slice thickness) when processing 3D volumes
- Verify anonymization thoroughly before sharing medical data (private tags, burned-in text, UIDs, and dates included)
- Use UIDs correctly - generate new UIDs when creating new instances, preserve them when modifying
Documentation
Official pydicom documentation (stable = current 3.x release): https://pydicom.github.io/pydicom/stable/
- User Guide: https://pydicom.github.io/pydicom/stable/guides/user/index.html
- Tutorials: https://pydicom.github.io/pydicom/stable/tutorials/index.html
- API Reference: https://pydicom.github.io/pydicom/stable/reference/index.html
- v3.0 release notes (API migration): https://pydicom.github.io/pydicom/stable/release_notes/v3.0.0.html
Part of the AlterLab Academic Skills suite.
Files (alterlab-academic-skills)
-
evals
-
fixtures
-
chest_ct
-
chest_ct_slice037.dcm 18.8 KB · in bundle
-
README.txt 225 B
Loading…
-
-
dicom_share
-
patient1_ct_0001.dcm 9.2 KB · in bundle
-
patient1_dose_report.dcm 5.1 KB · in bundle
-
patient2_ct_0001.dcm 9.2 KB · in bundle
-
README.txt 393 B
Loading…
-
-
-
evals.json 6.4 KB
Loading…
-
-
references
-
common_tags.md 10 KB
Loading… -
transfer_syntaxes.md 10.9 KB
Loading…
-
-
scripts
-
anonymize_dicom.py 7.3 KB
Loading… -
dicom_to_image.py 6.6 KB
Loading… -
extract_metadata.py 5.6 KB
Loading…
-
-
SKILL.md 17.9 KB
--- name: alterlab-pydicom description: Reads, writes, and manipulates DICOM (Digital Imaging and Communications in Medicine) medical imaging files with the pydicom Python library. Use when reading/writing/modifying DICOM data, extracting pixel data from CT, MRI, X-ray, or ultrasound images, anonymizing DICOM files, working with DICOM metadata and tags, converting DICOM to other formats, handling compressed DICOM, or processing medical imaging datasets for PACS systems, radiology workflows, and healthcare imaging applications. Part of the AlterLab Academic Skills suite. license: MIT allowed-tools: Read Write Edit Bash(python:*) Bash(uv run:*) compatibility: No API key required. Self-contained; runs install-free with `uv run --python ">=3.11" --with "pydicom>=3.0" --with numpy python script.py`, adding codec packages (pylibjpeg-openjpeg, python-gdcm, ...) with further `--with` flags for compressed files. metadata: skill-author: AlterLab version: "1.1.0" last_updated: "2026-09-23" --- # Pydicom ## Overview Pydicom is a pure Python package for working with DICOM files, the standard format for medical imaging data. This skill provides guidance on reading, writing, and manipulating DICOM files, including working with pixel data, metadata, and various compression formats. ## When to Use This Skill Use this skill when working with: - Medical imaging files (CT, MRI, X-ray, ultrasound, PET, etc.) - DICOM datasets requiring metadata extraction or modification - Pixel data extraction and image processing from medical scans - DICOM anonymization for research or data sharing - Converting DICOM files to standard image formats - Compressed DICOM data requiring decompression - DICOM sequences and structured reports - Multi-slice volume reconstruction - PACS (Picture Archiving and Communication System) integration ### Does NOT Trigger | Scenario | Use Instead | |----------|-------------| | Finding and downloading public cancer imaging collections (NCI Imaging Data Commons) | `alterlab-imaging-data-commons` | | Tiling or preprocessing whole-slide pathology images (H&E WSI) | `alterlab-histolab` | | Training ML models on clinical imaging or EHR datasets | `alterlab-pyhealth` | | Processing ECG/EEG/EDA physiological waveforms | `alterlab-neurokit2` | **Hand-off rule.** When the request matches a row above, open your answer by naming that skill by its exact id (for example `alterlab-imaging-data-commons`) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work. ## Installation Targets **pydicom 3.x** (current release 3.0.2 as of 2026-09; Python >= 3.10). 3.0 reorganized the pixel APIs — see the version note below. No install step: `uv run` resolves the packages per run (pin the interpreter; uv's default may be an older Python that gets older releases): ```bash uv run --python ">=3.11" --with "pydicom>=3.0" --with numpy python script.py # + --with pillow image export (PNG/JPEG) + --with matplotlib plots ``` For compressed DICOM, add the codec packages to the same command: ```bash --with pylibjpeg --with pylibjpeg-libjpeg --with pylibjpeg-openjpeg # JPEG / JPEG 2000 decode; JPEG 2000 encode --with pylibjpeg-rle # faster RLE encode/decode (pydicom's own RLE codec also works) --with python-gdcm # alternative decoder for most compressed syntaxes --with pyjpegls # JPEG-LS encode/decode ``` ### pydicom 3.0 API changes (important) 3.0 moved all pixel handling into the `pydicom.pixels` module and deprecated some long-standing APIs (the old names still work but emit warnings and are removed in 4.0): - `from pydicom.pixel_data_handlers.util import apply_voi_lut` → **`from pydicom.pixels import apply_voi_lut`** (same for `convert_color_space`). - `pydicom.encoders` → **`pydicom.pixels.encoders`**. - `ds.save_as(path, write_like_original=False)` → **`ds.save_as(path, enforce_file_format=True)`** (`write_like_original=True`, the default, became implicit and is no longer needed). - New helpers: `ds.set_pixel_data(arr, photometric_interpretation, bits_stored)` writes *Pixel Data* and the matching Image Pixel elements; `ds.compress()` / `ds.decompress()` convert between transfer syntaxes. All examples below use the 3.x APIs. ## Core Workflows ### Reading DICOM Files Read a DICOM file using `pydicom.dcmread()`: ```python import pydicom # Read a DICOM file ds = pydicom.dcmread('path/to/file.dcm') # Access metadata print(f"Patient Name: {ds.PatientName}") print(f"Study Date: {ds.StudyDate}") print(f"Modality: {ds.Modality}") # Display all elements print(ds) ``` **Key points:** - `dcmread()` returns a `Dataset` object - Access data elements using attribute notation (e.g., `ds.PatientName`) or tag notation (e.g., `ds[0x0010, 0x0010]`) - Use `ds.file_meta` to access file metadata like Transfer Syntax UID - Handle missing attributes with `getattr(ds, 'AttributeName', default_value)` or `hasattr(ds, 'AttributeName')` ### Working with Pixel Data Extract and manipulate image data from DICOM files: ```python import pydicom import numpy as np import matplotlib.pyplot as plt # Read DICOM file ds = pydicom.dcmread('image.dcm') # Get pixel array (requires numpy) pixel_array = ds.pixel_array # Image information print(f"Shape: {pixel_array.shape}") print(f"Data type: {pixel_array.dtype}") print(f"Rows: {ds.Rows}, Columns: {ds.Columns}") # Apply windowing for display (CT/MRI) if hasattr(ds, 'WindowCenter') and hasattr(ds, 'WindowWidth'): from pydicom.pixels import apply_modality_lut, apply_voi_lut # pydicom 3.x location # Window Center/Width are in modality units (HU for CT): rescale first hu = apply_modality_lut(pixel_array, ds) # RescaleSlope/RescaleIntercept windowed_image = apply_voi_lut(hu, ds, index=0) # index picks one of several windows else: windowed_image = pixel_array # Display image plt.imshow(windowed_image, cmap='gray') plt.title(f"{ds.Modality} - {ds.StudyDescription}") plt.axis('off') plt.show() ``` **Working with color images:** ```python # RGB images have shape (rows, columns, 3) if ds.PhotometricInterpretation == 'RGB': rgb_image = ds.pixel_array plt.imshow(rgb_image) elif ds.PhotometricInterpretation == 'YBR_FULL': from pydicom.pixels import convert_color_space # pydicom 3.x location rgb_image = convert_color_space(ds.pixel_array, 'YBR_FULL', 'RGB') plt.imshow(rgb_image) ``` **Multi-frame images (videos/series):** ```python # For multi-frame DICOM files if hasattr(ds, 'NumberOfFrames') and ds.NumberOfFrames > 1: frames = ds.pixel_array # Shape: (num_frames, rows, columns) print(f"Number of frames: {frames.shape[0]}") # Display specific frame plt.imshow(frames[0], cmap='gray') ``` ### Converting DICOM to Image Formats Use the provided `dicom_to_image.py` script or convert manually: ```python from PIL import Image import pydicom import numpy as np ds = pydicom.dcmread('input.dcm') pixel_array = ds.pixel_array # Normalize to 0-255 range if pixel_array.dtype != np.uint8: pixel_array = ((pixel_array - pixel_array.min()) / (pixel_array.max() - pixel_array.min()) * 255).astype(np.uint8) # Save as PNG image = Image.fromarray(pixel_array) image.save('output.png') ``` Use the script: `uv run --python ">=3.11" --with "pydicom>=3.0" --with pillow --with numpy python scripts/dicom_to_image.py input.dcm output.png` ### Modifying Metadata Modify DICOM data elements: ```python import pydicom from datetime import datetime ds = pydicom.dcmread('input.dcm') # Modify existing elements ds.PatientName = "Doe^John" ds.StudyDate = datetime.now().strftime('%Y%m%d') ds.StudyDescription = "Modified Study" # Add new elements ds.SeriesNumber = 1 ds.SeriesDescription = "New Series" # Remove elements if hasattr(ds, 'PatientComments'): delattr(ds, 'PatientComments') # Or using del if 'PatientComments' in ds: del ds.PatientComments # Save modified file ds.save_as('modified.dcm') ``` ### Anonymizing DICOM Files Remove or replace patient identifiable information: ```python import pydicom from datetime import datetime ds = pydicom.dcmread('input.dcm') # Tags commonly containing PHI (Protected Health Information) tags_to_anonymize = [ 'PatientName', 'PatientID', 'PatientBirthDate', 'PatientSex', 'PatientAge', 'PatientAddress', 'InstitutionName', 'InstitutionAddress', 'ReferringPhysicianName', 'PerformingPhysicianName', 'OperatorsName', 'StudyDescription', 'SeriesDescription', ] # Remove or replace sensitive data at every level: ds.walk() also visits items inside # sequences, where IDs such as AccessionNumber are often repeated def scrub(dataset, elem): if elem.keyword in ('PatientName', 'PatientID'): dataset[elem.tag].value = 'ANONYMOUS' elif elem.keyword == 'PatientBirthDate': dataset[elem.tag].value = '19000101' elif elem.keyword in tags_to_anonymize + ['AccessionNumber']: del dataset[elem.tag] ds.walk(scrub) # Vendor private tags frequently carry identifiers ds.remove_private_tags() # Replace dates consistently (e.g. one per-patient offset) to keep intervals meaningful if hasattr(ds, 'StudyDate'): ds.StudyDate = '20000101' ds.PatientIdentityRemoved = 'YES' # Keep pixel data intact ds.save_as('anonymized.dcm') ``` Use the provided script (it walks sequences and warns when `BurnedInAnnotation` is YES): `uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/anonymize_dicom.py input.dcm output.dcm` A tag list like this is a starting point, not a complete de-identification. Identifiers also hide in other date/time elements, UIDs, accession numbers, nested sequences, free-text fields, and text burned into the pixels (check `BurnedInAnnotation` and inspect ultrasound/secondary-capture images). For data leaving your institution, apply a profile based on DICOM PS3.15 Annex E (Basic Application Level Confidentiality Profile) with a dedicated tool such as `deid` (pydicom project) or `dicognito`, and have the output reviewed before release — the same standard your IRB or data use agreement will expect. ### Writing DICOM Files Create DICOM files from scratch: ```python import pydicom from pydicom.dataset import Dataset, FileDataset, FileMetaDataset from datetime import datetime import numpy as np # Create file meta information (use FileMetaDataset, not a bare Dataset) file_meta = FileMetaDataset() file_meta.MediaStorageSOPClassUID = pydicom.uid.CTImageStorage file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid() file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian # Create the FileDataset instance ds = FileDataset('new_dicom.dcm', {}, file_meta=file_meta, preamble=b"\0" * 128) # Add required DICOM elements ds.PatientName = "Test^Patient" ds.PatientID = "123456" ds.Modality = "CT" ds.StudyDate = datetime.now().strftime('%Y%m%d') ds.StudyTime = datetime.now().strftime('%H%M%S') ds.ContentDate = ds.StudyDate ds.ContentTime = ds.StudyTime # Add image-specific elements ds.SamplesPerPixel = 1 ds.PhotometricInterpretation = "MONOCHROME2" ds.Rows = 512 ds.Columns = 512 ds.BitsAllocated = 16 ds.BitsStored = 16 ds.HighBit = 15 ds.PixelRepresentation = 0 # Create pixel data (pydicom >= 3.0 alternative for the block above and this one: # ds.set_pixel_data(pixel_array, photometric_interpretation="MONOCHROME2", bits_stored=12)) pixel_array = np.random.randint(0, 4096, (512, 512), dtype=np.uint16) ds.PixelData = pixel_array.tobytes() # Add required UIDs ds.SOPClassUID = pydicom.uid.CTImageStorage ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID ds.SeriesInstanceUID = pydicom.uid.generate_uid() ds.StudyInstanceUID = pydicom.uid.generate_uid() # Save the file ds.save_as('new_dicom.dcm') ``` ### Compression and Decompression Handle compressed DICOM files: ```python import pydicom # Read compressed DICOM file ds = pydicom.dcmread('compressed.dcm') # Check transfer syntax print(f"Transfer Syntax: {ds.file_meta.TransferSyntaxUID}") print(f"Transfer Syntax Name: {ds.file_meta.TransferSyntaxUID.name}") # Decompress and save as uncompressed (Transfer Syntax becomes Explicit VR LE) ds.decompress() ds.save_as('uncompressed.dcm', enforce_file_format=True) # Or compress (RLE Lossless works with numpy alone) ds_uncompressed = pydicom.dcmread('uncompressed.dcm') ds_uncompressed.compress(pydicom.uid.RLELossless) ds_uncompressed.save_as('compressed_rle.dcm') ``` pydicom 3.0 can **encode** only RLE Lossless (native, `pylibjpeg-rle`, or `gdcm`), JPEG-LS Lossless/Near-Lossless (`pyjpegls`), and JPEG 2000 Lossless/lossy (`pylibjpeg-openjpeg`). JPEG Baseline and JPEG Lossless are decode-only — `compress()` raises `NotImplementedError` for them. **Common transfer syntaxes:** - `ExplicitVRLittleEndian` - Uncompressed, most common - `JPEGBaseline8Bit` - JPEG lossy compression - `JPEGLossless` - JPEG lossless compression - `JPEG2000Lossless` - JPEG 2000 lossless - `RLELossless` - Run-Length Encoding lossless See `references/transfer_syntaxes.md` for complete list. ### Working with DICOM Sequences Handle nested data structures: ```python import pydicom ds = pydicom.dcmread('file.dcm') # Access sequences if 'ReferencedStudySequence' in ds: for item in ds.ReferencedStudySequence: print(f"Referenced SOP Instance UID: {item.ReferencedSOPInstanceUID}") # Create a sequence from pydicom.sequence import Sequence sequence_item = Dataset() sequence_item.ReferencedSOPClassUID = pydicom.uid.CTImageStorage sequence_item.ReferencedSOPInstanceUID = pydicom.uid.generate_uid() ds.ReferencedImageSequence = Sequence([sequence_item]) ``` ### Processing DICOM Series Work with multiple related DICOM files: ```python import pydicom import numpy as np from pathlib import Path # Read all DICOM files in a directory dicom_dir = Path('dicom_series/') slices = [] for file_path in dicom_dir.glob('*.dcm'): ds = pydicom.dcmread(file_path) slices.append(ds) # Sort by slice location or instance number slices.sort(key=lambda x: float(x.ImagePositionPatient[2])) # Or: slices.sort(key=lambda x: int(x.InstanceNumber)) # Create 3D volume volume = np.stack([s.pixel_array for s in slices]) print(f"Volume shape: {volume.shape}") # (num_slices, rows, columns) # Get spacing information for proper scaling pixel_spacing = slices[0].PixelSpacing # [row_spacing, col_spacing] slice_thickness = slices[0].SliceThickness print(f"Voxel size: {pixel_spacing[0]}x{pixel_spacing[1]}x{slice_thickness} mm") ``` ## Helper Scripts This skill includes utility scripts in the `scripts/` directory: ### anonymize_dicom.py Anonymize DICOM files by removing or replacing Protected Health Information (PHI). ```bash uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/anonymize_dicom.py input.dcm output.dcm ``` ### dicom_to_image.py Convert DICOM files to common image formats (PNG, JPEG, TIFF). ```bash uv run --python ">=3.11" --with "pydicom>=3.0" --with pillow --with numpy python scripts/dicom_to_image.py input.dcm output.png uv run --python ">=3.11" --with "pydicom>=3.0" --with pillow --with numpy python scripts/dicom_to_image.py input.dcm output.jpg --format JPEG ``` ### extract_metadata.py Extract and display DICOM metadata in a readable format. ```bash uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/extract_metadata.py file.dcm uv run --python ">=3.11" --with "pydicom>=3.0" python scripts/extract_metadata.py file.dcm --output metadata.txt ``` ## Reference Materials Detailed reference information is available in the `references/` directory: - **common_tags.md**: Comprehensive list of commonly used DICOM tags organized by category (Patient, Study, Series, Image, etc.) - **transfer_syntaxes.md**: Complete reference of DICOM transfer syntaxes and compression formats ## Common Issues and Solutions **Issue: "Unable to decode pixel data"** - Solution: Add compression handlers to the run: `uv run --python ">=3.11" --with "pydicom>=3.0" --with pylibjpeg --with pylibjpeg-libjpeg --with pylibjpeg-openjpeg --with python-gdcm python script.py` **Issue: "AttributeError" when accessing tags** - Solution: Check if attribute exists with `hasattr(ds, 'AttributeName')` or use `ds.get('AttributeName', default)` **Issue: Incorrect image display (too dark/bright)** - Solution: Apply the modality LUT, then the VOI LUT: `apply_voi_lut(apply_modality_lut(pixel_array, ds), ds)`, or window the rescaled values manually with `WindowCenter` and `WindowWidth`. Windowing raw stored values of a CT with RescaleIntercept -1024 shifts every window by 1024 HU **Issue: Memory issues with large series** - Solution: Process files iteratively, use memory-mapped arrays, or downsample images ## Best Practices 1. **Always check for required attributes** before accessing them using `hasattr()` or `get()` 2. **Preserve original encoding** when modifying files: plain `ds.save_as(path)` keeps the source layout (pydicom 3.x makes this the default); pass `enforce_file_format=True` only when you need a fully standard-compliant File Format output 3. **Use Transfer Syntax UIDs** to understand compression format before processing pixel data 4. **Handle exceptions** when reading files from untrusted sources 5. **Apply proper windowing** (VOI LUT) for medical image visualization 6. **Maintain spatial information** (pixel spacing, slice thickness) when processing 3D volumes 7. **Verify anonymization** thoroughly before sharing medical data (private tags, burned-in text, UIDs, and dates included) 8. **Use UIDs correctly** - generate new UIDs when creating new instances, preserve them when modifying ## Documentation Official pydicom documentation (stable = current 3.x release): https://pydicom.github.io/pydicom/stable/ - User Guide: https://pydicom.github.io/pydicom/stable/guides/user/index.html - Tutorials: https://pydicom.github.io/pydicom/stable/tutorials/index.html - API Reference: https://pydicom.github.io/pydicom/stable/reference/index.html - v3.0 release notes (API migration): https://pydicom.github.io/pydicom/stable/release_notes/v3.0.0.html Part of the AlterLab Academic Skills suite.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.