v9.1.1
Menu

RGB to Grayscale

easyFREEWhat is Computer Vision?Color ConversionCV: Introduction to Computer Vision

Implement a function to convert an RGB pixel to grayscale using the luminosity method, which is a widely used technique in Computer Vision. This method involves calculating a weighted average of the RGB values to produce a grayscale value that approximates human perception.

The human eye perceives colors differently, with varying sensitivities to red, green, and blue light, which is why we use weighted averaging to convert RGB to grayscale. The weights used in this method reflect the sensitivity of the human eye to different colors, with green contributing most to perceived luminance.

To perform this conversion, follow these steps:

  1. Extract the RGB values from the input pixel
  2. Apply the weighted sum formula to calculate the grayscale value
  3. Round the result to obtain the final grayscale value
Gray=0.2126×R+0.7152×G+0.0722×BGray = 0.2126 \times R + 0.7152 \times G + 0.0722 \times B

This technique is widely used in image processing applications.

Example

Input
rgb_to_gray([255, 0, 0])
Output
54
Reasoning
  • Input: rgb is one pixel as three intensities [R,G,B][R, G, B], each from 0 (none of that colour) to 255 (full). Here R=255R = 255, G=0G = 0, B=0B = 0: pure, fully saturated red.
  • Weighted sum: each channel is scaled by how bright the eye perceives it. Red contributes 0.2126×255=54.2130.2126 \times 255 = 54.213, green contributes 0.7152×0=00.7152 \times 0 = 0, and blue contributes 0.0722×0=00.0722 \times 0 = 0, so Gray=54.213Gray = 54.213.
  • Rounding: grayscale levels are whole numbers, so 54.21354.213 rounds to the nearest integer, giving the output 54.
  • Notice: the three weights add up to exactly 11, so white [255,255,255][255, 255, 255] maps to 255255 and black maps to 00, which keeps the result inside [0,255][0, 255].
  • Pure green at full intensity would give about 182182 and pure blue only about 1818. A red that looks vivid on screen ends up as a fairly dark gray, because red light counts for far less perceived brightness than green.

Constraints

  • RGB values are in range [0, 255]
  • Return grayscale value rounded to nearest integer
  • Output should be in range [0, 255]

Learn this in

More from CV: Introduction to Computer Vision

solution.py

Test results

Sign in to run your code against the test cases.