Key ideas
- Computer vision aims at a high-level understanding of images and video: finding objects, recognising events, describing a picture, reconstructing a scene in 3D, estimating age or emotion from a face1. Optical flow describes how pixels move between video frames: dense flow gives a motion vector for every pixel, sparse flow follows only distinctive feature points1.
- Images are arrays: an 8-bit colour image is height × width × channels with values 0–255, so a "320×200" image is a array; OpenCV loads the channels in BGR order, Matplotlib and most other tools expect RGB1. PyTorch models take float minibatches of shape (N, C, H, W);
ToTensorturns images into 32-bit floats in , channels first2. Arithmetic onuint8wraps around modulo 256 (250 + 10 = 4, see the code), so convert to a wider type and clip. - Colour: Rec. 601 luma weights each primary by its contribution to perceived brightness, green most and blue least5. HSV separates hue and saturation from the value 5. R, G and B all rise and fall with the light hitting an object, so hue (with saturation and value) separates objects more reliably than raw RGB; colour segmentation therefore thresholds hue5.
- Filtering slides a small kernel over the image and takes a weighted sum at every pixel3. Classic kernels: identity (single 1 in the centre), box blur ( times all ones), Gaussian blur, sharpen, edge detectors; a kernel whose weights sum to 1 keeps the average brightness3. A true convolution flips the kernel in both directions first3; CNN layers skip the flip, i.e. they compute cross-correlation. Border pixels need a policy: extend, wrap, mirror, a constant such as zero padding, or a smaller (cropped) output3.
- Sobel estimates the image gradient. As cross-correlation with pointing right and down, subtracts the left column from the right with weights 1, 2, 1 and the top row from the bottom; the magnitude is and the direction , which is 0 for a vertical edge that is brighter on the right4. Each kernel is a central difference times a smoothing perpendicular to it (along the edge), so it is less sensitive to noise than a bare difference4. Texts print the kernels with different signs (convolution vs correlation, up vs down); the magnitude is the same4.
- Laplacian sums the second differences along and : zero on flat regions and on linear ramps, large at isolated spots, thin lines and beside step edges. Kernel tables often list its negative, with 4 in the centre, as an edge detector3.
- Median filter replaces each pixel by the median of its window6. An isolated impulse ("salt" or "pepper" pixel) is discarded instead of averaged in, while a mean filter smears it into the neighbours; this works as long as fewer than half of the pixels in a window are corrupted6. It is particularly effective against salt-and-pepper noise and preserves edges better than a Gaussian blur at moderate noise levels6.
- Histogram equalization maps each gray level through the cumulative histogram, spreading the most frequent levels over the full range and increasing global contrast, e.g. for X-rays that use only a narrow band of levels7.
- Integral image (summed-area table): is the sum of all pixels above and to the left, inclusive; any rectangle sum then takes 4 look-ups, whatever its size (formula below).
- Hand-crafted vs learned features: classic pipelines computed descriptors such as SIFT or HOG and trained a classifier such as an SVM on them8. In HOG each pixel of a cell votes with its gradient magnitude into an orientation histogram; Dalal and Triggs found 9 bins over 0–180° ("unsigned" gradients) best for detecting people8. CNNs instead learn the features from raw pixels, jointly with the classifier.
- Data augmentation creates random variants of the training images (flips, crops, colour changes): it enlarges the training set and makes the model rely less on the exact position or colour of an object, which improves generalization2. Left–right flips usually keep the category; up–down flips are less common2. Only training images are augmented; d2l applies no random transforms at prediction time, so predictions are deterministic2. Averaging the predictions over several augmented copies at inference is called test-time augmentation (TTA).
Formulas
In the equalization map, counts the pixels with level , is its smallest nonzero value, the number of pixels and the number of levels7. HSV from RGB in : , , hue in sectors depending on which channel is largest5.
Worked example
Sobel at the centre of the patch (cross-correlation, pointing down):
- (right column minus left column).
- (bottom row minus top row).
- Magnitude , direction : the intensity increases towards the bottom right. As a true convolution both kernels turn into their negatives, giving , and direction , with the same magnitude.
Median vs mean on the window with a "pepper" centre: the median is 12, the mean .
In code
import numpy as np
img = np.array([[250, 100], [30, 5]], dtype=np.uint8)
print((img + 10).tolist()) # [[4, 110], [40, 15]] uint8 wraps around
print(np.clip(img.astype(np.int16) + 10, 0, 255).astype(np.uint8).tolist()) # [[255, 110], [40, 15]]
batch = np.zeros((16, 120, 160, 3), dtype=np.uint8) # N x H x W x C, as images are loaded
print(batch.transpose(0, 3, 1, 2).shape) # (16, 3, 120, 160) N x C x H x W for PyTorch
green = np.array([0.0, 200.0, 0.0])
print(round(green @ np.array([0.299, 0.587, 0.114]), 1), round(green.mean(), 1)) # 117.4 66.7
Common pitfalls
- Array shape is (height, width, channels), not (width, height); OpenCV images are BGR, Matplotlib expects RGB1.
uint8arithmetic overflows silently (modulo 256); it does not saturate at 255.- A plain channel average makes pure green and pure blue equally bright; luma weights green about five times more than blue.
- Convolution and cross-correlation differ by a rotation of the kernel: for an antisymmetric kernel such as Sobel the outputs differ in sign, so gradient directions flip while magnitudes stay the same; kernels unchanged by the rotation (box, Gaussian, Laplacian) give identical results3.
- An augmentation must keep the label: rotating a 6 by 180° gives a 9, mirroring "b" gives "d", and large hue shifts can change a flower's species; overhead satellite images, in contrast, tolerate any rotation or flip.
- Augment only the training set, after the train/test split; augmented copies of one image on both sides of the split leak information into the test score.
- Histogram equalization is a global, nonlinear lookup through the cumulative histogram, not a linear stretch of the range7.
- Spectrograms are not natural images: shifting them vertically changes the frequencies, so image augmentations can hurt.
References
- AI for Beginners — Lesson 6 Introduction to Computer Vision: introduction; OpenCV (Loading Images); Examples of using Computer Vision (optical flow)
- Dive into Deep Learning — Sec. 14.1 Image Augmentation (introduction); 14.1.1.1 Flipping and Cropping; 14.1.2 Training with Image Augmentation
- Wikipedia: Kernel (image processing) — Details (table of kernels); Convolution; Edge handling; Normalization
- Wikipedia: Sobel operator — Formulation; Extension to other dimensions
- Wikipedia: HSL and HSV — Formal derivation (Lightness); Use in image analysis; Color conversion formulae (From RGB)
- Wikipedia: Median filter — Worked one-dimensional example; Edge preservation properties
- Wikipedia: Histogram equalization — Overview; Examples (Small image)
- Wikipedia: Histogram of oriented gradients — Algorithm implementation (Gradient computation; Orientation binning; Object recognition)