← back

Convert RGB Image to Grayscale

#237 · Computer Vision · Easy

⊣ Solve on deep-ml.com

Problem

Convert an RGB image to grayscale using the luminosity method, which weights the color channels according to human perception.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def rgb_to_grayscale(image: list[list[list[int]]]) -> list[list[int]]:
    """
    image: [H, W, 3] with R, G, B channels (0-255)
    Returns: [H, W] grayscale image
    """
    H = len(image)
    W = len(image[0])

    gray = []
    for h in range(H):
        row = []
        for w in range(W):
            r, g, b = image[h][w][0], image[h][w][1], image[h][w][2]
            # Luminosity method (ITU-R BT.601)
            val = 0.299 * r + 0.587 * g + 0.114 * b
            row.append(round(val))
        gray.append(row)

    return gray

Explanation

  1. The luminosity method uses weighted coefficients based on human eye sensitivity: R=0.299, G=0.587, B=0.114.
  2. Green has the highest weight because the human eye is most sensitive to green light.
  3. For each pixel, compute the weighted sum and round to the nearest integer.
  4. The output is a single-channel 2D image with values in [0, 255].

Complexity

  • Time: O(H * W) where H and W are image dimensions
  • Space: O(H * W) for the grayscale image