Grayscale: Weighting Colours the Way Eyes Do

Computer VisionEasy+10 XP+10

Grayscale: Weighting Colours the Way Eyes Do

Flattening a colour image to one channel seems like it should be an average of red, green and blue. It isn't — the eye is far more sensitive to green than to blue, so a plain average makes blues look unnaturally bright and greens unnaturally dull.

The standard luminance weights match human sensitivity instead:

gray=0.299R+0.587G+0.114Bgray = 0.299 R + 0.587 G + 0.114 Bgray=0.299R+0.587G+0.114B

Task: write to_grayscale(rgb) returning a 2D grid of brightness values, each rounded to 4 decimal places.

  • rgb is a grid of pixels, where each pixel is a three-item list [R, G, B].
  • The output has the same height and width, with one number per pixel instead of three.
  • Don't round to integers — return the 4-decimal value.

Notice the weights sum to exactly 1.0. That's what keeps the brightness range intact: pure white [255, 255, 255] comes out as exactly 255, and pure black as 0. Weights summing to anything else would darken or brighten the whole image.

And look at what the individual channels produce. Pure red lands around 76, pure green around 150, pure blue around 29 — a factor of five between the brightest and darkest of the three primaries, all at full intensity. That's the perceptual difference a naive average throws away, and it's why converting a colourful chart to greyscale with the wrong formula can make distinct colours collapse into the same shade.

Examples

rgb = [[[255, 0, 0], [0, 255, 0]]]
returns [[76.245, 149.685]]
rgb = [[[0, 0, 0], [255, 255, 255]]]
returns [[0.0, 255.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run