Computer vision: Sobel gradients

The Sobel operator measures how fast brightness changes across and down an image.

What to build

A program that computes the Sobel gradients gx and gy at every inner pixel.

Requirements

  • For each pixel with all eight neighbours, gx = (p[r−1][c+1] + 2p[r][c+1] + p[r+1][c+1]) − (p[r−1][c−1] + 2p[r][c−1] + p[r+1][c−1]).
  • gy = (p[r+1][c−1] + 2p[r+1][c] + p[r+1][c+1]) − (p[r−1][c−1] + 2p[r−1][c] + p[r−1][c+1]).
  • Print gx, then H − 2 rows of W − 2 values; then gy and its rows.

Input

Line 1: H and W (both at least 3). Then H rows of W values.

Output

The gx block, then the gy block.

Constraints

3 ≤ H, W ≤ 50.

Example

Input:

3 3
0 0 10
0 0 10
0 0 10

Output:

gx
40
gy
0

Why it works

Subtracting the left column from the right column measures change to the right, and the 1, 2, 1 weights average three rows so single noisy pixels matter less; gy does the same downwards.

Examples

Example 1 · Input
3 3
0 0 10
0 0 10
0 0 10
Expected output
gx
40
gy
0
Example 2 · Input
4 3
0 0 0
0 0 0
5 5 5
5 5 5
Expected output
gx
0
0
gy
20
20

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

Hints

Hint 1

gx at (r, c) is (right column with weights 1, 2, 1) minus (left column with weights 1, 2, 1).

Hint 2

gy at (r, c) is (bottom row with weights 1, 2, 1) minus (top row with weights 1, 2, 1).

Solution

Show one correct solution (try it yourself first)
h, w = map(int, input().split())
p = [list(map(int, input().split())) for _ in range(h)]
gx, gy = [], []
for r in range(1, h - 1):
    gx.append([(p[r - 1][c + 1] + 2 * p[r][c + 1] + p[r + 1][c + 1]) - (p[r - 1][c - 1] + 2 * p[r][c - 1] + p[r + 1][c - 1]) for c in range(1, w - 1)])
    gy.append([(p[r + 1][c - 1] + 2 * p[r + 1][c] + p[r + 1][c + 1]) - (p[r - 1][c - 1] + 2 * p[r - 1][c] + p[r - 1][c + 1]) for c in range(1, w - 1)])
print("gx")
for row in gx:
    print(" ".join(map(str, row)))
print("gy")
for row in gy:
    print(" ".join(map(str, row)))

Lesson: Edges with Sobel gradients →