Kumita← Open visual lesson

Give the edges room

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 inputs

    The three rows of the watermelon around the edge pixel at row 10, column 0, first two columns, and the lesson's hand-set filter.

    import json
    
    rows = [[8, 8], [8, 0], [0, 4]]  # picture rows 9-11, columns 0-1
    kernel = [[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]]
  2. 2. Pad the left edge three ways

    Zero supplies 0, replicate copies column 0, reflect copies column 1 (the mirror without repeating the edge). Then take the weighted sum of each 3 × 3 window.

    def window(policy):
        left = {"zero": lambda r: 0, "replicate": lambda r: r[0], "reflect": lambda r: r[1]}[policy]
        return [[left(r), r[0], r[1]] for r in rows]
    
    def respond(patch):
        return sum(k * v for kr, pr in zip(kernel, patch) for k, v in zip(kr, pr))
    
    result = {p: respond(window(p)) for p in ["zero", "replicate", "reflect"]}
  3. 3. Inspect the result

    Print the result as JSON so both languages use the same output format.

    print(json.dumps(result))

Expected result

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

{
  "zero": 12,
  "replicate": -4,
  "reflect": 0
}