Computer vision: An edge map from gradient magnitude

Turn gradients into a picture of where the edges are.

What to build

A program that computes the Sobel gradient magnitude and marks strong edges.

Requirements

  • For every inner pixel, compute gx and gy with the Sobel kernels and the magnitude √(gx² + gy²), rounded to the nearest whole number (add 0.5 and round down).
  • Print the magnitudes: H − 2 rows of W − 2 values.
  • Then print the edge map, H rows of W characters: # where an inner pixel's magnitude is at least T, . everywhere else (including the border).

Input

Line 1: H, W and the threshold T. Then H rows of W values.

Output

The magnitude rows, then the edge-map rows.

Constraints

3 ≤ H, W ≤ 50; T ≥ 1.

Example

Input:

3 3 30
0 0 10
0 0 10
0 0 10

Output:

40
...
.#.
...

Why it works

The magnitude measures how strongly brightness changes in any direction, so a single threshold on it finds both vertical and horizontal edges.

Examples

Example 1 · Input
3 3 30
0 0 10
0 0 10
0 0 10
Expected output
40
...
.#.
...
Example 2 · Input
3 4 50
0 0 30 30
0 0 30 30
0 0 30 30
Expected output
120 120
....
.##.
....

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

Hints

Hint 1

Compute gx and gy with the Sobel formulas, then `int(math.sqrt(gx * gx + gy * gy) + 0.5)`.

Hint 2

Border pixels have no full window: they are never edges.

Solution

Show one correct solution (try it yourself first)
import math

h, w, t = map(int, input().split())
p = [list(map(int, input().split())) for _ in range(h)]
mag = [[0] * w for _ in range(h)]
for r in range(1, h - 1):
    for c in range(1, w - 1):
        gx = (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])
        gy = (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])
        mag[r][c] = int(math.sqrt(gx * gx + gy * gy) + 0.5)
for r in range(1, h - 1):
    print(" ".join(map(str, mag[r][1:w - 1])))
for r in range(h):
    print("".join("#" if 0 < r < h - 1 and 0 < c < w - 1 and mag[r][c] >= t else "." for c in range(w)))

Lesson: Edges with Sobel gradients →