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,
Large marks a vertical edge (a left–right intensity jump); flat regions give . 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.
▶ 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