TIER 1 / brightness-and-overflow

Brightening an image — and the overflow trap

One line instead of two loops

At Tier 0 you inverted an image with nested for loops. numpy does that whole job in one line, because an operation on an array applies to every pixel at once. That is called broadcasting.

`` inverted = 255 - img # every pixel, no loops ``

The trap

Now try to brighten instead of invert. The obvious version is:

`` bright = img + 60 ``

Run it and look at the picture. The dark end brightens correctly — and the bright end turns black.

The image is uint8: every pixel is an 8-bit integer, so it can only hold 0 to 255. A pixel of 220 plus 60 is 280, which does not fit, so it wraps around to 24. Bright becomes dark. numpy does not warn you.

Your task

Brighten the image by 60 without wrapping. Do the arithmetic somewhere wider than 8 bits, clamp the result into 0–255, then convert back:

  • img.astype(np.int16) gives you room to overflow into
  • np.clip(values, 0, 255) clamps anything above 255 down to 255
  • .astype(np.uint8) converts back to an image

Store the result in bright.

Loading Python (runtime)…