Computer vision: Colour to greyscale

Most image algorithms work on one brightness value per pixel. Convert a colour image the way OpenCV and Pillow do.

What to build

A program that converts an RGB image to greyscale with the luma weights.

Requirements

  • For each pixel, print (299 R + 587 G + 114 B + 500) // 1000.
  • Print one line per image row, values separated by spaces.

Input

Line 1: H and W. Then H lines, each with W pixels written as R,G,B and separated by spaces.

Output

H lines of W greyscale values.

Constraints

1 ≤ H, W ≤ 100; every channel is from 0 to 255.

Example

Input:

1 3
255,0,0 0,255,0 0,0,255

Output:

76 150 29

Why it works

The weights 0.299, 0.587 and 0.114 match how bright each colour looks to people, and adding 500 before dividing by 1000 rounds to the nearest whole number.

Examples

Example 1 · Input
1 3
255,0,0 0,255,0 0,0,255
Expected output
76 150 29
Example 2 · Input
2 2
0,0,0 255,255,255
128,128,128 255,255,0
Expected output
0 255
128 226

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Split each pixel such as `193,107,60` at the commas to get its three numbers.

Hint 2

Use whole-number arithmetic: `(299 * r + 587 * g + 114 * b + 500) // 1000`.

Solution

Show one correct solution (try it yourself first)
h, w = map(int, input().split())
for _ in range(h):
    pixels = [tuple(map(int, p.split(","))) for p in input().split()]
    print(" ".join(str((299 * r + 587 * g + 114 * b + 500) // 1000) for r, g, b in pixels))

Lesson: Colour channels, colour spaces and greyscale →