pydicom.pixel_data_handlers.util

Utility functions used in the pixel data handlers.

Functions

apply_color_lut(arr[, ds, palette])

Apply a color palette lookup table to arr.

apply_modality_lut(arr, ds)

Apply a modality lookup table or rescale operation to arr.

apply_voi(arr, ds[, index])

Apply a VOI lookup table to arr.

apply_voi_lut(arr, ds[, index, prefer_lut])

Apply a VOI lookup table or windowing operation to arr.

apply_windowing(arr, ds[, index])

Apply a windowing operation to arr.

convert_color_space(arr, current, desired[, ...])

Convert the image(s) in arr from one color space to another.

dtype_corrected_for_endianness(...)

Return a numpy.dtype corrected for system and Dataset endianness.

expand_ybr422(src, bits_allocated)

Return YBR_FULL_422 data expanded to YBR_FULL.

get_expected_length(ds[, unit])

Return the expected length (in terms of bytes or pixels) of the Pixel Data.

get_image_pixel_ids(ds)

Return a dict of the pixel data affecting element's id() values.

get_j2k_parameters(codestream)

Return a dict containing JPEG 2000 component parameters.

get_nr_frames(ds)

Return NumberOfFrames or 1 if NumberOfFrames is None.

pack_bits(arr[, pad])

Pack a binary numpy.ndarray for use with Pixel Data.

pixel_dtype(ds[, as_float])

Return a numpy.dtype for the pixel data in ds.

reshape_pixel_array(ds, arr)

Return a reshaped numpy.ndarray arr.

unpack_bits(src[, as_array])

Unpack the bit-packed data in src.

pydicom.pixel_data_handlers.util.apply_color_lut(arr: np.ndarray, ds: Dataset | None = None, palette: str | UID | None = None) np.ndarray[source]

Apply a color palette lookup table to arr.

New in version 1.4.

If (0028,1201-1203) Palette Color Lookup Table Data are missing then (0028,1221-1223) Segmented Palette Color Lookup Table Data must be present and vice versa. The presence of (0028,1204) Alpha Palette Color Lookup Table Data or (0028,1224) Alpha Segmented Palette Color Lookup Table Data is optional.

Use of this function with the Enhanced Palette Color Lookup Table Module or Supplemental Palette Color LUT Module is not currently supported.

Parameters:
  • arr (numpy.ndarray) – The pixel data to apply the color palette to.

  • ds (dataset.Dataset, optional) – Required if palette is not supplied. A Dataset containing a suitable Image Pixel or Palette Color Lookup Table Module.

  • palette (str or uid.UID, optional) – Required if ds is not supplied. The name of one of the well-known color palettes defined by the DICOM Standard. One of: 'HOT_IRON', 'PET', 'HOT_METAL_BLUE', 'PET_20_STEP', 'SPRING', 'SUMMER', 'FALL', 'WINTER' or the corresponding well-known (0008,0018) SOP Instance UID.

Returns:

The RGB or RGBA pixel data as an array of np.uint8 or np.uint16 values, depending on the 3rd value of (0028,1201) Red Palette Color Lookup Table Descriptor.

Return type:

numpy.ndarray

References

pydicom.pixel_data_handlers.util.apply_modality_lut(arr: np.ndarray, ds: Dataset) np.ndarray[source]

Apply a modality lookup table or rescale operation to arr.

New in version 1.4.

Parameters:
Returns:

An array with applied modality LUT or rescale operation. If (0028,3000) Modality LUT Sequence is present then returns an array of np.uint8 or np.uint16, depending on the 3rd value of (0028,3002) LUT Descriptor. If (0028,1052) Rescale Intercept and (0028,1053) Rescale Slope are present then returns an array of np.float64. If neither are present then arr will be returned unchanged.

Return type:

numpy.ndarray

Notes

When Rescale Slope and Rescale Intercept are used, the output range is from (min. pixel value * Rescale Slope + Rescale Intercept) to (max. pixel value * Rescale Slope + Rescale Intercept), where min. and max. pixel value are determined from (0028,0101) Bits Stored and (0028,0103) Pixel Representation.

References

pydicom.pixel_data_handlers.util.apply_voi(arr: np.ndarray, ds: Dataset, index: int = 0) np.ndarray[source]

Apply a VOI lookup table to arr.

New in version 2.1.

Parameters:
  • arr (numpy.ndarray) – The ndarray to apply the VOI LUT to.

  • ds (dataset.Dataset) – A dataset containing a VOI LUT Module. If (0028,3010) VOI LUT Sequence is present then returns an array of np.uint8 or np.uint16, depending on the 3rd value of (0028,3002) LUT Descriptor, otherwise arr will be returned unchanged.

  • index (int, optional) – When the VOI LUT Module contains multiple alternative views, this is the index of the view to return (default 0).

Returns:

An array with applied VOI LUT.

Return type:

numpy.ndarray

References

pydicom.pixel_data_handlers.util.apply_voi_lut(arr: np.ndarray, ds: Dataset, index: int = 0, prefer_lut: bool = True) np.ndarray[source]

Apply a VOI lookup table or windowing operation to arr.

New in version 1.4.

Changed in version 2.1: Added the prefer_lut keyword parameter

Parameters:
  • arr (numpy.ndarray) – The ndarray to apply the VOI LUT or windowing operation to.

  • ds (dataset.Dataset) – A dataset containing a VOI LUT Module. If (0028,3010) VOI LUT Sequence is present then returns an array of np.uint8 or np.uint16, depending on the 3rd value of (0028,3002) LUT Descriptor. If (0028,1050) Window Center and (0028,1051) Window Width are present then returns an array of np.float64. If neither are present then arr will be returned unchanged.

  • index (int, optional) – When the VOI LUT Module contains multiple alternative views, this is the index of the view to return (default 0).

  • prefer_lut (bool) – When the VOI LUT Module contains both Window Width/Window Center and VOI LUT Sequence, if True (default) then apply the VOI LUT, otherwise apply the windowing operation.

Returns:

An array with applied VOI LUT or windowing operation.

Return type:

numpy.ndarray

Notes

When the dataset requires a modality LUT or rescale operation as part of the Modality LUT module then that must be applied before any windowing operation.

References

pydicom.pixel_data_handlers.util.apply_windowing(arr: np.ndarray, ds: Dataset, index: int = 0) np.ndarray[source]

Apply a windowing operation to arr.

New in version 2.1.

Parameters:
  • arr (numpy.ndarray) – The ndarray to apply the windowing operation to.

  • ds (dataset.Dataset) – A dataset containing a VOI LUT Module. If (0028,1050) Window Center and (0028,1051) Window Width are present then returns an array of np.float64, otherwise arr will be returned unchanged.

  • index (int, optional) – When the VOI LUT Module contains multiple alternative views, this is the index of the view to return (default 0).

Returns:

An array with applied windowing operation.

Return type:

numpy.ndarray

Notes

When the dataset requires a modality LUT or rescale operation as part of the Modality LUT module then that must be applied before any windowing operation.

References

pydicom.pixel_data_handlers.util.convert_color_space(arr: ndarray, current: str, desired: str, per_frame: bool = False) ndarray[source]

Convert the image(s) in arr from one color space to another.

Changed in version 1.4: Added support for YBR_FULL_422

Changed in version 2.2: Added per_frame keyword parameter.

Parameters:
  • arr (numpy.ndarray) – The image(s) as a numpy.ndarray with shape (frames, rows, columns, 3) or (rows, columns, 3).

  • current (str) – The current color space, should be a valid value for (0028,0004) Photometric Interpretation. One of 'RGB', 'YBR_FULL', 'YBR_FULL_422'.

  • desired (str) – The desired color space, should be a valid value for (0028,0004) Photometric Interpretation. One of 'RGB', 'YBR_FULL', 'YBR_FULL_422'.

  • per_frame (bool, optional) – If True and the input array contains multiple frames then process each frame individually to reduce memory usage. Default False.

Returns:

The image(s) converted to the desired color space.

Return type:

numpy.ndarray

References

pydicom.pixel_data_handlers.util.dtype_corrected_for_endianness(is_little_endian: bool, numpy_dtype: dtype) dtype[source]

Return a numpy.dtype corrected for system and Dataset endianness.

Parameters:
  • is_little_endian (bool) – The endianness of the affected Dataset.

  • numpy_dtype (numpy.dtype) – The numpy data type used for the Pixel Data without considering endianness.

Raises:

ValueError – If is_little_endian is None, e.g. not initialized.

Returns:

The numpy data type used for the Pixel Data without considering endianness.

Return type:

numpy.dtype

pydicom.pixel_data_handlers.util.expand_ybr422(src: ByteString, bits_allocated: int) bytes[source]

Return YBR_FULL_422 data expanded to YBR_FULL.

Uncompressed datasets with a (0028,0004) Photometric Interpretation of "YBR_FULL_422" are subsampled in the horizontal direction by halving the number of Cb and Cr pixels (i.e. there are two Y pixels for every Cb and Cr pixel). This function expands the YBR_FULL_422 data to remove the subsampling and the output is therefore YBR_FULL.

Parameters:
  • src (bytes or bytearray) – The YBR_FULL_422 pixel data to be expanded.

  • bits_allocated (int) – The number of bits used to store each pixel, as given by (0028,0100) Bits Allocated.

Returns:

The expanded data (as YBR_FULL).

Return type:

bytes

pydicom.pixel_data_handlers.util.get_expected_length(ds: Dataset, unit: str = 'bytes') int[source]

Return the expected length (in terms of bytes or pixels) of the Pixel Data.

Element

Required or optional

Tag

Keyword

Type

(0028,0002)

SamplesPerPixel

1

Required

(0028,0004)

PhotometricInterpretation

1

Required

(0028,0008)

NumberOfFrames

1C

Optional

(0028,0010)

Rows

1

Required

(0028,0011)

Columns

1

Required

(0028,0100)

BitsAllocated

1

Required

Changed in version 1.4: Added support for a Photometric Interpretation of YBR_FULL_422

Parameters:
  • ds (Dataset) – The Dataset containing the Image Pixel module and Pixel Data.

  • unit (str, optional) – If 'bytes' then returns the expected length of the Pixel Data in whole bytes and NOT including an odd length trailing NULL padding byte. If 'pixels' then returns the expected length of the Pixel Data in terms of the total number of pixels (default 'bytes').

Returns:

The expected length of the Pixel Data in either whole bytes or pixels, excluding the NULL trailing padding byte for odd length data.

Return type:

int

pydicom.pixel_data_handlers.util.get_image_pixel_ids(ds: Dataset) Dict[str, int][source]

Return a dict of the pixel data affecting element’s id() values.

New in version 1.4.

Element

Tag

Keyword

Type

(0028,0002)

SamplesPerPixel

1

(0028,0004)

PhotometricInterpretation

1

(0028,0006)

PlanarConfiguration

1C

(0028,0008)

NumberOfFrames

1C

(0028,0010)

Rows

1

(0028,0011)

Columns

1

(0028,0100)

BitsAllocated

1

(0028,0101)

BitsStored

1

(0028,0103)

PixelRepresentation

1

(7FE0,0008)

FloatPixelData

1C

(7FE0,0009)

DoubleFloatPixelData

1C

(7FE0,0010)

PixelData

1C

Parameters:

ds (Dataset) – The Dataset containing the pixel data.

Returns:

A dict containing the id() values for the elements that affect the pixel data.

Return type:

dict

pydicom.pixel_data_handlers.util.get_j2k_parameters(codestream: bytes) Dict[str, object][source]

Return a dict containing JPEG 2000 component parameters.

New in version 2.1.

Parameters:

codestream (bytes) – The JPEG 2000 (ISO/IEC 15444-1) codestream to be parsed.

Returns:

A dict containing parameters for the first component sample in the JPEG 2000 codestream, or an empty dict if unable to parse the data. Available parameters are {"precision": int, "is_signed": bool}.

Return type:

dict

pydicom.pixel_data_handlers.util.get_nr_frames(ds: Dataset) int[source]

Return NumberOfFrames or 1 if NumberOfFrames is None.

Parameters:

ds (dataset.Dataset) – The Dataset containing the Image Pixel module corresponding to the data in arr.

Returns:

An integer for the NumberOfFrames or 1 if NumberOfFrames is None

Return type:

int

pydicom.pixel_data_handlers.util.pack_bits(arr: ndarray, pad: bool = True) bytes[source]

Pack a binary numpy.ndarray for use with Pixel Data.

New in version 1.2.

Should be used in conjunction with (0028,0100) Bits Allocated = 1.

Changed in version 2.1: Added the pad keyword parameter and changed to allow arr to be 2 or 3D.

Parameters:
  • arr (numpy.ndarray) – The numpy.ndarray containing 1-bit data as ints. arr must only contain integer values of 0 and 1 and must have an ‘uint’ or ‘int’ numpy.dtype. For the sake of efficiency it’s recommended that the length of arr be a multiple of 8 (i.e. that any empty bit-padding to round out the byte has already been added). The input arr should either be shaped as (rows, columns) or (frames, rows, columns) or the equivalent 1D array used to ensure that the packed data is in the correct order.

  • pad (bool, optional) – If True (default) then add a null byte to the end of the packed data to ensure even length, otherwise no padding will be added.

Returns:

The bit packed data.

Return type:

bytes

Raises:

ValueError – If arr contains anything other than 0 or 1.

References

DICOM Standard, Part 5, Section 8.1.1 and Annex D

pydicom.pixel_data_handlers.util.pixel_dtype(ds: Dataset, as_float: bool = False) np.dtype[source]

Return a numpy.dtype for the pixel data in ds.

Suitable for use with IODs containing the Image Pixel module (with as_float=False) and the Floating Point Image Pixel and Double Floating Point Image Pixel modules (with as_float=True).

Element

Supported values

Tag

Keyword

Type

(0028,0101)

BitsAllocated

1

1, 8, 16, 32, 64

(0028,0103)

PixelRepresentation

1

0, 1

Changed in version 1.4: Added as_float keyword parameter and support for float dtypes.

Parameters:
  • ds (Dataset) – The Dataset containing the pixel data you wish to get the data type for.

  • as_float (bool, optional) – If True then return a float dtype, otherwise return an integer dtype (default False). Float dtypes are only supported when (0028,0101) Bits Allocated is 32 or 64.

Returns:

A numpy.dtype suitable for containing the pixel data.

Return type:

numpy.dtype

Raises:

NotImplementedError – If the pixel data is of a type that isn’t supported by either numpy or pydicom.

pydicom.pixel_data_handlers.util.reshape_pixel_array(ds: Dataset, arr: np.ndarray) np.ndarray[source]

Return a reshaped numpy.ndarray arr.

Element

Supported values

Tag

Keyword

Type

(0028,0002)

SamplesPerPixel

1

N > 0

Required

(0028,0006)

PlanarConfiguration

1C

0, 1

Optional

(0028,0008)

NumberOfFrames

1C

N > 0

Optional

(0028,0010)

Rows

1

N > 0

Required

(0028,0011)

Columns

1

N > 0

Required

(0028,0008) Number of Frames is required when Pixel Data contains more than 1 frame. (0028,0006) Planar Configuration is required when (0028,0002) Samples per Pixel is greater than 1. For certain compressed transfer syntaxes it is always taken to be either 0 or 1 as shown in the table below.

Transfer Syntax

Planar Configuration

UID

Name

1.2.840.10008.1.2.4.50

JPEG Baseline

0

1.2.840.10008.1.2.4.57

JPEG Lossless, Non-hierarchical

0

1.2.840.10008.1.2.4.70

JPEG Lossless, Non-hierarchical, SV1

0

1.2.840.10008.1.2.4.80

JPEG-LS Lossless

0

1.2.840.10008.1.2.4.81

JPEG-LS Lossy

0

1.2.840.10008.1.2.4.90

JPEG 2000 Lossless

0

1.2.840.10008.1.2.4.91

JPEG 2000 Lossy

0

1.2.840.10008.1.2.5

RLE Lossless

1

Changed in version 2.1: JPEG-LS transfer syntaxes changed to Planar Configuration of 0

Parameters:
Returns:

A reshaped array containing the pixel data. The shape of the array depends on the contents of the dataset:

  • For single frame, single sample data (rows, columns)

  • For single frame, multi-sample data (rows, columns, planes)

  • For multi-frame, single sample data (frames, rows, columns)

  • For multi-frame, multi-sample data (frames, rows, columns, planes)

Return type:

numpy.ndarray

References

pydicom.pixel_data_handlers.util.unpack_bits(src: bytes, as_array: bool = True) ndarray | bytes[source]

Unpack the bit-packed data in src.

Suitable for use when (0028,0011) Bits Allocated or (60xx,0100) Overlay Bits Allocated is 1.

If NumPy is available then it will be used to unpack the data, otherwise only the standard library will be used, which is about 20 times slower.

Changed in version 2.3: Added the as_array keyword parameter, support for unpacking without NumPy, and added bytes as a possible return type

Parameters:
  • src (bytes) – The bit-packed data.

  • as_array (bool, optional) – If False then return the unpacked data as bytes, otherwise return a numpy.ndarray (default, requires NumPy).

Returns:

The unpacked data as an numpy.ndarray (if NumPy is available and as_array == True) or bytes otherwise.

Return type:

bytes or numpy.ndarray

Raises:

ValueError – If as_array is True and NumPy is not available.

References

DICOM Standard, Part 5, Section 8.1.1 and Annex D