Kumita← Open visual lesson

RGB vs Grayscale

The code behind the picture

Follow the lesson’s implementation, one code cell at a time.

Choose a language and read the cells in order. These are small teaching examples; the visual lesson runs separately.

Follow the calculation

Same inputs · Same operation · Same result

3 teaching cells · Python standard library · Read-only

  1. 1. Prepare the inputs

    Four real or demonstration pixels from the lesson: red flesh, a labelled demonstration swatch, green rind and a pale pixel.

    import json
    
    pixels = [[240, 6, 56], [90, 70, 123], [27, 166, 85], [255, 255, 255]]
  2. 2. Combine three channels

    The same weighted rule as the visual lesson, rounded. The red flesh pixel and the violet swatch both give 82: different colours, one gray value.

    result = [round(0.299 * r + 0.587 * g + 0.114 * b) for r, g, b in pixels]
  3. 3. Inspect the result

    Print the result as JSON so both languages use the same output format.

    print(json.dumps(result))

Expected result

Running the three cells in order produces this result in either language.

[
  82,
  82,
  115,
  255
]