Kumita← Open visual lesson

Edges as Steepest Change

The code behind the picture

Follow the lesson’s implementation, one code cell at a time.

Choose a language and read the cells in order. These are small teaching examples; the visual lesson runs separately.

Follow the calculation

Same inputs · Same operation · Same result

3 teaching cells · Python standard library · Read-only

  1. 1. Prepare the patch and the Sobel filters

    A 3 × 3 patch from the watermelon's lower-right rim (grayscale levels 0–9), and the Sobel x and y kernels. y grows downward.

    import json
    
    patch = [[3, 3, 0], [0, 0, 8], [8, 8, 8]]
    sobel_x = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
    sobel_y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]
  2. 2. Measure the two components

    Each component is the sum of the nine pixel-weight products.

    def apply(kernel):
        return sum(
            patch[i][j] * kernel[i][j]
            for i in range(3)
            for j in range(3)
        )
    
    gx = apply(sobel_x)
    gy = apply(sobel_y)
    squared = gx * gx + gy * gy
  3. 3. Inspect the result

    Gx, Gy and the squared magnitude; its square root is about 26.4.

    print(json.dumps([gx, gy, squared]))

Expected result

Running the three cells in order produces this result in either language.

[
  13,
  23,
  698
]