#135Edges — the horizontal gradientEasy

Edges — the horizontal gradient

Background

The simplest low-level feature is an edge: a place where intensity changes sharply. The crudest edge detector is just the difference between horizontally adjacent pixels,

gr,c=imgr,c+1imgr,cg_{r,c} = \text{img}_{r,\,c+1} - \text{img}_{r,\,c}

Large g|g| marks a vertical edge (a left–right intensity jump); flat regions give g0g \approx 0. CNNs learn filters like this in their first layers instead of hand-coding them.

Problem statement

Implement horizontal_gradient(img) returning the per-pixel horizontal difference of a grayscale image.

Input

  • img — array-like of shape (H, W).

Output

Returns an np.ndarray of shape (H, W - 1): img[:, 1:] - img[:, :-1].

Examples

Example 1

Input:  img = [[1, 2, 4], [0, 0, 5]]
Output: [[1 2], [0 5]]

Explanation: differences along each row.

Example 2 — a sharp vertical edge

Input:  img = [[0, 0, 9, 9]]
Output: [[0 9 0]]

Explanation: the jump from 0→9 lights up; flat runs are 0.

Constraints

  • Compute img[:, 1:] - img[:, :-1].
  • Output width is W - 1.

Notes

  • This is a 1×2 convolution with kernel [-1, 1]. A CNN's first layer learns a bank of such small filters (edges at many orientations) rather than this single fixed one.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • example row differences
  • reference sharp vertical edge
  • sample flat image zeros