pydicom.pixels.utils.pack_bits#

pydicom.pixels.utils.pack_bits(arr: ndarray | bytes | bytearray, pad: bool = True) bytes[source]#

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

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.

Changed in version 3.1: Allow packing of bytes and bytearray objects when numpy is not installed.

Parameters:
  • arr (numpy.ndarray | bytes | bytearray) –

    The numpy.ndarray, bytes, or bytearray containing 1-bit data as ints/bytes:

    • For a numpy.ndarray, arr must only contain integer values of 0 and 1 and must have an ‘uint’ or ‘int’ numpy.dtype. The input arr should either be shaped as (rows, columns) or (frames, rows, columns) or the equivalent flattened 1D array used to ensure that the packed data is in the correct order.

    • For bytes or bytearray, each byte represents a single pixel and must have a value of either 0 or 1 (i.e. b'\' or b''`). Pixels should be ordered in the same order as a 1D array, i.e. column index changes most frequently, then row index, then frame index.

  • 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