RGB to Luminance

~10 mincode completion

Implement rgb_to_grayscale(image).

  • image has shape (H, W, 3).
  • Return a 2D array of shape (H, W).
  • Use the Rec. 601 weights above.

Examples

White pixel (1,1,1) maps to 1.0

Input
rgb_to_grayscale([[[1, 1, 1]]])
Output
[[1]]

Pure red / green / blue / white 2x2

Input
rgb_to_grayscale([[[10, 0, 0], [0, 10, 0]], [[0, 0, 10], [10, 10, 10]]])
Output
[[2.99, 5.87], [1.14, 10]]

Hints

Hint 1

Use a matrix product rather than nested loops, and check which operand transposes.

Hint 2

Watch for this: used equal one third weights.

Requirements

  • image: array of shape (H, W, 3)

  • Return array of shape (H, W)

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

8 employers weight this skill

4 autonomy companies, 1 defense company, 1 health and bio company, 1 enterprise vendor, 1 AI product company. Top match scores 93.

Python
import numpy as np


def rgb_to_grayscale(image):
    """
    Convert an RGB image to Rec. 601 luminance.

    Args:
        image: array of shape (H, W, 3)

    Returns:
        array of shape (H, W)
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.