Edges and corners
边缘与角点
Explain why a corner constrains two directions, then compute and test a Harris response from pixels.
edges-cornersA question to test
Look through a small window at a straight stripe. If the stripe moves along its own length, the visible pattern barely changes. Now put the window over an L-shaped junction. Moving in either direction changes the view. A corner is useful for tracking because it constrains two local directions; a long edge mostly constrains one.
An edge is a local intensity transition, not proof of an object boundary. A shadow, reflection or texture can create one. A corner detector measures a particular local image pattern, not the semantic corner of every physical object. We will make these distinctions visible with three synthetic five-by-five patches: a constant patch, a vertical step and a bright quadrant.
A: constant patch. B: vertical step. C: bright quadrant. The blue square marks the evaluated pixel [2,2]; the response uses its three-by-three neighbourhood. Original synthetic data, with black=0 and white=1.
The model and its derivation
For a small displacement , compare a patch with its shifted version. With nonnegative window weights , its squared change is:
A first-order Taylor approximation gives , so:
Each term is an outer product of a gradient with itself. Therefore M is positive semidefinite: no displacement has negative predicted squared error. Its two eigenvalues measure change along principal directions. Two small values indicate little local information; one large and one small value indicate an edge-like patch; two sufficiently large values indicate a corner-like patch. Harris and Stephens use this local-change view. A Combined Corner and Edge Detector
Rather than explicitly diagonalizing M for every response, their measure combines determinant and trace:
We use . For an ideal edge with eigenvalues , R is −0.09. For our quadrant patch, the centre matrix is:
A positive response is not sufficient for a useful corner: both eigenvalues can be tiny. A detector must also choose a strength threshold and isolated local maxima. If image intensities are multiplied by a positive gain a, gradients scale by a, M by a², and R by a⁴. Reusing an absolute threshold across different intensity scales can therefore change detections drastically.
Edge thinning answers another question. Canny formulates detection, localization and single-response criteria. Nonmaximum suppression keeps a gradient-magnitude peak across an edge; hysteresis lets weaker responses survive when connected to strong ones. This is different from selecting two-directional corner structure. The following program computes Harris responses only, not a Canny detector. A Computational Approach to Edge Detection
Run a small experiment
The derivatives are centred differences divided by two. Gradient products are summed over a three-by-three uniform window, using replicated boundary values in both operations. The window is a sum, not a mean or a Gaussian window; changing it changes the numeric responses. Use Python 3.12 and NumPy 1.26.4.
import numpy as np
def harris(image, k=.04):
a=np.asarray(image,dtype=float)
if a.ndim!=2 or min(a.shape,default=0)<3 or not np.isfinite(a).all():
raise ValueError('need a finite grayscale image at least 3x3')
if not np.isfinite(k) or not 0<k<.25:
raise ValueError('k must lie between 0 and .25 for this example')
padded=np.pad(a,1,mode='edge')
gx=(padded[1:-1,2:]-padded[1:-1,:-2])/2
gy=(padded[2:,1:-1]-padded[:-2,1:-1])/2
def window_sum(values):
p=np.pad(values,1,mode='edge'); out=np.zeros_like(values)
for y in range(3):
for x in range(3):
out += p[y:y+a.shape[0],x:x+a.shape[1]]
return out
xx,yy,xy=window_sum(gx*gx),window_sum(gy*gy),window_sum(gx*gy)
matrices=np.empty((*a.shape,2,2))
matrices[:,:,0,0]=xx;matrices[:,:,1,1]=yy
matrices[:,:,0,1]=xy;matrices[:,:,1,0]=xy
response=xx*yy-xy*xy-k*(xx+yy)**2
return response,matrices
if __name__=='__main__':
flat=np.ones((5,5)); edge=np.zeros((5,5));edge[:,2:]=1
corner=np.zeros((5,5));corner[2:,2:]=1
for label,patch in [('flat',flat),('edge',edge),('corner',corner)]:
response,m=harris(patch)
print(label, 'R:',round(float(response[2,2]),4),'eigenvalues:',np.linalg.eigvalsh(m[2,2]).round(4).tolist())
flat R: 0.0 eigenvalues: [0.0, 0.0]
edge R: -0.09 eigenvalues: [0.0, 1.5]
corner R: 0.7775 eigenvalues: [0.75, 1.25]
The values refer to array location [2,2]. The edge’s gradient vectors all point horizontally, producing only one informative direction. The quadrant supplies both horizontal and vertical gradients, so its information matrix has full rank.
For a fixed three-by-three window, this response computation takes O(HW) time and storage. A general K-by-K literal window sum would cost O(HWK²); separable or summed-area methods can change that cost. The returned matrices allow the explanation to be tested rather than hidden behind a single response number.
The checks verify the exact matrices above, compare determinant/trace responses with eigenvalue calculations on random patches, and test quarter-turn rotation, additive intensity shifts and threefold intensity gain. A gain of three should multiply R by 81. Invalid dimensions and k values are rejected.
Where the method breaks
This implementation stops at a response map. It does not perform nonmaximum suppression, select a target number of corners, refine subpixel coordinates or estimate a characteristic scale. A large edge response in magnitude is not a high-quality corner: its sign matters, and strength and conditioning both matter for tracking.
The continuous matrix construction supports rotation reasoning, but a sampled image also has interpolation and boundary effects. The tests establish quarter-turn behavior on this square grid, not exact invariance under every arbitrary rotation. Likewise, a fixed-size window is not scale invariant. Noise, blur and a repeated checkerboard can produce unstable or ambiguous correspondences even when R is large.
Canny’s output can be useful for tracing contours, while corner responses help select local tracking points. Neither directly establishes that two points in different images correspond. Descriptors and geometric verification address that additional problem.
Exercises with answers
1. Compute R for eigenvalues (2,2) at k=0.04.
Answer. det=4 and trace=4, so R=4−0.04×16=3.36.
2. Why can a straight edge fail to determine motion along itself?
Answer. Its gradients have no component along the edge. Displacement in that direction barely changes the patch, leaving one small eigenvalue.
3. Replace the nine-pixel sum by a mean. How does R change?
Answer. M is divided by nine. Both determinant and squared trace are divided by 81, so R is divided by 81; the old threshold is no longer equivalent.
4. Does large positive R guarantee a unique match in another image?
Answer. No. Repeated corners can have similar local structure. Matching needs a descriptor and consistency checks, not strength alone.
Sources and next steps
Harris and Stephens provide the local-change and corner-response construction; Canny provides a separate edge-detection formulation. We read bounded method passages rather than claiming to reproduce either complete detector. A Combined Corner and Edge Detector A Computational Approach to Edge Detection
Review eigenvalues and image filtering as needed. Optical flow reuses the same gradient information matrix, while SIFT adds scale and orientation handling around local descriptors.
Make a prediction, then check
If intensity is multiplied by 3, how does Harris R scale?
Learning objectives
- Derive the structure tensor from patch displacement error.
- Interpret eigenvalues, response sign and intensity scaling.
Prerequisites & connections
Explore related knowledge →References
- A Combined Corner and Edge Detector
Chris Harris; Mike Stephens · 1988 - A Computational Approach to Edge Detection
John Canny · 1986
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: bounded primary-source passages, explicit camera, filter, descriptor and local-motion models, executed programs, independent mathematical references, input boundaries and bilingual alignment. Not independent human or second-agent review; no full-system research reproduction claimed.
- Single-agent authored technical review; runnable example, exact or literal reference checks, explicit assumptions and matching bilingual equations/exercises. Automated execution and rendering results recorded separately.
- 5 tests: exact flat/edge/quadrant matrices and eigenvalues, determinant/trace versus eigenvalue response, quarter rotation and gain/offset, invalid settings. Corrected wording to threefold intensity gain. Original figure visually inspected; no full detector claimed.
- Single AI author compared all six sections, formulas, examples, source scopes and four exercise/answer pairs across both languages.35 tests across six chapters passed before freezing; no independent human review claimed.
- Complete bilingual prose and corresponding exercises promoted with formal status and SHA binding. Algorithm tests read formal MDX; historical essays claim no executable program or computational tests.
- Original figure generator stored at scripts/figures/vision-patches.py; SHA256 26347fcc03372d43e2ce611b261592d45117b1c74a4918785b82aaadf7086789. Runtime dependency binding covers the SVG. The existing validator only accepts src/ and public/examples/ dependencies, so the generator is recorded here rather than expanding that contract.
- After mobile visual inspection, enlarged A/B/C and response labels in the original SVG for readability at a350-pixel article width. Data and responses unchanged; regenerated and rebound final SVG and generator hashes.
Source locations checked:
- A Combined Corner and Edge Detector · Local-window/eigenvalue response passages, physical pages3–5; page4 R definition.
- A Computational Approach to Edge Detection · Abstract criteria and bounded nonmaximum/hysteresis passages; not full optimal-filter proof.
Related topics