PY-82

Build a Histogram-Based Contrast Lookup

  • Medium–Hard
  • Image Histograms
  • Python

Task

Write build_histogram_contrast_lookup(image). The image is a non-empty three-dimensional uint8 NumPy array with shape (height, width, channels). Each channel uses the fixed intensity range 0..255.

For each channel independently, count every pixel into a 256-bin histogram; bin v counts values exactly equal to v. Form the inclusive cumulative counts along the intensity axis. Let N = height * width and let c_min be the first positive cumulative count in that channel. If N - c_min > 0, define the lookup for every intensity v by

floor((cumulative[v] - c_min) * 255 / (N - c_min))

clipped to 0..255. If N - c_min == 0 (the channel is constant), use the identity lookup lookup[v] = v for every intensity. This keeps the constant channel unchanged instead of replacing it with black. Apply the channel's lookup to every pixel without changing shape or dtype.

Return a dictionary containing independent arrays under "histogram", "cumulative", "lookup", and "image". The first two have shape (channels, 256) and dtype int64; lookup has that shape and dtype uint8; image has the original shape and dtype. Invalid dimensions or dtype may raise ValueError. Do not modify the input.

Example

If a channel contains only values 10 and 20, its first observed intensity maps to 0 and its last observed intensity maps to 255; unobserved bins are still present in the histogram and cumulative table.

Your implementation

You may import NumPy as np. Do not print or ask for input.