pylibjpeg: JPEG and DICOM RLE Decoder Framework

2.1.0 · active · verified Fri Apr 17

pylibjpeg is a Python framework for decoding JPEG and decoding/encoding DICOM RLE data, primarily designed to support pydicom. It provides a flexible handler system that allows different backend implementations for JPEG and RLE to be used. The current version is 2.1.0, and it follows an infrequent release cadence, often tied to significant architectural changes or `pydicom`'s decoding needs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install `pylibjpeg` and its necessary backend handlers, then registers them with the `pydicom` library to enable decoding of compressed DICOM pixel data (JPEG, RLE). You must install the `pylibjpeg-libjpeg` and/or `pylibjpeg-rle` packages separately to enable their respective decoding capabilities. The `DICOM_FILE_PATH` environment variable can be set to point to a test DICOM file.

import pydicom
import pylibjpeg
import os

# Ensure you have installed a backend, e.g., 'pip install pylibjpeg-libjpeg'
# and optionally 'pip install pylibjpeg-rle' for RLE support.

try:
    import pylibjpeg_libjpeg
    # Register the JPEG handler. For pydicom, registering the top-level package
    # automatically adds all handlers within it.
    pylibjpeg.add_handler(pylibjpeg_libjpeg)
    print("pylibjpeg_libjpeg handler successfully added.")
except ImportError:
    print("Warning: pylibjpeg-libjpeg is not installed. JPEG decoding will not be available.")

try:
    import pylibjpeg_rle
    pylibjpeg.add_handler(pylibjpeg_rle)
    print("pylibjpeg_rle handler successfully added.")
except ImportError:
    print("Warning: pylibjpeg-rle is not installed. RLE decoding/encoding will not be available.")

print(f"Current active pylibjpeg handlers: {pylibjpeg.get_handlers()}")

# Example: Decode a DICOM file using pydicom (requires a valid DICOM file)
# Set DICOM_FILE_PATH environment variable for testing, e.g., an image with JPEG/RLE compression
dicom_file_path = os.environ.get('DICOM_FILE_PATH', 'path/to/your/compressed_dicom.dcm')

if os.path.exists(dicom_file_path):
    try:
        ds = pydicom.dcmread(dicom_file_path)
        if hasattr(ds, 'pixel_array'):
            pixel_array = ds.pixel_array
            print(f"Successfully decoded pixel data from '{dicom_file_path}' with shape: {pixel_array.shape}")
        else:
            print(f"DICOM file '{dicom_file_path}' does not contain pixel data or could not be decoded by available handlers.")
    except Exception as e:
        print(f"Error reading DICOM file or decoding pixel data: {e}")
else:
    print(f"Skipping DICOM decode example: DICOM_FILE_PATH '{dicom_file_path}' not found or not set.")

view raw JSON →