A pure Python package for reading and writing DICOM data
—
Core functionality for reading and writing DICOM files with comprehensive support for various transfer syntaxes, partial reading, metadata extraction, and flexible I/O operations.
Primary function for reading DICOM files from various sources with extensive configuration options for performance optimization and selective data loading.
def dcmread(
fp,
defer_size=None,
stop_before_pixels=False,
force=False,
specific_tags=None
):
"""
Read and parse a DICOM file.
Parameters:
- fp: str, PathLike, or file-like object - File path or file-like object to read
- defer_size: int, str, float, or None - Defer reading large elements above this size threshold
- stop_before_pixels: bool - Stop reading at Pixel Data element (faster when pixels not needed)
- force: bool - Read file even if no DICOM File Meta Information header present
- specific_tags: list of int/tuple - Only read specified tags (faster for large files)
Returns:
FileDataset object containing the DICOM data
"""Primary function for writing DICOM datasets to files with options for format preservation and compression.
def dcmwrite(
filename,
dataset,
/,
*,
implicit_vr=None,
little_endian=None,
enforce_file_format=False,
force_encoding=False,
overwrite=True
):
"""
Write a DICOM dataset to file.
Parameters:
- filename: str, PathLike, or file-like object - Output file path or file-like object
- dataset: Dataset - The dataset to write (positional-only)
- implicit_vr: bool or None - Use implicit VR encoding (keyword-only)
- little_endian: bool or None - Use little endian byte order (keyword-only)
- enforce_file_format: bool - Enforce DICOM File Format requirements (keyword-only)
- force_encoding: bool - Force encoding even with encoding issues (keyword-only)
- overwrite: bool - Overwrite existing files (keyword-only)
Returns:
None
"""Read specific portions of DICOM files without loading the entire dataset, useful for large files or metadata-only operations.
def read_file_meta_info(fp):
"""
Read only the DICOM File Meta Information.
Parameters:
- fp: str, PathLike, or file-like object - File to read from
Returns:
FileMetaDataset containing File Meta Information elements
"""
def read_partial(fileobj, specific_tags=None, stop_when=None):
"""
Read specific data elements from DICOM file without full parsing.
Parameters:
- fileobj: file-like object - File to read from
- specific_tags: list - Only read these specific tags
- stop_when: callable - Function that returns True when to stop reading
Returns:
Dataset containing only the requested elements
"""Advanced functions for custom DICOM file parsing and element-by-element processing.
def data_element_generator(fp, is_implicit_VR, is_little_endian, stop_when=None):
"""
Generate DataElement instances from a DICOM file.
Parameters:
- fp: file-like object - File to read from
- is_implicit_VR: bool - Whether the transfer syntax uses implicit VR
- is_little_endian: bool - Whether the transfer syntax uses little endian byte order
- stop_when: callable - Function that returns True when to stop reading
Yields:
DataElement instances as they are read
"""
def read_dataset(fp, is_implicit_VR, is_little_endian, bytelength=None):
"""
Read dataset from file-like object.
Parameters:
- fp: file-like object - File to read from
- is_implicit_VR: bool - Whether VR is implicit
- is_little_endian: bool - Byte order
- bytelength: int - Number of bytes to read (None for all)
Returns:
Dataset containing the read elements
"""
def read_sequence(fp, is_implicit_VR, is_little_endian, bytelength):
"""
Read a DICOM sequence from file.
Parameters:
- fp: file-like object - File to read from
- is_implicit_VR: bool - Whether VR is implicit
- is_little_endian: bool - Byte order
- bytelength: int - Number of bytes in sequence
Returns:
Sequence object containing datasets
"""Advanced functions for custom DICOM file creation and element-by-element writing.
def write_dataset(fp, dataset, parent_encoding=None):
"""
Write dataset to a file-like object.
Parameters:
- fp: file-like object - File to write to
- dataset: Dataset - Dataset to write
- parent_encoding: tuple - Parent dataset's (VR, endianness) info
Returns:
None
"""
def write_data_element(fp, data_element, encodings=None):
"""
Write a single DataElement to file.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - Element to write
- encodings: tuple - (is_implicit_VR, is_little_endian)
Returns:
None
"""Functions for handling ambiguous Value Representations and ensuring proper DICOM formatting.
def correct_ambiguous_vr(data_element, dataset):
"""
Correct ambiguous VR based on context.
Parameters:
- data_element: DataElement - Element with potentially ambiguous VR
- dataset: Dataset - Context dataset for VR determination
Returns:
DataElement with corrected VR
"""
def correct_ambiguous_vr_element(data_element, dataset, is_little_endian):
"""
Correct element VR when transfer syntax context is known.
Parameters:
- data_element: DataElement - Element to correct
- dataset: Dataset - Context dataset
- is_little_endian: bool - Transfer syntax byte order
Returns:
DataElement with corrected VR
"""Specialized writing functions for specific DICOM Value Representations.
def write_numbers(fp, data_element, struct_format):
"""
Write numeric data elements.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - Numeric element to write
- struct_format: str - Struct format string for packing
Returns:
None
"""
def write_string(fp, data_element, encoding):
"""
Write string data elements with proper encoding.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - String element to write
- encoding: str - Character encoding to use
Returns:
None
"""
def write_text(fp, data_element, encoding):
"""
Write text data elements (UT VR).
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - Text element to write
- encoding: str - Character encoding to use
Returns:
None
"""
def write_PN(fp, data_element, encoding):
"""
Write Person Name data elements.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - Person Name element to write
- encoding: str - Character encoding to use
Returns:
None
"""
def write_DA(fp, data_element):
"""
Write Date (DA) data elements.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - Date element to write
Returns:
None
"""
def write_TM(fp, data_element):
"""
Write Time (TM) data elements.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - Time element to write
Returns:
None
"""
def write_DT(fp, data_element):
"""
Write DateTime (DT) data elements.
Parameters:
- fp: file-like object - File to write to
- data_element: DataElement - DateTime element to write
Returns:
None
"""from pydicom import dcmread
# Read complete DICOM file
dataset = dcmread("image.dcm")
# Read without pixel data for faster metadata access
header_only = dcmread("image.dcm", stop_before_pixels=True)
# Read only specific tags
patient_info = dcmread("image.dcm", specific_tags=[0x00100010, 0x00100020])
# Force reading non-standard files
questionable_file = dcmread("maybe_dicom.bin", force=True)from pydicom.filereader import read_file_meta_info
# Read only File Meta Information
meta_info = read_file_meta_info("image.dcm")
print(f"Transfer Syntax: {meta_info.TransferSyntaxUID}")
print(f"Implementation Class: {meta_info.ImplementationClassUID}")from pydicom.filereader import read_partial
# Read only patient and study information
with open("large_image.dcm", "rb") as f:
patient_study = read_partial(f, specific_tags=[
0x00100010, # Patient Name
0x00100020, # Patient ID
0x0020000D, # Study Instance UID
0x00200010 # Study ID
])from pydicom import dcmread, dcmwrite
# Read original file
dataset = dcmread("original.dcm")
# Modify and save preserving original format
dataset.PatientName = "Anonymous"
dcmwrite("anonymized.dcm", dataset, write_like_original=True)
# Save with new format (will use Explicit VR Little Endian)
dcmwrite("converted.dcm", dataset, write_like_original=False)from pydicom.filereader import data_element_generator
# Process elements one by one without loading entire file
with open("huge_file.dcm", "rb") as f:
# Skip File Meta Information
f.seek(132) # Standard meta info size
for elem in data_element_generator(f, True, True): # Implicit VR, Little Endian
if elem.tag == 0x7FE00010: # Pixel Data
print(f"Found pixel data: {len(elem.value)} bytes")
break
print(f"{elem.keyword}: {elem.value}")Install with Tessl CLI
npx tessl i tessl/pypi-pydicom