AI Wiki中文/EN

SIFT features

SIFT 特征

Build a 128-entry gradient descriptor and separate what normalization can guarantee from what the full SIFT pipeline must do.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A question to test

You photograph a book cover from farther away and rotate the camera. Comparing the same sixteen-by-sixteen pixel square in both photographs will usually fail: that square no longer covers the same physical region or orientation. SIFT separates two jobs: establish a repeatable local coordinate frame, then describe the gradients inside it.

SIFT stands for Scale-Invariant Feature Transform. A keypoint includes a location, scale and orientation; its descriptor summarizes the surrounding image. The descriptor alone is not the whole method. In this chapter you will implement its histogram construction on an already canonical patch and see exactly which invariance claims that small program can support.

The model and its derivation

Lowe’s pipeline first searches for extrema in a difference-of-Gaussians scale space, refines their position and scale, rejects unstable candidates, assigns orientation and constructs a descriptor. The orientation stage can assign more than one orientation to a location. The OpenCV tutorial is a useful route through these stages; the author paper provides the method details. Distinctive Image Features from Scale-Invariant Keypoints — author version Introduction to SIFT — OpenCV 4.10.0

Gaussian smoothing at scale σ\sigma defines LL; subtracting nearby scales defines DD:

L(x,y,σ)=Gσ∗I(x,y),D(x,y,σ)=L(x,y,kσ)−L(x,y,σ),k>1.L(x,y,\sigma)=G_\sigma*I(x,y),\qquad D(x,y,\sigma)=L(x,y,k\sigma)-L(x,y,\sigma),\qquad k>1.

A candidate is compared spatially and across neighbouring scales. Merely computing a gradient histogram at a fixed pixel window does not perform that search. Similarly, orientation normalization requires a consistent rotation of both patch coordinates and gradient directions, not just renaming histogram bins.

Inside a canonical patch, estimate gradients and form magnitude and signed orientation:

m=Ix2+Iy2,θ=atan2⁡(Iy,Ix) mod 2π.m=\sqrt{I_x^2+I_y^2},\qquad \theta=\operatorname{atan2}(I_y,I_x)\bmod 2\pi.

The teaching descriptor uses four-by-four spatial cells and eight orientation bins, producing 128 entries. Each gradient contributes according to magnitude, a Gaussian spatial weight and interpolation weights. Interpolation in x, y and orientation distributes a contribution to at most eight neighbouring bins. This soft assignment avoids the discontinuity of sending an entire gradient to a new bin after a tiny shift. Spatial contributions outside the descriptor are discarded in our implementation; orientation wraps around.

Let h be the nonnegative concatenated histogram. The normalization used here is:

Nε(h)=h∥h∥22+ε2,d=Nε(min⁡(Nε(h),0.2)).N_\varepsilon(h)=\frac{h}{\sqrt{\lVert h\rVert_2^2+\varepsilon^2}},\qquad d=N_\varepsilon\bigl(\min(N_\varepsilon(h),0.2)\bigr).

The minimum is elementwise and ε=10−12\varepsilon=10^{-12} is our numerical convention. The second normalization means final entries can exceed 0.2. Clipping limits dominance before renormalization; it is not a final bound. Lowe describes this normalize–clip–normalize sequence. Distinctive Image Features from Scale-Invariant Keypoints — author version

Under an intensity change I′=aI+bI'=aI+b with a>0a>0, differences remove b and gradient magnitudes scale by a without changing orientation. Ignoring the tiny epsilon term, normalization removes that common factor. Clipping of sensor values, spatially varying lighting and a negative a break parts of this argument. With epsilon, invariance is approximate and can deteriorate for nearly zero gradients.

Run a small experiment

Input is an 18-by-18 finite grayscale patch whose central 16-by-16 region has already been resampled at the chosen scale and orientation. The one-pixel border supports centred derivatives. We use a Gaussian descriptor weight with sigma eight pixels. This program has no scale pyramid, keypoint detector, orientation estimator, resampling function or matcher. Run it with Python 3.12 and NumPy 1.26.4.

import numpy as np

def normalise(values):
    scale=max(float(np.max(np.abs(values),initial=0)),1e-12)
    scaled=values/scale
    return scaled/np.sqrt(np.dot(scaled,scaled)+(1e-12/scale)**2)

def sift_descriptor(patch):
    # Input has already been resampled into a canonical scale/orientation frame.
    # Its one-pixel border supports derivatives on the central 16x16 region.
    a=np.asarray(patch,dtype=float)
    if a.shape!=(18,18) or not np.isfinite(a).all():
        raise ValueError('need a finite 18x18 canonical grayscale patch')
    gx=(a[1:-1,2:]-a[1:-1,:-2])/2
    gy=(a[2:,1:-1]-a[:-2,1:-1])/2
    magnitude=np.hypot(gx,gy)
    angle=np.mod(np.arctan2(gy,gx),2*np.pi)*8/(2*np.pi)
    hist=np.zeros((4,4,8))
    for y in range(16):
        for x in range(16):
            cy,cx=(y+.5)/4-.5,(x+.5)/4-.5
            by,bx,bo=int(np.floor(cy)),int(np.floor(cx)),int(np.floor(angle[y,x]))
            fy,fx,fo=cy-by,cx-bx,angle[y,x]-bo
            weight=magnitude[y,x]*np.exp(-((x-7.5)**2+(y-7.5)**2)/(2*8**2))
            for iy,wy in ((by,1-fy),(by+1,fy)):
                for ix,wx in ((bx,1-fx),(bx+1,fx)):
                    if 0<=iy<4 and 0<=ix<4:
                        hist[iy,ix,bo%8] += weight*wy*wx*(1-fo)
                        hist[iy,ix,(bo+1)%8] += weight*wy*wx*fo
    vector=normalise(hist.ravel())
    return normalise(np.minimum(vector,.2))

if __name__=='__main__':
    ramp=np.tile(np.arange(18,dtype=float),(18,1))
    descriptor=sift_descriptor(ramp)
    print('dimensions:',descriptor.size,'norm:',round(float(np.linalg.norm(descriptor)),6))
    print('positive gain and offset:',np.allclose(descriptor,sift_descriptor(3*ramp+7)))
    print('constant patch norm:',np.linalg.norm(sift_descriptor(np.ones((18,18)))))
    print('final clipping example:',normalise(np.minimum(normalise(np.array([1.,0.])),.2)).tolist())
dimensions: 128 norm: 1.0
positive gain and offset: True
constant patch norm: 0.0
final clipping example: [1.0, 0.0]

normalise first rescales by the largest absolute component, avoiding an unnecessary overflow from directly squaring a large histogram. Algebraically it implements the epsilon-normalized expression above. The tests include a large finite gain of 10²⁰⁰, although arbitrary floating-point extremes in earlier gradient arithmetic are not guaranteed safe.

For a patch containing P samples and B histogram entries, voting takes O(P) work with a constant number of contributions per sample; normalization takes O(B). Here P=256 and B=128. This is descriptor cost only, not the cost of the complete SIFT pipeline.

A literal ramp reference checks spatial weights and orientation bins. Other tests cover constant patches, gain and offset, signed contrast reversal, an unnormalized raw rotation and the final clipping counterexample. A rotated raw patch changes the descriptor because this function does not estimate or undo its rotation.

Where the method breaks

A distinctive descriptor can still find the wrong neighbour in a repeated pattern. Comparing the nearest and second-nearest distances tests ambiguity, but any ratio threshold is a decision rule tied to data and evaluation conditions, not a universal probability of correctness. Geometric consistency across several matches supplies evidence that a single descriptor cannot.

Scale and orientation handling improve repeatability under the modeled transformations; they do not guarantee invariance to occlusion, perspective changes, deformation, severe blur or every illumination change. The detector may choose a different location before the descriptor is even computed. A match failure can therefore come from detection, frame estimation, descriptor construction or matching, and these stages should be evaluated separately.

The teaching patch conventions are explicit and are not claimed to be bit-identical to OpenCV or Lowe’s implementation. A successful synthetic gain test is not a reproduction of the paper’s image-matching experiments.

Exercises with answers

1. Why is the descriptor 128-dimensional?

Answer. It concatenates 4×4 spatial cells with 8 orientation bins each. The keypoint location, scale and orientation are separate metadata.

2. Can the final vector contain a value greater than 0.2?

Answer. Yes. Starting from (1,0), clipping yields approximately (0.2,0), and renormalization returns approximately (1,0).

3. Does passing a rotated raw patch into this function prove rotation invariance?

Answer. No. It assumes a canonical frame; it does not estimate orientation or resample the rotated patch. The test intentionally demonstrates a change.

4. Two nearest descriptors have nearly equal distances. What should a matcher infer?

Answer. The local evidence is ambiguous. Reject or defer the match and seek additional geometric/contextual evidence; closeness alone does not identify the correct point.

Sources and next steps

The source scope here extends beyond the separate historical introduction: the 28-page author version’s pipeline overview and orientation/descriptor/normalization passages were read. Its January 5, 2004 header is a version date, not an asserted journal publication day. Distinctive Image Features from Scale-Invariant Keypoints — author version Introduction to SIFT — OpenCV 4.10.0

Edges and corners explains local information before descriptor construction. Compare HOG to see how related gradient histograms can describe a fixed detection window with different orientation and normalization choices.

Make a prediction, then check

Which operation is missing from this descriptor-only implementation?

Choose one answer

Learning objectives

  • Separate keypoint detection, canonical frames and description.
  • Implement soft histogram voting and test normalization limits.

Prerequisites & connections

Explore related knowledge →

References

  1. Distinctive Image Features from Scale-Invariant Keypoints — author version
    David G. Lowe · 2004
  2. Introduction to SIFT — OpenCV 4.10.0
    OpenCV contributors

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.
  • 6 tests: independent ramp/cell-weight reference, gain/offset and10^200 gain, constant patch, signed reversal/raw rotation, final clipping counterexample and bad input. Only canonical-patch descriptor; no detector, scale pyramid, orientation estimator or image matching benchmark.
  • 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.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.