Algorithm Search⌘K

Algorithmcore

Shi-Tomasi corner detector

Also called good features to track, minimum eigenvalue corner detector.

Score each pixel by the smaller eigenvalue of its structure tensor and keep strong local maxima a minimum distance apart, the points a translation tracker follows well.

Time
O(W H r + K log K + K N) worst · averageO(W H r) best
Space
Θ(W H) extra
Where
H = the image height in pixels; K = the number of candidate pixels; N = the largest number of corners to return; W = the image width in pixels; r = the radius of the window
Properties
deterministicexactnot heuristicrotation invariant responsenot scale invariant
Origin
Jianbo Shi, Carlo Tomasi, 1994

The Shi-Tomasi corner detector, also called good features to track or the minimum eigenvalue corner detector, solves corner detection. It builds the same 2×22 \times 2 structure tensor MM as the Harris corner detector, but it scores each pixel by the smaller eigenvalue λmin⁡\lambda_{\min} of MM instead of by det⁡M−k(tr⁡M)2\det M - k (\operatorname{tr} M)^2. The smaller eigenvalue is the smallest change of the window over all unit shifts, so it is large exactly when the window changes in every direction. The Moravec detector took this minimum over four shifts only. The usual selection keeps the local maxima of λmin⁡\lambda_{\min} above a fraction of the largest value and accepts them, strongest first, when they are at least a given distance from the points already accepted. The cost is O(WHr)O(WHr) for the response plus a sort of the candidates. Shi and Tomasi chose this score in 1994 because it is the condition under which the Lucas-Kanade translation tracker can solve for the motion of the window.

In plain words

Look at the slopes of the brightness inside a small window around a pixel. Collect them in a small table that tells, for each direction, how much the window changes when it moves in that direction. On a flat area it changes in no direction. On an edge it changes across the edge but not along it. On a corner it changes in every direction. The Shi-Tomasi score is the change in the weakest direction. It is near zero on flat areas and on edges, and large only on corners and spots. To pick the final points, keep the pixels that score higher than their neighbours and higher than a fraction of the best score. Then take them from the strongest down, and skip any point that is too close to a point you already took.

The problem

The input is a gray digital image II with WW columns and HH rows. A pixel has integer coordinates (u,v)(u, v): uu is the column and goes right, vv is the row and goes down. A read outside the image takes the nearest edge pixel (the clamp rule). The parameters are a quality fraction qq with 0≤q≤10 \le q \le 1, a minimum distance d≥0d \ge 0, a largest number of corners N≥1N \ge 1, and a window ww of radius rr.

With the gradients X=∂I/∂uX = \partial I / \partial u and Y=∂I/∂vY = \partial I / \partial v, the structure tensor at a pixel is

M=(ACCB),A=∑wX2,B=∑wY2,C=∑wXY,M = \begin{pmatrix} A & C \\ C & B \end{pmatrix}, \qquad A = \sum w X^2, \quad B = \sum w Y^2, \quad C = \sum w XY,

where each sum runs over the window. For a small shift s=(a,b)s = (a, b), the weighted sum of squared changes of the window is about sTMss^{\mathsf T} M s. MM is symmetric and positive semidefinite, so its eigenvalues are real and at least 00. The response is the smaller one,

λmin⁡=A+B2−(A−B2)2+C2=min⁡∥s∥=1sTMs.\lambda_{\min} = \frac{A + B}{2} - \sqrt{\Big(\frac{A - B}{2}\Big)^2 + C^2} = \min_{\|s\| = 1} s^{\mathsf T} M s .

The output is a list of pixels: the candidates are the pixels with λmin⁡>qλmax⁡∗\lambda_{\min} > q \lambda_{\max}^{\ast}, where λmax⁡∗\lambda_{\max}^{\ast} is the largest response in the image, that are not smaller than any of their eight neighbours inside the image. The output takes the candidates in order of decreasing response, ties in order of vv and then uu, and keeps a candidate when it is at least dd from every kept point and fewer than NN points are kept. This selection rule is not in the paper, which only sets a threshold on λmin⁡\lambda_{\min}, but it is the rule most libraries use, for example the OpenCV function goodFeaturesToTrack.

The algorithm

  1. SHI-TOMASI(I, q, d, N, w) ▷ I is W × H, w is a window of radius r
  2. 1X ← I(u + 1, v) - I(u - 1, v); Y ← I(u, v + 1) - I(u, v - 1) ▷ at each pixel, clamp border
  3. 2A ← w ∗ X²; B ← w ∗ Y²; C ← w ∗ X Y ▷ separable window, clamp border
  4. 3for each pixel: λ(u, v) ← (A + B)/2 - sqrt(((A - B)/2)² + C²)
  5. 4λmax ← the largest λ(u, v)
  6. 5P ← the pixels with λ > q λmax and λ ≥ λ at each of their 8 neighbours inside the image
  7. 6sort P by λ, largest first, ties by v and then u
  8. 7kept ← empty list
  9. 8for each p in P in order do
  10. 9if |kept| < N and ‖p - p'‖ ≥ d for each p' in kept then
  11. 10append p to kept
  12. 11return kept

Lines L1 and L2 are the first lines of the Harris detector: central differences, not divided by 2, and a window sum. This page uses the binomial weights (1,2,1)(1, 2, 1) in each direction for r=1r = 1, a small integer approximation of a Gaussian window. Line L3 is the closed form of the smaller eigenvalue of a symmetric 2×22 \times 2 matrix. Line L5 is a non-maximum suppression with a test that is not strict, so a flat top of equal values gives several candidates; line L9 then removes those that are too close. Lines L8 to L10 are a greedy pass: a point is never removed once it is kept.

For an integer image, AA, BB and CC are integers and 2λ=s−D2\lambda = s - \sqrt{D} with the integers s=A+Bs = A + B and D=(A−B)2+4C2D = (A - B)^2 + 4C^2. The implementation keeps the pair (s,D)(s, D) and compares two values p1−n1p_1 - \sqrt{n_1} and p2−n2p_2 - \sqrt{n_2} exactly, by isolating one root and squaring with attention to the signs. So the order, the ties and the test λ>qλmax⁡\lambda > q \lambda_{\max} for a rational qq do not depend on rounding. A floating point version is the same algorithm and gives the same output except on near ties.

Example

Take the 8×88 \times 8 image with 00 everywhere except a block of 99s at u≥4u \ge 4 and v≥4v \ge 4, with r=1r = 1. The table compares the Shi-Tomasi response with the Harris response R=AB−C2−k(A+B)2R = AB - C^2 - k(A + B)^2 for k=0.04k = 0.04:

pixel kind AA BB CC λmin⁡\lambda_{\min} Harris RR
(4,4)(4, 4) corner 729 729 324 405 341434.44
(3,4)(3, 4) beside the corner 729 243 162 193.95 113111.64
(3,3)(3, 3) outside the corner 243 243 81 162 43040.16
(6,4)(6, 4) on the top edge 0 972 0 0 -37791.36
(1,1)(1, 1) flat 0 0 0 0 0

At (4,4)(4, 4), A=BA = B, so λmin⁡=729−324=405\lambda_{\min} = 729 - 324 = 405. On the edge pixel the gradient is vertical only, so A=C=0A = C = 0 and the smaller eigenvalue is 00: the score does not separate an edge from a flat area, while the Harris score is negative on the edge. The response is 00 everywhere except at the nine pixels with 3≤u,v≤53 \le u, v \le 5, and the only local maximum is (4,4)(4, 4). With q=1/100q = 1/100 the output is [(4,4)][(4, 4)].

For the selection, take a 12×1212 \times 12 image with a square of 99s at 3≤u,v≤83 \le u, v \le 8. Its four corners (3,3)(3, 3), (8,3)(8, 3), (3,8)(3, 8) and (8,8)(8, 8) all have λmin⁡=405\lambda_{\min} = 405, so the tie rule orders them by vv and then uu. With d=3d = 3 all four are kept. With d=3d = 3 and N=2N = 2 the output is [(3,3),(8,3)][(3, 3), (8, 3)]. With d=6d = 6 the output is [(3,3),(8,8)][(3, 3), (8, 8)]: the points (8,3)(8, 3) and (3,8)(3, 8) are 55 from (3,3)(3, 3), and (8,8)(8, 8) is 52≈7.075\sqrt{2} \approx 7.07 from it. With q=1q = 1 the output is empty, because no pixel is strictly larger than the largest value.

Correctness

Two facts make the score right. First, for a symmetric MM the minimum of sTMss^{\mathsf T} M s over unit vectors ss is the smaller eigenvalue, which is the formula of line L3. So λmin⁡\lambda_{\min} is the smallest change of the window, to first order, over all directions of motion, and it is large only when every direction changes the window. Second, the Lucas-Kanade tracker finds the shift ss of a window by solving Ms=eM s = e. Shi and Tomasi point out that this system is well conditioned and above the image noise when both eigenvalues are large, and since λmax⁡≥λmin⁡\lambda_{\max} \ge \lambda_{\min} it is enough to ask that λmin⁡\lambda_{\min} is large.

The algorithm returns exactly the list defined in The problem: lines L4 and L5 build the candidate set, line L6 fixes the order, and the greedy loop keeps a candidate exactly when it passes the distance and count tests at its turn. The proof of both parts, and of the exact comparison of the implementation, is in proofs/correctness.md.

Proof: Correctness of the Shi-Tomasi corner detectorfull

We prove three things: line L3 computes the smaller eigenvalue of MM, which is the smallest value of the quadratic form over unit vectors; the algorithm returns the list defined in The problem; and the exact comparison of the implementation gives the sign of (p1−n1)−(p2−n2)(p_1 - \sqrt{n_1}) - (p_2 - \sqrt{n_2}).

Lemma 1 (the smaller eigenvalue). Let M=(ACCB)M = \begin{pmatrix} A & C \\ C & B \end{pmatrix} be real and symmetric, and let λ=A+B2−(A−B2)2+C2\lambda = \frac{A + B}{2} - \sqrt{(\frac{A - B}{2})^2 + C^2}. Then λ\lambda is the smaller eigenvalue of MM and λ=min⁡∥s∥=1sTMs\lambda = \min_{\|s\| = 1} s^{\mathsf T} M s. If MM is a sum of matrices wggTw g g^{\mathsf T} with w≥0w \ge 0, then λ≥0\lambda \ge 0.

Proof. The characteristic polynomial is μ2−(A+B)μ+(AB−C2)\mu^2 - (A + B)\mu + (AB - C^2). Its discriminant is (A+B)2−4(AB−C2)=(A−B)2+4C2≥0(A + B)^2 - 4(AB - C^2) = (A - B)^2 + 4C^2 \ge 0, so both roots are real, and they are A+B2±(A−B2)2+C2\frac{A + B}{2} \pm \sqrt{(\frac{A - B}{2})^2 + C^2}. The root with the minus sign is the smaller one, λ\lambda. Since MM is symmetric, it has an orthonormal basis of eigenvectors e1,e2e_1, e_2 with eigenvalues λ≤λ′\lambda \le \lambda'. A unit vector is s=αe1+βe2s = \alpha e_1 + \beta e_2 with α2+β2=1\alpha^2 + \beta^2 = 1, and sTMs=α2λ+β2λ′≥λs^{\mathsf T} M s = \alpha^2 \lambda + \beta^2 \lambda' \ge \lambda, with equality at s=e1s = e_1. For the last claim, sT(wggT)s=w(g⋅s)2≥0s^{\mathsf T} (w g g^{\mathsf T}) s = w (g \cdot s)^2 \ge 0 for each term, so the minimum is at least 00. □\square

In the algorithm, M=∑w (X,Y)T(X,Y)M = \sum w \, (X, Y)^{\mathsf T} (X, Y) with binomial weights w>0w > 0, so the response of line L3 is the smaller eigenvalue of MM and is at least 00.

Lemma 2 (the candidates). After line L6, PP holds exactly the pixels pp with λ(p)>qλmax⁡\lambda(p) > q \lambda_{\max} and λ(p)≥λ(p′)\lambda(p) \ge \lambda(p') for each of the eight neighbours p′p' of pp inside the image, in order of decreasing λ\lambda, ties in order of vv and then uu.

Proof. Line L4 sets λmax⁡\lambda_{\max} to the largest response. Line L5 applies the two tests of the definition to each pixel, and line L6 sorts by the stated key. Since the key is a total order on the pixels (two pixels with equal response differ in (v,u)(v, u)), the order is unique. □\square

Theorem (output). SHI-TOMASI returns the list of The problem: the candidates in the order of Lemma 2, where a candidate is kept exactly when, at its turn, fewer than NN points are kept and it is at least dd from each kept point.

Proof. We prove by induction on ii that after the ii-th pass of line L8, kept is the list defined for the first ii candidates. For i=0i = 0 both are empty (line L7). At pass i+1i + 1, line L9 tests the two conditions of the definition against the current kept list, which by the hypothesis is the defined list for the first ii candidates, and line L10 appends the candidate exactly when both hold. No line removes a point or changes the order. After the last candidate, line L11 returns the defined list. □\square

Lemma 3 (exact comparison). For integers aa, bb and n≥0n \ge 0, the function sign(a+bn)\mathrm{sign}(a + b\sqrt{n}) of the implementation is correct: if bn=0b\sqrt{n} = 0 the sign is the sign of aa; if a=0a = 0 or aa and bb have the same sign, the sign is the sign of bb; otherwise the sign is the sign of aa when a2>b2na^2 > b^2 n, the opposite sign when a2<b2na^2 < b^2 n, and 00 when they are equal.

Proof. The first two cases are clear, since a sum of two numbers of the same sign, or of a number and zero, has that sign. In the last case aa and bnb\sqrt{n} are nonzero with opposite signs, so the sum has the sign of the term of larger absolute value, and ∣a∣>∣bn∣|a| > |b\sqrt{n}| exactly when a2>b2na^2 > b^2 n. Equal absolute values give 00. □\square

Lemma 4. For integers p1p_1, p2p_2 and n1,n2≥0n_1, n_2 \ge 0, the function compare_roots returns the sign of (p1−n1)−(p2−n2)(p_1 - \sqrt{n_1}) - (p_2 - \sqrt{n_2}).

Proof. Put e=p1−p2e = p_1 - p_2 and x=e+n2x = e + \sqrt{n_2}. The difference is x−n1x - \sqrt{n_1}. If x<0x < 0, which Lemma 3 decides as the sign of e+1⋅n2e + 1 \cdot \sqrt{n_2}, then x−n1<0x - \sqrt{n_1} < 0 since n1≥0\sqrt{n_1} \ge 0, and the function returns −1-1. Otherwise x≥0x \ge 0 and n1≥0\sqrt{n_1} \ge 0, and the map t↦t2t \mapsto t^2 is strictly increasing on [0,∞)[0, \infty), so x−n1x - \sqrt{n_1} has the sign of x2−n1=(e2+n2−n1)+2en2x^2 - n_1 = (e^2 + n_2 - n_1) + 2e\sqrt{n_2}, which Lemma 3 decides. □\square

The implementation stores 2λ=s−D2\lambda = s - \sqrt{D} with s=A+Bs = A + B and D=(A−B)2+4C2D = (A - B)^2 + 4C^2, which is twice the formula of Lemma 1. For q=qa/qbq = q_a / q_b with qa≥0q_a \ge 0 and qb>0q_b > 0, the test λ>qλmax⁡\lambda > q \lambda_{\max} is equivalent, after multiplication by 2qb>02 q_b > 0, to qbs−qb2D>qas∗−qa2D∗q_b s - \sqrt{q_b^2 D} > q_a s^{\ast} - \sqrt{q_a^2 D^{\ast}}, where (s∗,D∗)(s^{\ast}, D^{\ast}) is the pair of λmax⁡\lambda_{\max}; this is one call of compare_roots. Every comparison of responses in lines L4 to L6 is one call of compare_roots on the pairs, so by Lemma 4 each is exact. With Lemma 2 and the Theorem, the implementation returns the defined list. ■\blacksquare

Complexity

The model is the real RAM with a square root. Let KK be the number of candidates of line L5.

  • Lines L1 to L3 cost O(WHr)O(WHr) with a separable window, as for the Harris detector.
  • Lines L4 and L5 cost O(WH)O(WH).
  • Line L6 costs O(Klog⁡K)O(K \log K).
  • Each candidate at line L9 is compared with at most NN kept points, so lines L8 to L10 cost O(KN)O(KN). A grid of cells of side dd makes each test O(1)O(1) on average, since only nearby cells can hold a point closer than dd.
  • The tables take Θ(WH)\Theta(WH) extra space.

The total is O(WHr+Klog⁡K+KN)O(WHr + K \log K + KN), and O(WHr)O(WHr) when there are few candidates. The exact comparison of the implementation squares integers of at most twice the size of DD, so it costs O(1)O(1) word operations for 8-bit images and small windows.

Properties

  • Isotropic response. λmin⁡\lambda_{\min} is an eigenvalue, so a rotation of the gradients does not change it. On the pixel grid this holds exactly for rotations by 90°90° and approximately for other angles.
  • Zero on edges. On an ideal straight edge, MM has rank one and λmin⁡=0\lambda_{\min} = 0. Unlike the Harris response, the score does not go negative on edges, so a pixel on an edge and a flat pixel score the same.
  • Contrast. An offset does not change MM. A gain gg multiplies MM and so λmin⁡\lambda_{\min} by g2g^2. The relative threshold qλmax⁡q \lambda_{\max} and the order are therefore unchanged by a gain, unlike a fixed threshold.
  • Not scale invariant. The window and the derivatives have one fixed size. The Harris-Laplace detector adds a scale search.
  • Spread of points. The minimum distance rule spreads the points over the image, which is what a tracker or a pose estimator needs.

Variants and improvements

  • Harris response. det⁡M−k(tr⁡M)2=λ1λ2−k(λ1+λ2)2\det M - k (\operatorname{tr} M)^2 = \lambda_1 \lambda_2 - k (\lambda_1 + \lambda_2)^2 avoids the square root and penalizes edges more. See the Harris corner detector.
  • Other combinations of the eigenvalues. The harmonic mean det⁡M/tr⁡M\det M / \operatorname{tr} M and the ratio λmin⁡/λmax⁡\lambda_{\min} / \lambda_{\max} are other common scores.
  • Feature monitoring. The 1994 paper also checks each tracked feature over time: it fits an affine model of the window between the first frame and the current one and drops the feature when the residual grows. This is part of the Kanade-Lucas-Tomasi tracker.
  • Scales. Run the detector on each level of a Gaussian pyramid for a tracker that works coarse to fine.
  • Speed. FAST finds candidates with a few comparisons per pixel; ORB then ranks them by the Harris score.

When to use it

Use it to choose the points for a translation tracker, as in the KLT tracker or in optical flow at sparse points, and whenever the points must be well spread over the image. It is a good default corner detector for frames of video at one scale. For matching between images with different scales or viewpoints, use a scale invariant detector such as the DoG detector or Harris-Laplace.

Pitfalls

  • Quality of 1. The test λ>qλmax⁡\lambda > q \lambda_{\max} is strict, so q=1q = 1 returns nothing. A value of about 0.010.01 to 0.10.1 is common.
  • Flat images. If the image is flat, λmax⁡=0\lambda_{\max} = 0 and nothing passes; a version that divides by λmax⁡\lambda_{\max} to get a relative score divides by zero.
  • Cancellation. For A≈BA \approx B and small CC, the subtraction in line L3 loses digits in floating point. The form λmin⁡=det⁡M/λmax⁡\lambda_{\min} = \det M / \lambda_{\max} with λmax⁡=(A+B)/2+⋯\lambda_{\max} = (A + B)/2 + \sqrt{\cdots} avoids it.
  • Greedy order matters. The distance rule depends on the order of the candidates. Two runs that break ties in different ways can return different points; fix the tie rule if results must repeat.
  • Edges near the border. The clamp rule gives a zero gradient across the image border, so a bright object that touches the border can give corners at the border.

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.

shi_tomasi_corner_detector.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shi-tomasi-corner-detector/. The authors are listed in prov/K93XA7.jsonl.

"""Shi-Tomasi corner detector (good features to track), with exact comparisons.

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). Reads outside the image
take the nearest edge pixel (clamp border rule).

X and Y are central differences, not divided by 2. The structure tensor
M = [[A, C], [C, B]] sums X^2, Y^2 and X Y with the binomial window of
radius r, (1, 2, 1) in each direction for r = 1. The response is the smaller
eigenvalue of M,

    lam = (A + B) / 2 - sqrt(((A - B) / 2)^2 + C^2).

For integer images A, B and C are integers, and 2 lam = s - sqrt(D) with
s = A + B and D = (A - B)^2 + 4 C^2. The code keeps the pair (s, D) and
compares such numbers exactly with integer arithmetic, so ties and the
threshold test do not depend on rounding.

Selection: keep the pixels with lam > q lam_max that are not smaller than
any of their 8 neighbours, sort them by lam in decreasing order (ties by v,
then u), and accept them greedily when they are at least d away from every
accepted point, up to n points.
"""

from fractions import Fraction
from functools import cmp_to_key
import math
from typing import List, Optional, Sequence, Tuple

Image = Sequence[Sequence[int]]


def binomial_row(radius: int) -> List[int]:
    """Row 2 radius of Pascal's triangle: (1, 2, 1) for radius 1."""
    row = [1]
    for _ in range(2 * radius):
        row = [a + b for a, b in zip([0] + row, row + [0])]
    return row


def _clamp(x: int, lo: int, hi: int) -> int:
    return lo if x < lo else hi if x > hi else x


def gradients(img: Image) -> Tuple[List[List[int]], List[List[int]]]:
    """Central differences X and Y with the clamp border rule."""
    h, w = len(img), len(img[0])
    gx = [[img[v][_clamp(u + 1, 0, w - 1)] - img[v][_clamp(u - 1, 0, w - 1)] for u in range(w)] for v in range(h)]
    gy = [[img[_clamp(v + 1, 0, h - 1)][u] - img[_clamp(v - 1, 0, h - 1)][u] for u in range(w)] for v in range(h)]
    return gx, gy


def _window_sum(field: List[List[int]], weights: List[int]) -> List[List[int]]:
    """Separable weighted sum with the clamp border rule: rows first, then columns."""
    h, w = len(field), len(field[0])
    r = len(weights) // 2
    tmp = [[sum(weights[i] * field[v][_clamp(u + i - r, 0, w - 1)] for i in range(len(weights)))
            for u in range(w)] for v in range(h)]
    return [[sum(weights[j] * tmp[_clamp(v + j - r, 0, h - 1)][u] for j in range(len(weights)))
             for u in range(w)] for v in range(h)]


def structure_tensor(img: Image, radius: int = 1):
    """Return the integer tables (A, B, C)."""
    gx, gy = gradients(img)  # @line L1
    wts = binomial_row(radius)
    xx = [[a * a for a in row] for row in gx]
    yy = [[b * b for b in row] for row in gy]
    xy = [[a * b for a, b in zip(ra, rb)] for ra, rb in zip(gx, gy)]
    return _window_sum(xx, wts), _window_sum(yy, wts), _window_sum(xy, wts)  # @line L2


def _sign_lin(a: int, b: int, n: int) -> int:
    """Sign of a + b sqrt(n) for integers a, b and n >= 0."""
    sa = (a > 0) - (a < 0)
    sb = ((b > 0) - (b < 0)) if n > 0 else 0
    if sb == 0:
        return sa
    if sa == 0 or sa == sb:
        return sb
    t = a * a - b * b * n
    return sa if t > 0 else (-sa if t < 0 else 0)


def compare_roots(p1: int, n1: int, p2: int, n2: int) -> int:
    """Sign of (p1 - sqrt(n1)) - (p2 - sqrt(n2)) for integers with n1, n2 >= 0."""
    e = p1 - p2
    # The sign of x - sqrt(n1) with x = e + sqrt(n2).
    if _sign_lin(e, 1, n2) < 0:
        return -1
    # x >= 0 and sqrt(n1) >= 0, so compare x^2 = e^2 + n2 + 2 e sqrt(n2) with n1.
    return _sign_lin(e * e + n2 - n1, 2 * e, n2)


def min_eigen_pairs(img: Image, radius: int = 1) -> List[List[Tuple[int, int]]]:
    """For each pixel the pair (s, D) with 2 lam = s - sqrt(D)."""
    a, b, c = structure_tensor(img, radius)
    h, w = len(img), len(img[0])
    out = []
    for v in range(h):
        row = []
        for u in range(w):
            aa, bb, cc = a[v][u], b[v][u], c[v][u]
            row.append((aa + bb, (aa - bb) ** 2 + 4 * cc * cc))  # @line L3
        out.append(row)
    return out


def pair_value(pair: Tuple[int, int]) -> float:
    """The eigenvalue lam of a pair (s, D), as a float, for display."""
    s, d = pair
    return (s - math.sqrt(d)) / 2


def shi_tomasi_response(img: Image, radius: int = 1) -> List[List[float]]:
    """The smaller eigenvalue of M at each pixel, as floats."""
    return [[pair_value(p) for p in row] for row in min_eigen_pairs(img, radius)]


def shi_tomasi_corners(img: Image, quality=Fraction(1, 100), min_distance: int = 0,
                       max_corners: Optional[int] = None, radius: int = 1) -> List[Tuple[int, int]]:
    """Return the selected corners (u, v), strongest first.

    Precondition: img is a non-empty rectangular list of integer rows,
    0 <= quality <= 1 (an int or a Fraction), min_distance >= 0 and
    max_corners is None (no limit) or at least 1.
    """
    q = Fraction(quality)
    qa, qb = q.numerator, q.denominator
    lam = min_eigen_pairs(img, radius)
    h, w = len(img), len(img[0])
    best = lam[0][0]
    for row in lam:  # @line L4
        for p in row:
            if compare_roots(p[0], p[1], best[0], best[1]) > 0:
                best = p
    cands = []
    for v in range(h):
        for u in range(w):
            s, d = lam[v][u]
            # lam > q lam_max, both sides multiplied by 2 qb.
            if compare_roots(qb * s, qb * qb * d, qa * best[0], qa * qa * best[1]) <= 0:  # @line L5
                continue
            ok = True
            for dv in (-1, 0, 1):
                for du in (-1, 0, 1):
                    uu, vv = u + du, v + dv
                    if (du or dv) and 0 <= uu < w and 0 <= vv < h:
                        o = lam[vv][uu]
                        if compare_roots(s, d, o[0], o[1]) < 0:
                            ok = False
            if ok:
                cands.append((u, v))

    def stronger_first(p, o):
        lp, lo = lam[p[1]][p[0]], lam[o[1]][o[0]]
        return compare_roots(lo[0], lo[1], lp[0], lp[1])

    # cands is in (v, u) order and the sort is stable, so ties stay in (v, u) order.
    cands.sort(key=cmp_to_key(stronger_first))  # @line L6
    kept: List[Tuple[int, int]] = []  # @line L7
    d2 = min_distance * min_distance
    for u, v in cands:  # @line L8
        if max_corners is not None and len(kept) >= max_corners:  # @line L9
            break
        if all((u - x) ** 2 + (v - y) ** 2 >= d2 for x, y in kept):
            kept.append((u, v))  # @line L10
    return kept  # @line L11
test_shi_tomasi_corner_detector.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shi-tomasi-corner-detector/. The authors are listed in prov/K93XA7.jsonl.

import math
import random
from decimal import Decimal, getcontext
from fractions import Fraction

from shi_tomasi_corner_detector import (
    compare_roots,
    shi_tomasi_corners,
    shi_tomasi_response,
    structure_tensor,
)

getcontext().prec = 60


def pix(img, u, v):
    h, w = len(img), len(img[0])
    return img[min(max(v, 0), h - 1)][min(max(u, 0), w - 1)]


def oracle_lambda(img):
    """Direct 2D window sums and the eigenvalue in 60-digit decimals."""
    h, w = len(img), len(img[0])
    gx = [[pix(img, u + 1, v) - pix(img, u - 1, v) for u in range(w)] for v in range(h)]
    gy = [[pix(img, u, v + 1) - pix(img, u, v - 1) for u in range(w)] for v in range(h)]
    wt = [1, 2, 1]
    lam = {}
    for v in range(h):
        for u in range(w):
            a = b = c = 0
            for j in range(-1, 2):
                for i in range(-1, 2):
                    x = pix(gx, u + i, v + j)
                    y = pix(gy, u + i, v + j)
                    k = wt[i + 1] * wt[j + 1]
                    a += k * x * x
                    b += k * y * y
                    c += k * x * y
            disc = Decimal((a - b) ** 2 + 4 * c * c).sqrt()
            lam[(u, v)] = (Decimal(a + b) - disc) / 2
    return lam


def oracle_corners(img, q, d, n):
    h, w = len(img), len(img[0])
    lam = oracle_lambda(img)
    top = max(lam.values())
    qd = Decimal(q.numerator) / Decimal(q.denominator)
    cands = []
    for (u, v), x in lam.items():
        if not x > qd * top:
            continue
        if all(lam[(u + du, v + dv)] <= x for du in (-1, 0, 1) for dv in (-1, 0, 1)
               if (u + du, v + dv) in lam):
            cands.append((-x, v, u))
    cands.sort()
    kept = []
    for _, v, u in cands:
        if n is not None and len(kept) == n:
            break
        if all(math.hypot(u - x, v - y) >= d for x, y in kept):
            kept.append((u, v))
    return kept


def square(n, lo, hi, val=9):
    return [[val if (lo <= u <= hi and lo <= v <= hi) else 0 for u in range(n)] for v in range(n)]


def test_worked_example_single_corner():
    img = [[9 if (u >= 4 and v >= 4) else 0 for u in range(8)] for v in range(8)]
    a, b, c = structure_tensor(img)
    assert (a[4][4], b[4][4], c[4][4]) == (729, 729, 324)
    lam = shi_tomasi_response(img)
    assert lam[4][4] == 405.0 and lam[3][3] == 162.0
    assert (a[4][6], b[4][6], c[4][6]) == (0, 972, 0) and lam[4][6] == 0.0
    assert shi_tomasi_corners(img) == [(4, 4)]


def test_worked_example_square_and_selection():
    img = square(12, 3, 8)
    assert shi_tomasi_corners(img) == [(3, 3), (8, 3), (3, 8), (8, 8)]
    assert shi_tomasi_corners(img, min_distance=3) == [(3, 3), (8, 3), (3, 8), (8, 8)]
    assert shi_tomasi_corners(img, min_distance=3, max_corners=2) == [(3, 3), (8, 3)]
    # (8, 3) and (3, 8) are 5 away from (3, 3); (8, 8) is 5 sqrt(2), about 7.07, away.
    assert shi_tomasi_corners(img, min_distance=6) == [(3, 3), (8, 8)]


def test_flat_image_and_quality_one():
    assert shi_tomasi_corners([[5] * 6 for _ in range(6)]) == []
    assert shi_tomasi_corners(square(12, 3, 8), quality=1) == []
    assert shi_tomasi_corners([[3]]) == []


def test_compare_roots_against_decimals():
    rng = random.Random(5)
    for _ in range(3000):
        p1, p2 = rng.randint(-30, 30), rng.randint(-30, 30)
        n1, n2 = rng.choice([rng.randint(0, 900), rng.randint(0, 30) ** 2]), rng.randint(0, 900)
        x = Decimal(p1) - Decimal(n1).sqrt()
        y = Decimal(p2) - Decimal(n2).sqrt()
        want = (x > y) - (x < y)
        assert compare_roots(p1, n1, p2, n2) == want
    assert compare_roots(5, 4, 4, 1) == 0 and compare_roots(3, 2, 3, 2) == 0


def test_eigenvalue_identities():
    rng = random.Random(17)
    for _ in range(40):
        img = [[rng.randint(0, 9) for _ in range(6)] for _ in range(6)]
        a, b, c = structure_tensor(img)
        lam = shi_tomasi_response(img)
        for v in range(6):
            for u in range(6):
                x, aa, bb, cc = lam[v][u], a[v][u], b[v][u], c[v][u]
                scale = 1 + (aa + bb) ** 2
                assert x >= -1e-9
                assert abs(x * (aa + bb - x) - (aa * bb - cc * cc)) <= 1e-9 * scale
                # Rayleigh: no unit direction gives a smaller quadratic form.
                for k in range(12):
                    t = math.pi * k / 12
                    e, f = math.cos(t), math.sin(t)
                    assert aa * e * e + 2 * cc * e * f + bb * f * f >= x - 1e-9 * scale


def test_random_against_oracle():
    rng = random.Random(1994)
    for _ in range(600):
        w, h = rng.randint(3, 7), rng.randint(3, 7)
        img = [[rng.randint(0, 3) for _ in range(w)] for _ in range(h)]
        q = rng.choice([Fraction(0), Fraction(1, 10), Fraction(1, 2), Fraction(9, 10)])
        d = rng.choice([0, 1, 2, 3])
        n = rng.choice([None, 1, 3])
        assert shi_tomasi_corners(img, q, d, n) == oracle_corners(img, q, d, n)


def test_rotation_by_90_degrees():
    rng = random.Random(23)
    for _ in range(30):
        img = [[rng.randint(0, 20) for _ in range(7)] for _ in range(5)]
        h, w = 5, 7
        rot = [[img[h - 1 - j][i] for j in range(h)] for i in range(w)]  # rot[i][j] = img[h-1-j][i]
        la, lb = shi_tomasi_response(img), shi_tomasi_response(rot)
        for v in range(h):
            for u in range(w):
                # img pixel (u, v) goes to rot pixel (h - 1 - v, u).
                assert abs(la[v][u] - lb[u][h - 1 - v]) < 1e-9


def test_offset_and_gain():
    rng = random.Random(29)
    for _ in range(30):
        img = [[rng.randint(0, 20) for _ in range(7)] for _ in range(7)]
        base = shi_tomasi_corners(img, Fraction(1, 5), 2)
        assert shi_tomasi_corners([[x + 50 for x in r] for r in img], Fraction(1, 5), 2) == base
        assert shi_tomasi_corners([[3 * x for x in r] for r in img], Fraction(1, 5), 2) == base

History

Jianbo Shi and Carlo Tomasi presented the criterion at CVPR in 1994 in the paper Good features to track. Earlier work selected points by interest operators such as Moravec's or by the Harris response, which were defined without reference to a tracker. Shi and Tomasi instead asked which windows the tracker can follow and derived the condition on the smaller eigenvalue of the gradient matrix. The criterion became part of the KLT tracker and is the default corner detector of many vision libraries.

References

  1. Jianbo Shi and Carlo Tomasi, Good features to track, IEEE Conference on Computer Vision and Pattern Recognition, 1994, pages 593-600, the section on feature selection (a window is accepted when the smaller eigenvalue of the 2 x 2 gradient matrix is above a threshold)
  2. Chris Harris and Mike Stephens, A combined corner and edge detector, Proceedings of the Alvey Vision Conference 1988, Manchester, the section Corner/edge response function (the matrix M and the response det M - k tr^2 M)
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 7, Section 7.1.1, Feature detectors (the smaller eigenvalue as a corner measure)
  4. 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

Where this leads

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example