Measuring Relationships: From Inner Products to Attention · Chapter 2
Cross-correlation and convolution: the sliding inner product
Adding a shift to the inner product gives cross-correlation; flipping the kernel gives convolution. This chapter derives how the two relate, why linear time-invariant systems are exactly convolutions, and why normalized cross-correlation is the correlation coefficient over a window, with uses in template matching and stereo.
Series contentsChapter 2 of 4
Series
Measuring Relationships: From Inner Products to Attention- 01Inner products, covariance and correlation
- 02Cross-correlation and convolution: the sliding inner product
- 03From convolution to attention
- 04Mutual information: dependence beyond linearity
The question
Two signals have the same shape but are offset. How do we find the offset? More generally, how do we find where a given pattern occurs in an image?
The inner product of Chapter 1 only compares vectors that are already aligned. This chapter adds a single operation, the shift, which gives cross-correlation. It then shows that convolution differs from cross-correlation only by a flip, and explains why the “convolution” in a CNN actually computes cross-correlation.
Intuition
Slide a short template along a long signal. At each offset, take the inner product of the template with the stretch it covers. The result is a curve of match quality against position, and its peak marks the best alignment. In two dimensions the template moves pixel by pixel over the image and produces a response map.
Convolution computes almost the same thing, except that the template is flipped before sliding: reversed in 1D, rotated by 180° in 2D. The flip comes from what convolution means in systems theory. Convolution describes how the responses left behind by every past input impulse add up, and those responses run backwards in time relative to the input.
Plain cross-correlation has one flaw: bright regions produce large sums whatever their shape. Centering and normalizing both the template and the window removes the flaw, and the quantity that results is exactly the correlation coefficient from Chapter 1.
Formalism
Definitions
For real discrete signals , define
Texts differ in where they put the shift; the conventions differ only in the sign of .
Let be the flipped signal. Then
Cross-correlating with is the same as convolving with the flipped .
In two dimensions, with image , kernel and indices :
Fix a position and let be the window of the same size as centered there. is the inner product of the flattened kernel and the flattened window:
This is the sliding inner product.
Why the flip does not matter in a CNN
The kernel of a convolutional layer is a learned parameter. Training with convolution and obtaining is equivalent to training with cross-correlation and obtaining the flipped : both describe the same function, the two parameterizations correspond one to one, and gradient descent simply learns whichever version the layer uses.
Deep learning frameworks, PyTorch’s Conv2d for example, therefore implement cross-correlation and skip the flip. Chapter 9 of Goodfellow et al.’s Deep Learning says so explicitly. When later chapters say “convolutional layer”, the computation is cross-correlation.
Algebraic properties and translation equivariance
The flip buys convolution better algebra. Convolution is commutative and associative:
Associativity means two cascaded filters can be merged into one. Cross-correlation is not commutative; instead .
LTI systems are convolutions. Let be a linear time-invariant (LTI) system with impulse response . Any input decomposes into shifted impulses, .
- Linearity gives .
- Time invariance gives .
Together, . Every LTI system is a convolution, and every convolution is clearly LTI.
Translation equivariance. With the shift operator ,
where the middle step substitutes . Cross-correlation has the same property.
Shift the input and the output shifts by the same amount. A pattern produces the same response wherever it appears, which is where Chapter 3 begins its discussion of the CNN’s inductive bias.
Frequency domain. By the convolution theorem, . For real signals and the definition above, . For large templates the FFT makes matching much faster.
Normalized cross-correlation is a windowed correlation coefficient
Let the template have pixels and let be the window at position . The raw sum is inflated in bright regions. Removing the means and dividing by the scales gives normalized cross-correlation (NCC):
Treat the pixel pairs as paired samples, and this is precisely the sample correlation coefficient from Chapter 1. NCC inherits its properties directly:
- , and it equals 1 exactly when with .
- It is unchanged by an affine change of window brightness with , so it is robust to exposure gain and global illumination offsets.
Relation to the sum of squared differences (SSD). Let be the template and window vectors after centering and scaling to unit length. Then
After normalization, minimizing the squared difference and maximizing the correlation are the same criterion.
In robotics
Template matching
When the target’s appearance is known, such as a landing pad, the border of a marker board or a symbol on a charging station, NCC template matching is the most direct detector.
It is neither rotation- nor scale-invariant. In practice it needs templates at several scales and angles, or it gives way to feature-based methods.
Stereo matching
In a rectified stereo pair, a scene point moves only horizontally along the same image row. That horizontal offset is the disparity .
For a left-image pixel , with the column coordinate, search along the same row of the right image:
and recover depth as , where is the focal length in pixels and the baseline.
This is the first stage in the taxonomy of Scharstein and Szeliski (2002), which splits stereo matching into four stages: matching cost computation, cost aggregation, disparity computation and disparity refinement. NCC, SAD and census are all standard matching costs. When the two cameras’ exposures differ, NCC holds up better than SAD, precisely because of the affine invariance above.
Multi-view dense reconstruction, for example PatchMatch-based MVS, also commonly scores photometric consistency between neighbouring views with NCC.
Experiment
The first script checks that cross-correlation equals convolution with the flipped kernel.
import numpy as np
from scipy.signal import correlate2d, convolve2d
rng = np.random.default_rng(0)
I = rng.standard_normal((32, 32))
K = rng.standard_normal((3, 3))
corr = correlate2d(I, K, mode="valid")
conv = convolve2d(I, K[::-1, ::-1], mode="valid") # kernel rotated by 180°
print(np.allclose(corr, conv)) # True
The second script implements NCC by hand, compares it with OpenCV’s TM_CCOEFF_NORMED, and checks invariance to an affine brightness change.
import numpy as np
import cv2
rng = np.random.default_rng(0)
img = rng.random((120, 160)).astype(np.float32)
tpl = img[40:56, 70:90].copy()
def ncc_map(img, tpl):
h, w = tpl.shape
t = tpl - tpl.mean()
t_norm = np.sqrt((t**2).sum())
H, W = img.shape
out = np.empty((H - h + 1, W - w + 1), np.float32)
for u in range(H - h + 1):
for v in range(W - w + 1):
c = img[u:u + h, v:v + w]
c = c - c.mean()
out[u, v] = (t * c).sum() / (t_norm * np.sqrt((c**2).sum()) + 1e-12)
return out
mine = ncc_map(img, tpl)
ref = cv2.matchTemplate(img, tpl, cv2.TM_CCOEFF_NORMED)
print(np.abs(mine - ref).max()) # about 1e-6
print(np.unravel_index(mine.argmax(), mine.shape)) # (40, 70)
# affine brightness change of the template: same peak location and value
tpl2 = 0.5 * tpl + 0.2
res2 = cv2.matchTemplate(img, tpl2, cv2.TM_CCOEFF_NORMED)
print(np.unravel_index(res2.argmax(), res2.shape), res2.max()) # (40, 70), about 1.0
References
- Lewis, J. P. (1995). Fast normalized cross-correlation. Vision Interface.
- Scharstein, D., & Szeliski, R. (2002). A taxonomy and evaluation of dense two-frame stereo correspondence algorithms. International Journal of Computer Vision, 47(1–3), 7–42.
- Oppenheim, A. V., Willsky, A. S., & Nawab, S. H. (1997). Signals and Systems (2nd ed.). Prentice Hall.
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning, Chapter 9. MIT Press. https://www.deeplearningbook.org/
- Szeliski, R. (2022). Computer Vision: Algorithms and Applications (2nd ed.). Springer.