Install & Compatibility
Where this runs
tested against v3.0.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.634s · 38.2MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 2.4s · import 0.626s · 39MB
31MB installed
● package 31MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
dcmread
✓ from pydicom import dcmread
✗ import dicom; ds = dicom.read_file(filename)
Prior to v1.0, the package was imported as `dicom`. Since v3.0, `read_file` and `write_file` have been removed in favor of `dcmread` and `dcmwrite`.
Dataset
✓ from pydicom.dataset import Dataset
This quickstart demonstrates how to read a DICOM file (either a test file or a minimal dummy file), access and modify its metadata elements, and save the changes to a new file. It also shows how to access the pixel data as a NumPy array if available. The example handles the creation of a minimal DICOM file if no test data is readily accessible.
import os
import pydicom
from pydicom.data import get_testdata_files
# Create a dummy DICOM file for demonstration if it doesn't exist
# In a real scenario, you would read an existing .dcm file.
try:
# Using a test file provided by pydicom
filename = get_testdata_files("CT_small.dcm")[0]
ds = pydicom.dcmread(filename)
print(f"Successfully read: {filename}")
except Exception as e:
print(f"Could not read test file: {e}. Creating a minimal dataset.")
# Create a dummy dataset if test files are unavailable or for new creation
from pydicom.dataset import Dataset, FileDataset, FileMetaDataset
from pydicom.uid import generate_uid
file_meta = FileMetaDataset()
file_meta.MediaStorageSOPClassUID = '1.2.840.10008.5.1.4.1.1.2' # CT Image Storage
file_meta.MediaStorageSOPInstanceUID = generate_uid()
file_meta.ImplementationClassUID = generate_uid()
ds = FileDataset("dummy.dcm", {}, file_meta=file_meta, preamble=b"\0" * 128)
ds.PatientName = "Doe^John"
ds.PatientID = "123456"
ds.Modality = "CT"
ds.StudyInstanceUID = generate_uid()
ds.SeriesInstanceUID = generate_uid()
ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID
ds.SOPClassUID = file_meta.MediaStorageSOPClassUID
ds.BodyPartExamined = "CHEST"
ds.Rows = 128
ds.Columns = 128
ds.BitsAllocated = 16
ds.BitsStored = 12
ds.HighBit = 11
ds.PixelRepresentation = 0 # unsigned
ds.PhotometricInterpretation = "MONOCHROME2"
ds.SamplesPerPixel = 1
ds.PixelData = b'\x00\x00' * ds.Rows * ds.Columns # Dummy pixel data
ds.is_little_endian = True
ds.is_implicit_VR = False
ds.save_as("dummy.dcm")
filename = "dummy.dcm"
ds = pydicom.dcmread(filename)
# Accessing DICOM elements
print(f"Patient Name: {ds.PatientName}")
print(f"Modality: {ds.Modality}")
# Modifying DICOM elements
ds.PatientName = "Smith^Jane"
print(f"New Patient Name: {ds.PatientName}")
# Adding new elements (if not present in the dictionary, define VR first)
if 'PhysicianOfRecord' not in ds:
ds.add_new('00080090', 'PN', 'Dr. Who') # Tag, VR, Value
else:
ds.PhysicianOfRecord = 'Dr. New'
print(f"Physician Of Record: {ds.PhysicianOfRecord}")
# Saving the modified dataset to a new file
output_filename = "modified_image.dcm"
ds.save_as(output_filename)
print(f"Modified DICOM saved to: {output_filename}")
# Accessing pixel data (requires numpy)
if 'PixelData' in ds and 'numpy' in globals():
try:
pixel_array = ds.pixel_array
print(f"Pixel data shape: {pixel_array.shape}")
except Exception as e:
print(f"Could not access pixel_array: {e}. Is numpy installed?")
# Clean up (optional)
# os.remove(output_filename)
# if filename == "dummy.dcm":
# os.remove(filename)
Debug
Known issues
breakingThe functions `read_file()` and `write_file()` have been removed in pydicom v3.0. Users should now use `pydicom.dcmread()` and `pydicom.dcmwrite()` respectively. Additionally, `Dataset.pixel_array` now converts YCbCr Pixel Data to RGB by default. Python versions older than 3.10 are no longer supported.fixReplace `read_file()` with `dcmread()` and `write_file()` with `dcmwrite()`. Ensure your environment uses Python 3.10 or newer. Be aware of potential changes in pixel data color space conversion.
affects: >=3.0.0
breakingThe main package import changed from `import dicom` to `import pydicom` in v1.0. Older code relying on `import dicom` will fail.fixUpdate all import statements from `import dicom` to `import pydicom`.
affects: >=1.0.0
deprecatedThe `pydicom.pixel_data_handlers` module is deprecated and will be removed in v4.0. Users should migrate to the `pydicom.pixels` module for pixel data handling.fixRefactor code to use classes and functions from `pydicom.pixels` instead of `pydicom.pixel_data_handlers`.
affects: >=3.0.0
gotchaHandling compressed pixel data (e.g., JPEG, JPEG 2000) requires additional, optional third-party libraries (`numpy`, `pillow`, `gdcm`, `jpeg_ls`, `pylibjpeg` with its plugins). `PixelData` stores raw bytes, and direct modification of compressed pixel data usually requires decompression first.fixInstall necessary optional dependencies for specific compressed transfer syntaxes. Convert to `pixel_array` (requires `numpy`) for image processing. Decompress pixel data before modification if working with compressed images.
affects: All versions
gotchaAccessing private DICOM tags by keyword (e.g., `ds.PrivateTag`) is generally not possible. They must be accessed by their tag number (e.g., `ds[0xGGXXEEEE]`) or iterated using `ds.dir()` and inspected.fixWhen working with private tags, use their full tag number in hexadecimal format or iterate through `ds.elements()` and check `elem.is_private`.
affects: All versions
gotchaTo prepare for future breaking changes, pydicom provides a 'future behavior' flag. Running with this flag can help identify code incompatibilities with upcoming major versions.fixEnable the future behavior by setting the environment variable `PYDICOM_FUTURE=True` or by calling `from pydicom import config; config.future_behavior(True)` in your code, then test your application thoroughly.
affects: All versions (for future-proofing)
Errors
Common errors & fixes
pydicom.errors.InvalidDicomError: File is missing DICOM File Meta Information header or the 'DICM' prefix is missing from the header.
The file being read is either not a valid DICOM file, or it's a DICOM file that is missing the standard DICOM File Meta Information Header (including the 'DICM' prefix at byte offset 128).
fixUse the `force=True` argument when calling `pydicom.dcmread()` to force pydicom to attempt reading the file even without a proper header.
AttributeError: 'list' object has no attribute 'pixel_array'
This error occurs when attempting to access the `pixel_array` attribute directly on a Python list containing multiple `pydicom.Dataset` objects, instead of on an individual `Dataset` object within the list.
fixIterate through the list to access `pixel_array` for each individual `Dataset`, or select a specific dataset from the list before accessing its `pixel_array` attribute.
ModuleNotFoundError: No module named 'pydicom'
The `pydicom` library is either not installed in the current Python environment, or for very old versions (pre-1.0), the package was imported as `dicom` instead of `pydicom`.
fixEnsure `pydicom` is installed via `pip install pydicom`. For current versions of pydicom, the correct import statement is `import pydicom`.
ModuleNotFoundError: No module named 'pydicom.encoders.gdcm' (or 'pydicom.encoders.pylibjpeg', 'openjpeg', 'jpeg_ls')
Pydicom relies on optional external libraries (plugins) like GDCM, pylibjpeg, jpeg_ls, or openjp2 for handling pixel data, especially for compressed DICOM formats. This `ModuleNotFoundError` indicates that a specific required backend library for a particular compressed DICOM transfer syntax is not installed or accessible in the Python environment.
fixInstall the missing optional dependency corresponding to the encoder mentioned in the error. For example, if 'gdcm' is missing, install it using `pip install gdcm` (or `conda install -c conda-forge gdcm`). If 'pylibjpeg' is missing, install with `pip install pylibjpeg pylibjpeg-openjp2 pylibjpeg-rle`. For 'jpeg_ls', use `pip install jpeg_ls`.
Upgrade
Version history
3.0.2latest on PyPI · released Mar 19, 2026
Audit
Dependencies
numpyoptionalRecommended for general use; required for manipulating pixel data and accessing `Dataset.pixel_array`.
pillowoptionalOptional, for handling certain compressed pixel data (e.g., JPEG, JPEG 2000).
gdcmoptionalOptional, for handling various compressed pixel data transfer syntaxes.
jpeg_lsoptionalOptional, for JPEG-LS compressed pixel data.
pylibjpegoptionalOptional, framework for decompressing various JPEG and RLE images; requires specific plugins.
pylibjpeg-libjpegoptionalPlugin for `pylibjpeg` to support JPEG compression.
pylibjpeg-openjpegoptionalPlugin for `pylibjpeg` to support JPEG 2000 compression.
pylibjpeg-rleoptionalPlugin for `pylibjpeg` to support RLE compression.
types-pydicomoptionalOptional, for additional type hints when accessing standard element keywords through `Dataset`.