CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pydicom

A pure Python package for reading and writing DICOM data

Pending
Overview
Eval results
Files

pixel-data-processing.mddocs/

Pixel Data Processing

Advanced pixel data manipulation including array extraction, compression, decompression, color space conversion, and various image processing operations for medical imaging workflows.

Capabilities

Pixel Array Access

Core functions for extracting pixel data from DICOM datasets as NumPy arrays with proper handling of various formats and orientations.

def pixel_array(
    src, 
    *,
    ds_out=None, 
    specific_tags=None, 
    index=None, 
    raw=False, 
    decoding_plugin="", 
    **kwargs
):
    """
    Extract pixel data as NumPy array from various sources.
    
    Parameters:
    - src: str, PathLike, file-like, or Dataset - Source of pixel data
    - ds_out: Dataset or None - Output dataset for metadata (keyword-only)
    - specific_tags: list of int or None - Specific tags to read (keyword-only)
    - index: int or None - Frame index for multi-frame datasets (keyword-only)
    - raw: bool - Return raw pixel data without processing (keyword-only)
    - decoding_plugin: str - Specific decoder plugin to use (keyword-only)
    - **kwargs: Additional keyword arguments for decoders
    
    Returns:
    ndarray - Pixel data array with appropriate shape and dtype
    
    Raises:
    AttributeError - If source has no pixel data
    ImportError - If NumPy not available
    """

def iter_pixels(
    src, 
    *,
    ds_out=None, 
    specific_tags=None, 
    indices=None, 
    raw=False, 
    decoding_plugin="", 
    **kwargs
):
    """
    Iterate over pixel data frames from various sources.
    
    Parameters:
    - src: str, PathLike, file-like, or Dataset - Source of pixel data
    - ds_out: Dataset or None - Output dataset for metadata (keyword-only)
    - specific_tags: list of int or None - Specific tags to read (keyword-only)
    - indices: list of int or None - Specific frame indices to iterate over (keyword-only)
    - raw: bool - Return raw pixel data without processing (keyword-only)
    - decoding_plugin: str - Specific decoder plugin to use (keyword-only)
    - **kwargs: Additional keyword arguments for decoders
    
    Yields:
    ndarray - Individual frame arrays
    """

def get_expected_length(dataset, unit='bytes'):
    """
    Calculate expected pixel data length.
    
    Parameters:
    - dataset: Dataset - DICOM dataset
    - unit: str - Unit for length ('bytes' or 'pixels')
    
    Returns:
    int - Expected length in specified units
    """

Compression and Decompression

Functions for compressing and decompressing pixel data using various DICOM transfer syntaxes.

def compress(dataset, transfer_syntax_uid, encoding_plugin=None, **kwargs):
    """
    Compress pixel data using specified transfer syntax.
    
    Parameters:
    - dataset: Dataset - Dataset to compress
    - transfer_syntax_uid: str - Target transfer syntax UID
    - encoding_plugin: str - Specific encoder to use
    - **kwargs: Additional encoder-specific options
    
    Returns:
    None - Modifies dataset in place
    """

def decompress(dataset, handler_name=None):
    """
    Decompress pixel data to uncompressed format.
    
    Parameters:
    - dataset: Dataset - Dataset to decompress
    - handler_name: str - Specific decoder to use
    
    Returns:
    None - Modifies dataset in place
    """

Image Processing Operations

Advanced image processing functions for medical imaging applications including windowing, LUT applications, and color space conversions.

def apply_windowing(arr, dataset, index=0):
    """
    Apply window/level adjustments to pixel array.
    
    Parameters:
    - arr: ndarray - Input pixel array
    - dataset: Dataset - Dataset containing windowing parameters
    - index: int - Window/level pair index for multi-window datasets
    
    Returns:
    ndarray - Windowed pixel array
    """

def apply_modality_lut(arr, dataset):
    """
    Apply modality LUT transformation.
    
    Parameters:
    - arr: ndarray - Input pixel array
    - dataset: Dataset - Dataset containing modality LUT
    
    Returns:
    ndarray - Transformed pixel array
    """

def apply_voi_lut(arr, dataset, index=0):
    """
    Apply VOI LUT transformation.
    
    Parameters:
    - arr: ndarray - Input pixel array
    - dataset: Dataset - Dataset containing VOI LUT
    - index: int - VOI LUT index
    
    Returns:
    ndarray - Transformed pixel array
    """

def apply_color_lut(arr, dataset, palette='RGB'):
    """
    Apply color palette LUT.
    
    Parameters:
    - arr: ndarray - Input pixel array
    - dataset: Dataset - Dataset containing color LUT
    - palette: str - Target color palette ('RGB', 'BGR', etc.)
    
    Returns:
    ndarray - Color-mapped pixel array
    """

Color Space Conversion

Functions for converting between different color spaces used in medical imaging.

def convert_color_space(arr, current, desired, per_frame=False):
    """
    Convert pixel array between color spaces.
    
    Parameters:
    - arr: ndarray - Input pixel array
    - current: str - Current color space ('RGB', 'YBR_FULL', etc.)
    - desired: str - Desired color space
    - per_frame: bool - Apply conversion per frame
    
    Returns:
    ndarray - Converted pixel array
    """

def apply_icc_profile(arr, dataset):
    """
    Apply ICC color profile transformation.
    
    Parameters:
    - arr: ndarray - Input pixel array
    - dataset: Dataset - Dataset containing ICC profile
    
    Returns:
    ndarray - Color-corrected pixel array
    """

Pixel Data Utilities

Utility functions for pixel data manipulation and format conversion.

def pack_bits(arr):
    """
    Pack pixel array using bit packing.
    
    Parameters:
    - arr: ndarray - Input pixel array
    
    Returns:
    bytes - Packed pixel data
    """

def unpack_bits(data, shape):
    """
    Unpack bit-packed pixel data.
    
    Parameters:
    - data: bytes - Packed pixel data
    - shape: tuple - Expected array shape
    
    Returns:
    ndarray - Unpacked pixel array
    """

def set_pixel_data(dataset, arr, photometric_interpretation=None):
    """
    Set pixel data in dataset from NumPy array.
    
    Parameters:
    - dataset: Dataset - Target dataset
    - arr: ndarray - Pixel array to set
    - photometric_interpretation: str - Color interpretation
    
    Returns:
    None - Modifies dataset in place
    """

def reshape_pixel_array(dataset, arr):
    """
    Reshape pixel array according to DICOM parameters.
    
    Parameters:
    - dataset: Dataset - Dataset with image parameters
    - arr: ndarray - Input pixel array
    
    Returns:
    ndarray - Reshaped array matching DICOM dimensions
    """

Usage Examples

Basic Pixel Array Access

from pydicom import dcmread
from pydicom.pixels.utils import pixel_array
import numpy as np

# Read DICOM file
ds = dcmread("image.dcm")

# Get pixel array
if hasattr(ds, 'pixel_array'):
    pixels = ds.pixel_array
    print(f"Shape: {pixels.shape}")
    print(f"Data type: {pixels.dtype}")
    print(f"Min/Max: {pixels.min()}/{pixels.max()}")
    
    # Alternative using function
    pixels2 = pixel_array(ds)
    assert np.array_equal(pixels, pixels2)

Multi-frame Processing

from pydicom.pixels.utils import iter_pixels

# Process multi-frame dataset frame by frame
ds = dcmread("multiframe.dcm")

for i, frame in enumerate(iter_pixels(ds)):
    print(f"Frame {i}: shape {frame.shape}")
    
    # Process individual frame
    mean_intensity = frame.mean()
    print(f"  Mean intensity: {mean_intensity:.2f}")

# Process specific frames only
for frame in iter_pixels(ds, indices=[0, 5, 10]):
    # Process selected frames
    pass

Image Enhancement

from pydicom.pixels.processing import apply_windowing, apply_modality_lut

# Read CT dataset
ds = dcmread("ct_image.dcm")
pixels = ds.pixel_array

# Apply modality LUT (Hounsfield units for CT)
hu_pixels = apply_modality_lut(pixels, ds)

# Apply window/level for soft tissue viewing
windowed = apply_windowing(hu_pixels, ds, index=0)

# Display-ready pixel values
print(f"Original range: {pixels.min()}-{pixels.max()}")
print(f"HU range: {hu_pixels.min()}-{hu_pixels.max()}")
print(f"Windowed range: {windowed.min()}-{windowed.max()}")

Color Image Processing

from pydicom.pixels.processing import convert_color_space, apply_color_lut

# Read color ultrasound image
ds = dcmread("color_us.dcm")
pixels = ds.pixel_array

# Convert from YBR_FULL to RGB
if ds.PhotometricInterpretation == "YBR_FULL":
    rgb_pixels = convert_color_space(pixels, "YBR_FULL", "RGB")
    ds.PhotometricInterpretation = "RGB"
    
    print(f"Converted from YBR to RGB: {rgb_pixels.shape}")

# Apply color palette for pseudocolor images
if ds.PhotometricInterpretation == "PALETTE COLOR":
    color_pixels = apply_color_lut(pixels, ds)
    print(f"Applied color LUT: {color_pixels.shape}")

Compression Workflows

from pydicom.pixels.utils import compress, decompress

# Read uncompressed image
ds = dcmread("uncompressed.dcm")
original_size = len(ds.PixelData)

# Compress using JPEG 2000 Lossless
compress(ds, "1.2.840.10008.1.2.4.90")
compressed_size = len(ds.PixelData)

print(f"Compression ratio: {original_size/compressed_size:.2f}")

# Decompress back to uncompressed
decompress(ds)
decompressed_size = len(ds.PixelData)

print(f"Round-trip successful: {original_size == decompressed_size}")

Custom Pixel Data Handling

from pydicom.pixels.utils import set_pixel_data, reshape_pixel_array
import numpy as np

# Create synthetic image data
synthetic_image = np.random.randint(0, 4096, (512, 512), dtype=np.uint16)

# Create new dataset
ds = Dataset()
ds.Rows = 512
ds.Columns = 512
ds.BitsAllocated = 16
ds.BitsStored = 12
ds.HighBit = 11
ds.PixelRepresentation = 0
ds.SamplesPerPixel = 1
ds.PhotometricInterpretation = "MONOCHROME2"

# Set pixel data
set_pixel_data(ds, synthetic_image)

# Verify
verify_pixels = ds.pixel_array
print(f"Successfully set pixel data: {np.array_equal(synthetic_image, verify_pixels)}")

Install with Tessl CLI

npx tessl i tessl/pypi-pydicom

docs

configuration-utilities.md

data-elements.md

dataset-manipulation.md

file-operations.md

index.md

pixel-data-processing.md

sequences-collections.md

tags-and-uids.md

value-representations.md

tile.json