Algorithmintro
Moravec corner detector
Also called Moravec interest operator.
Score each pixel by the smallest sum of squared differences between its window and the window shifted by one pixel in four directions, and keep the local maxima.
- Solves
- Corner detection
- Time
- O(W H r^2) worst · average · best
- Space
- Θ(W H) extra
- Where
- H = the image height in pixels; W = the image width in pixels; r = the radius of the window in pixels
- Model
- Word RAM
- Properties
- deterministicexactheuristicnot rotation invariant responsenot scale invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hans Moravec, 1980
The Moravec corner detector, also called the Moravec interest operator, is the first widely used method for corner detection. For each pixel it compares a small window with the same window moved by one pixel in four directions, horizontal, vertical and the two diagonals. It sums the squared differences for each direction and takes the smallest of the four sums as the score, so a pixel scores high only when the image changes in every one of the four directions. It keeps the pixels whose score is a local maximum above a threshold. The cost is for a image and a window of radius . The Harris corner detector replaces the four discrete shifts by a quadratic form in the gradients, and the Shi-Tomasi detector by the smaller eigenvalue of that form; both are fixes of the faults of this operator that are shown below.
In plain words
Put a small square window on the image and move it one pixel to the right. Add up how much each pixel under the window changed, squared. Do the same for a move down and for the two diagonal moves. On a flat area none of the four moves changes anything. On a straight edge the move along the edge changes nothing, so the smallest of the four totals is zero. Only on a corner or on a spot does every move change the window. So the score of a pixel is the smallest of its four totals. A pixel is a corner if its score is above a threshold and no pixel near it has a higher score. The method is simple and uses only integer additions and products.
The problem
The input is a gray digital image with columns and rows of integer values. A pixel has integer coordinates : is the column and goes right, is the row and goes down, and the origin is the top left pixel. The window has radius , so it holds pixels. For a shift the change of the window at is
The response is the minimum over four shifts,
This page uses no border rule: is defined only where each read is inside the image, that is for and . The output is the set of defined pixels with that are not smaller than at any defined pixel within a Chebyshev distance . As for every corner detector, "corner" here means the points that this response selects; the problem page explains why there is no single correct answer.
Moravec's thesis states the operator as the sum of squares of the differences of adjacent pixels in each of four directions over the window. The shift form above, which Harris and Stephens use when they analyze the operator, counts the same kind of pairs; the two forms differ only in which pairs at the border of the window they include. Some texts use all eight unit shifts. The opposite shift adds nothing new in the limit of a large window, since : it is the same sum, taken at the neighbouring pixel.
The algorithm
MORAVEC(I, r, τ, m) ▷ I is W × H with integer values, τ ≥ 0, m ≥ 1- 1
S ← {(1, 0), (0, 1), (1, 1), (1, -1)} - 2
for each pixel (u, v) with r + 1 ≤ u ≤ W - r - 2 and r + 1 ≤ v ≤ H - r - 2 do - 3
C(u, v) ← min over (a, b) ∈ S of E_ab(u, v) - 4
corners ← ∅ - 5
for each pixel (u, v) where C is defined and C(u, v) > τ do - 6
if C(u, v) ≥ C(u', v') for each defined (u', v') with |u' - u| ≤ m and |v' - v| ≤ m then - 7
add (u, v) to corners - 8
return corners
Line L1 fixes the four directions: right, down, and the two diagonals. Lines L2 and L3 compute the response at every pixel where the shifted window stays inside the image. Each is a sum of squared integer differences. Lines L4 to L7 keep the pixels above the threshold that are local maxima of . The test at line L6 is not strict, so two equal neighbours are both kept. Moravec spaced his windows half a window apart and kept a window when its score was the largest of the 25 windows that overlap or touch it; this page uses every pixel and the neighbourhood of radius , which is the usual dense form.
Example
Take the image with everywhere except a block of s at and . The block has one corner, at , and two edges, along the row and the column . With , is defined for . The four sums at some pixels are:
| pixel | kind | |||||
|---|---|---|---|---|---|---|
| corner | 162 | 162 | 405 | 243 | 162 | |
| next to the corner | 81 | 81 | 243 | 81 | 81 | |
| on the top edge | 0 | 243 | 243 | 243 | 0 | |
| on the left edge | 243 | 0 | 243 | 324 | 0 |
At the window covers , and four of its pixels are . The shift changes the two pixels and from to , so . At the shift along the edge, , changes nothing, so . The full table of for is except for and . With and the detector returns one corner, .
Now take a image with where and elsewhere. This is a straight edge with a slope of , at about , which is not one of the four directions. At the sums are , , and , so . Every pixel of the defined area that touches the edge has , and with and the detector returns 17 "corners", all on the edge. A vertical edge or an edge at gives everywhere, because one of the four shifts runs along it.
Correctness
The detector computes exactly the response it defines. Lines L2 and L3 visit each pixel of the defined area once and set to the minimum of the four sums. Lines L5 to L7 add a pixel exactly when it passes the threshold and the neighbourhood test, and no line removes a pixel. So the output is the set described in The problem. The full proof is in proofs/correctness.md. It also proves the facts that justify the response:
- when the window lies in a region where is constant along one of the four directions. So a straight edge along a direction of gives no response.
- On a window where is constant, all four sums are .
- An offset gives the same , and a gain gives ; with the output does not change.
Whether a returned pixel is a corner for a human is not a theorem. The slanted edge above shows that the operator reports edges at angles between the four directions.
Proof: Correctness of the Moravec corner detectorfull
We prove that MORAVEC returns exactly the set defined in The problem, and we prove the three facts about the response that the page states.
Setting. is a image with integer values, , and . Let be the set of pixels with and . The target output is
Lemma 1 (the reads are in the image). For , and , both and are pixels of .
Proof. Each of and is in . So and . The same bounds hold for , and the same argument with holds for the row.
Lemma 2 (the table ). After lines L1 to L3, is defined exactly on , and for each it holds .
Proof. Line L2 visits each pixel of once and no other pixel. By Lemma 1, each sum reads only pixels of , so it is a well defined integer. Line L3 stores the minimum of the four sums for the set of line L1, and no later line writes to .
Theorem (output). MORAVEC returns .
Proof. By Lemma 2, line L5 visits exactly the pixels with , each once. For such a pixel, line L6 tests for each defined in the square of radius . The pixel passes this test trivially, so the test is true exactly when the second condition in the definition of holds. Line L7 adds the pixel exactly when the test is true. Lines L4 to L7 only add to the set, so after the loop the set holds each pixel of and no other pixel, and line L8 returns it.
Proposition 1 (an edge along a direction of ). Let and . If for each pixel of the window at , then . In particular, a window that lies in a region where is constant gives .
Proof. Each term of is , so . Each is a sum of squares and so is at least . The minimum of four numbers that are at least , one of which is , is . If is constant on the window and its shifted copies, the hypothesis holds for each shift.
Proposition 2 (offset and gain). For an integer and an integer , let be the response of . Then for each . If and , MORAVEC returns the same set for as for .
Proof. Each difference becomes , so each squared difference, each sum and so the minimum is multiplied by . Multiplying by keeps every inequality and keeps , and the set depends only on , and . So by the Theorem the two outputs are the same set.
Proposition 3 (the opposite shift). For a shift and a pixel such that both sides read only pixels of , .
Proof. Write for the set of offsets with . Then . Put . The term for is , which is the term for of . Summing over gives the claim.
So the minimum over the eight unit shifts at is the minimum of the four sums at and of the four sums at the neighbours, which is the statement on the page about the eight-shift variant.
Complexity
The model is the word RAM. Let the pixels be integers of bits. Each squared difference has at most bits, and a sum of of them has at most bits, so it fits in one word for 8-bit images and any window that fits in the image.
- Lines L2 and L3 compute 4 sums of terms at each of at most pixels: time.
- Lines L5 to L7 compare each pixel with at most neighbours: time, which is for a fixed .
- The table takes extra space.
The total is for a fixed , in every case. For each shift, the squared differences form one image, and a box sum over it can use an integral image. Then each costs per pixel and the whole response costs for any .
Properties
- Not isotropic. The response looks only in four directions. An edge at an angle between them gets a positive score, as the example shows. This is the first fault that Harris and Stephens list.
- Noisy. The square window weighs all pixels the same, so a pixel that enters or leaves the window changes the score by a jump. Harris and Stephens use a Gaussian window instead.
- Edges and noise. The minimum of four sums is large on any pixel where all four shifts change the window, which also happens on noisy edges and on single noisy pixels.
- Gain and offset. does not change under an offset and is multiplied by under a gain . A fixed threshold therefore depends on the contrast.
- Not scale invariant. The window and the shift are one pixel in size, so a blurred corner or a corner seen from far away gives a different response.
- Exact integer arithmetic. No division and no square root is needed.
Variants and improvements
- Harris and Stephens. Expand to first order in the shift. Then with the structure tensor , and every direction is covered at once. This is the Harris corner detector.
- Smallest eigenvalue. Take the smallest value of the quadratic form over unit shifts, which is the smaller eigenvalue of . This is the Shi-Tomasi detector.
- Eight shifts. Take the minimum over the eight unit shifts. By the identity in The problem, this adds the four sums of the neighbours , so the response is a little smoother but has the same faults.
- Sparse windows. Moravec computed the operator on windows spaced half a window apart, on an image reduced in size, to save time on the computers of his day.
- Segment tests. The FAST detector compares the pixels on a circle with the center and needs no sums of squares.
When to use it
Use it to teach corner detection, or when only integer additions are available and the edges of interest are horizontal, vertical or diagonal. For any other use, the Harris or Shi-Tomasi detector gives a better response at a similar cost, and FAST is faster on 8-bit images.
Pitfalls
- Reads outside the image. Line L3 reads up to pixels away from . A loop over , as for a window without a shift, reads outside the image. Use the bounds of line L2, or a border rule.
- Strict maxima on plateaus. A test in place of at line L6 drops both pixels of two equal neighbours. On the corner example both forms return , but on symmetric shapes the strict test can return nothing.
- Threshold zero on slanted edges. With every pixel on an edge between the four directions passes, as in the example. Choose above the response of the edges you expect, or use a detector with an isotropic response.
- Overflow. In 16-bit arithmetic, a window of 8-bit differences can reach , which does not fit. Use 32-bit or 64-bit sums.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moravec-corner-detector/. The authors are listed in prov/S56VW3.jsonl.
"""Moravec corner detector (interest operator) with exact integer arithmetic.
An image is a list of H rows of W integers; pixel (u, v) is img[v][u], with
u the column (to the right) and v the row (down). The window has radius r,
so it holds (2 r + 1)^2 pixels. For a shift (a, b) the change of the window
at (u, v) is
E_ab(u, v) = sum over |i| <= r, |j| <= r of
(I(u + i + a, v + j + b) - I(u + i, v + j))^2,
and the response is C(u, v) = min of E_ab over the four shifts
(1, 0), (0, 1), (1, 1) and (1, -1). C is defined only where every read is
inside the image: r + 1 <= u <= W - r - 2 and r + 1 <= v <= H - r - 2.
A corner is a defined pixel with C > tau that is not smaller than C at any
defined pixel of its (2 m + 1) x (2 m + 1) neighbourhood.
Cost: O(W H r^2) time and O(W H) extra space on a word RAM.
"""
from typing import Dict, List, Sequence, Tuple
Image = Sequence[Sequence[int]]
SHIFTS: Tuple[Tuple[int, int], ...] = ((1, 0), (0, 1), (1, 1), (1, -1))
def shift_change(img: Image, u: int, v: int, a: int, b: int, r: int) -> int:
"""Return E_ab(u, v), the sum of squared differences for the shift (a, b)."""
total = 0
for j in range(-r, r + 1):
row = img[v + j]
row_s = img[v + j + b]
for i in range(-r, r + 1):
d = row_s[u + i + a] - row[u + i]
total += d * d
return total
def moravec_response(img: Image, r: int = 1) -> Dict[Tuple[int, int], int]:
"""Return C as a dict from (u, v) to the response, for the defined pixels only."""
h, w = len(img), len(img[0])
resp: Dict[Tuple[int, int], int] = {}
for v in range(r + 1, h - r - 1): # @line L2
for u in range(r + 1, w - r - 1):
resp[(u, v)] = min(shift_change(img, u, v, a, b, r) for a, b in SHIFTS) # @line L1 @line L3
return resp
def moravec_corners(img: Image, r: int = 1, tau: int = 0, m: int = 1) -> List[Tuple[int, int]]:
"""Return the corners (u, v), sorted by v then u.
Precondition: img is a non-empty rectangular list of integer rows,
r >= 0, m >= 1 and tau >= 0.
"""
resp = moravec_response(img, r)
corners: List[Tuple[int, int]] = [] # @line L4
for (u, v), c in sorted(resp.items(), key=lambda kv: (kv[0][1], kv[0][0])):
if c <= tau: # @line L5
continue
ok = True
for dv in range(-m, m + 1): # @line L6
for du in range(-m, m + 1):
other = resp.get((u + du, v + dv))
if (du or dv) and other is not None and other > c:
ok = False
if ok:
corners.append((u, v)) # @line L7
return corners # @line L8
test_moravec_corner_detector.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moravec-corner-detector/. The authors are listed in prov/S56VW3.jsonl.
import random
from moravec_corner_detector import SHIFTS, moravec_corners, moravec_response, shift_change
def oracle_corners(img, r, tau, m):
"""Brute force: build the four shifted windows as lists and compare them."""
h, w = len(img), len(img[0])
defined = {}
for v in range(h):
for u in range(w):
if not (r + 1 <= u <= w - r - 2 and r + 1 <= v <= h - r - 2):
continue
best = None
for a, b in [(1, 0), (0, 1), (1, 1), (1, -1)]:
win = [img[v + j][u + i] for j in range(-r, r + 1) for i in range(-r, r + 1)]
moved = [img[v + j + b][u + i + a] for j in range(-r, r + 1) for i in range(-r, r + 1)]
e = sum((x - y) ** 2 for x, y in zip(win, moved))
best = e if best is None else min(best, e)
defined[(u, v)] = best
out = []
for (u, v), c in defined.items():
if c > tau and all(
defined.get((u + du, v + dv), -1) <= c
for du in range(-m, m + 1)
for dv in range(-m, m + 1)
):
out.append((u, v))
return sorted(out, key=lambda p: (p[1], p[0]))
def corner_image():
return [[9 if (u >= 4 and v >= 4) else 0 for u in range(8)] for v in range(8)]
def test_worked_example_corner():
img = corner_image()
resp = moravec_response(img, 1)
assert [shift_change(img, 4, 4, a, b, 1) for a, b in SHIFTS] == [162, 162, 405, 243]
assert resp[(4, 4)] == 162
assert resp[(3, 3)] == 81 and resp[(4, 3)] == 81 and resp[(3, 4)] == 81
assert resp[(5, 4)] == 0 and resp[(4, 5)] == 0 and resp[(2, 2)] == 0
assert moravec_corners(img, 1, 0, 1) == [(4, 4)]
def test_slanted_edge_gives_false_corners():
img = [[9 if 2 * v >= u + 3 else 0 for u in range(10)] for v in range(10)]
resp = moravec_response(img, 1)
assert [shift_change(img, 5, 4, a, b, 1) for a, b in SHIFTS] == [81, 243, 162, 324]
corners = moravec_corners(img, 1, 0, 1)
assert len(corners) == 17
assert all(resp[p] == 81 for p in corners)
def test_straight_edges_give_zero():
vert = [[5 if u >= 4 else 0 for u in range(9)] for v in range(9)]
diag = [[5 if u + v >= 8 else 0 for u in range(9)] for v in range(9)]
for img in (vert, diag):
assert all(c == 0 for c in moravec_response(img, 1).values())
assert moravec_corners(img, 1, 0, 1) == []
def test_flat_and_tiny_images():
assert moravec_corners([[7] * 6 for _ in range(6)], 1, 0, 1) == []
assert moravec_response([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1) == {}
assert moravec_corners([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 1, 0, 1) == []
def test_random_against_oracle():
rng = random.Random(1980)
for _ in range(600):
w, h = rng.randint(4, 8), rng.randint(4, 8)
img = [[rng.randint(0, 3) for _ in range(w)] for _ in range(h)]
r = rng.choice([0, 1])
m = rng.choice([1, 2])
tau = rng.choice([0, 2, 5])
assert moravec_corners(img, r, tau, m) == oracle_corners(img, r, tau, m)
def test_offset_and_gain():
rng = random.Random(7)
for _ in range(50):
img = [[rng.randint(0, 20) for _ in range(9)] for _ in range(9)]
base = moravec_response(img, 1)
shifted = moravec_response([[x + 100 for x in row] for row in img], 1)
scaled = moravec_response([[3 * x for x in row] for row in img], 1)
assert shifted == base
assert all(scaled[p] == 9 * base[p] for p in base)
assert moravec_corners([[3 * x for x in row] for row in img]) == moravec_corners(img)
def test_opposite_shift_identity():
# E for the shift -s at p equals E for the shift s at p - s.
rng = random.Random(11)
img = [[rng.randint(0, 50) for _ in range(10)] for _ in range(10)]
for v in range(3, 7):
for u in range(3, 7):
for a, b in SHIFTS:
assert shift_change(img, u, v, -a, -b, 1) == shift_change(img, u - a, v - b, a, b, 1)
History
Hans Moravec built the interest operator for the Stanford Cart, a small robot that found its way among obstacles by stereo vision. His 1980 Stanford thesis describes it in Chapter 5: the score of a window is the minimum of the four sums of squared differences of adjacent pixels, and a window is a feature when its score is the largest among the 25 windows that overlap or touch it. The cart then matched these features between stereo images with a correlator. In 1988 Chris Harris and Mike Stephens analyzed the operator, listed its three faults (the discrete set of shifts, the binary window and the use of the minimum), and fixed them with the gradient form that became the Harris detector.
References
- Hans P. Moravec, Obstacle avoidance and navigation in the real world by a seeing robot rover, PhD thesis, Stanford University, 1980 (also Stanford AIM-340 and CMU-RI-TR-80-03), Chapter 5, Interest Operator (four directions, the minimum of the four sums, the local maximum over the 25 windows that overlap or touch a window)
- Chris Harris and Mike Stephens, A combined corner and edge detector, Proceedings of the Alvey Vision Conference 1988, Manchester, the section Moravec revisited (the shifts (1,0), (1,1), (0,1), (-1,1) and the three faults of the operator)
- Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 7, Section 7.1.1, Feature detectors (the auto-correlation function of a patch)
- Tinne Tuytelaars and Krystian Mikolajczyk, Local invariant feature detectors, a survey, Foundations and Trends in Computer Graphics and Vision 3(3), 177-280, 2008, the part on corner detectors (the Harris detector and its origin in the Moravec operator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag S56VW3 Edit this page History Report an error Markdown