Computer vision: A 3 x 3 mean filter

The mean filter is the simplest way to soften noise.

What to build

A program that applies a 3 × 3 mean filter to the inside of an image.

Requirements

  • Each pixel that has all eight neighbours becomes (sum of its 3 × 3 window + 4) // 9.
  • Pixels on the border keep their values.
  • Print H rows of W values.

Input

Line 1: H and W. Then H rows of W values from 0 to 255.

Output

H rows.

Constraints

1 ≤ H, W ≤ 60.

Example

Input:

3 3
0 0 0
0 90 0
0 0 0

Output:

0 0 0
0 10 0
0 0 0

Why it works

Averaging nine neighbouring values lets random errors partly cancel; reading only the original image keeps every window independent of the others.

Examples

Example 1 · Input
3 3
0 0 0
0 90 0
0 0 0
Expected output
0 0 0
0 10 0
0 0 0
Example 2 · Input
3 4
10 20 30 40
10 20 30 40
10 20 30 100
Expected output
10 20 30 40
10 20 37 40
10 20 30 100

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

Hints

Hint 1

Copy the image first (`[row[:] for row in img]`) and write the results into the copy, reading only from the original.

Hint 2

Adding 4 before dividing by 9 rounds to the nearest whole number.

Solution

Show one correct solution (try it yourself first)
h, w = map(int, input().split())
img = [list(map(int, input().split())) for _ in range(h)]
out = [row[:] for row in img]
for r in range(1, h - 1):
    for c in range(1, w - 1):
        s = sum(img[r + i][c + j] for i in (-1, 0, 1) for j in (-1, 0, 1))
        out[r][c] = (s + 4) // 9
for row in out:
    print(" ".join(map(str, row)))

Lesson: Blurring and noise removal →