#141RGB to grayscale (luminosity)Easy

RGB to grayscale (luminosity)

Background

Converting colour to grayscale isn't a plain average — human eyes are more sensitive to green than red or blue. The standard luminosity weights are:

Y=0.299R+0.587G+0.114BY = 0.299\,R + 0.587\,G + 0.114\,B

applied per pixel.

Problem statement

Implement rgb_to_grayscale(img) converting an RGB image to a grayscale matrix using the luminosity weights.

Input

  • img — array-like of shape (H, W, 3): RGB intensities.

Output

Returns an np.ndarray of shape (H, W): the grayscale intensity per pixel.

Examples

Example 1 — white stays white

Input:  img = [[[255, 255, 255]]]
Output: [[255.]]

Explanation: 0.299+0.587+0.114=1.00.299+0.587+0.114 = 1.0, so 255×1.0=255255 \times 1.0 = 255.

Example 2 — pure colors

Input:  img = [[[255, 0, 0], [0, 255, 0]]]
Output: [[76.245 149.685]]

Explanation: red → 0.299×255=76.2450.299\times255=76.245; green → 0.587×255=149.6850.587\times255=149.685.

Constraints

  • Apply weights [0.299, 0.587, 0.114] along the channel axis.
  • Return shape (H, W).

Notes

  • Because green carries the most luminance weight, a pure-green pixel looks brighter in grayscale than a pure-red or pure-blue one of the same intensity.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Example pure red and green
  • Reference mixed colours match weights
  • Sample pure blue is dim