TheAlgorithms/Python · error · ValueError

level must be between -255.0 (black) and 255.0 (white)

Error message

level must be between -255.0 (black) and 255.0 (white)

What it means

Raised by change_brightness() in digital_image_processing/change_brightness.py:17 when the `level` argument falls outside [-255.0, 255.0]. The level is applied as `128 + level + (c - 128)` per pixel via PIL's Image.point, so anything beyond ±255 would push 8-bit channel values out of representable range; the check is a documented precondition.

Source

Thrown at digital_image_processing/change_brightness.py:17

from PIL import Image


def change_brightness(img: Image, level: float) -> Image:
    """
    Change the brightness of a PIL Image to a given level.
    """

    def brightness(c: int) -> float:
        """
        Fundamental Transformation/Operation that'll be performed on
        every bit.
        """
        return 128 + level + (c - 128)

    if not -255.0 <= level <= 255.0:
        raise ValueError("level must be between -255.0 (black) and 255.0 (white)")
    return img.point(brightness)


if __name__ == "__main__":
    # Load image
    with Image.open("image_data/lena.jpg") as img:
        # Change brightness to 100
        brigt_img = change_brightness(img, 100)
        brigt_img.save("image_data/lena_brightness.png", format="png")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp before calling: level = max(-255.0, min(255.0, level))
  2. Validate and re-prompt at the input boundary (CLI/UI) with a range message
  3. If you truly need larger shifts, apply the point operation yourself in multiple clamped passes

Example fix

// before
bright = change_brightness(img, user_level)  # user_level=300 -> ValueError

# after
level = max(-255.0, min(255.0, float(user_level)))
bright = change_brightness(img, level)
Defensive patterns

Strategy: validation

Validate before calling

level = max(-255.0, min(255.0, float(level)))
bright = change_brightness(img, level)

Type guard

def is_valid_brightness_level(level) -> bool:
    try:
        return -255.0 <= float(level) <= 255.0
    except (TypeError, ValueError):
        return False

Try / catch

try:
    bright = change_brightness(img, level)
except ValueError:
    level = max(-255.0, min(255.0, level))
    bright = change_brightness(img, level)

Prevention

When it happens

Trigger: change_brightness(img, 300), change_brightness(img, -260), or passing a numpy uint8 overflow artifact (e.g. a wrapped-around value) as level.

Common situations: UI sliders or CLI args with unbounded ranges feeding level directly, or computing level from image statistics without clamping.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/3837b7c899fa99d8. Report an issue: GitHub.