PY-72

Adjust Brightness without Unsigned Overflow

  • Medium
  • Image Arrays
  • Python

Task

Write adjust_brightness(image, offset) for an image stored as an array.

image is a non-empty two-dimensional grayscale or three-dimensional multi-channel NumPy array with dtype np.uint8. Each element is an intensity in the inclusive range [0, 255]. offset is an integer; it may be positive or negative. For invalid input, raise ValueError with "invalid brightness input".

Return a new np.uint8 array with the same shape. For every element, add the offset in a signed working type and clip the result to the valid intensity range:

adjusted = min(255, max(0, int(original) + offset))

Convert to np.uint8 only after clipping. Adding directly to an unsigned array can wrap a value below 0 around to a large value, so the working type and the order of operations matter. The source image must remain unchanged, and changing the returned array later must not change it.

Example

For np.array([[0, 10, 250, 255]], dtype=np.uint8) and offset=20, the result is [[20, 30, 255, 255]]. With offset=-20, it is [[0, 0, 230, 235]].

Your implementation

Edit solution.py and keep this function signature:

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