Skip to content

SegmentedPaletteColorLUT expands the standard 8-bit palettes to a single entry with NumPy 2 #540

Done

Description

@HEOJUNFO

SegmentedPaletteColorLUT does not expand the 8-bit segmented LUTs of the
DICOM well-known color palettes (PS3.6 Annex B, shipped with pydicom) when
NumPy 2 is installed.

import numpy as np
import highdicom as hd
from pydicom import dcmread
from pydicom.data import get_palette_files

# "Spring" palette, green: 0, 1, 0, 1, 255, 255
ds = dcmread(get_palette_files('spring.dcm')[0])
lut = hd.SegmentedPaletteColorLUT.extract_from_dataset(ds, color='green')
print(lut.number_of_entries, lut.lut_data.shape)
print(lut.apply(np.array([0, 100, 255])))

# Building the same LUT
lut = hd.SegmentedPaletteColorLUT(
    0,
    np.array([0, 1, 0, 1, 255, 255], dtype=np.uint8),
    color='green',
)
print(lut.GreenPaletteColorLookupTableDescriptor)

# "Summer" palette, blue: 9 values and a padding byte
ds = dcmread(get_palette_files('summer.dcm')[0])
lut = hd.SegmentedPaletteColorLUT.extract_from_dataset(ds, color='blue')
print(lut.lut_data.shape)

Output on master (highdicom 0.29.0, numpy 2.5.5, pydicom 3.0.2):

256 (1,)
[0 0 0]
[0, 0, 8]
IndexError: index 10 is out of bounds for axis 0 with size 10

Expected:

256 (256,)
[  0 100 255]
[256, 0, 8]
(256,)

There are two causes, both in _expand_segmented_lut() and
_get_expanded_lut_length() in src/highdicom/pixels.py:

  1. The segment length is read as a NumPy scalar. With NumPy 2 a Python
    integer no longer upcasts it, so range(1, length + 1), i + 2 + length
    and total_length += length are computed in uint8 (or uint16) and wrap
    around. A linear segment of length 255 produces no values and the expanded
    length of a 256 entry LUT becomes 0, which the constructor writes to the
    descriptor where it means 2^16 entries. With NumPy 1.26 the same code gives
    256 entries. A 16-bit LUT with a segment of length 65535 behaves the same way.
  2. Odd length 8-bit data has a trailing padding byte once it has been written
    to a file. The loop treats that byte as the opcode of another segment and
    reads past the end of the data. This one does not depend on the NumPy version.

I have a fix with tests ready and can open a pull request.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions