Chapter 3: Image Processing
Fundamental techniques for manipulating and enhancing digital images
- Topics
- 6
- Demos
- 2
- Videos
- 4
- Min read
- 39
Chapter Overview
Now that we understand how images are formed, it's time to manipulate them. Image processing provides the tools to enhance, filter, and transform images.
What is this chapter about? We cover the fundamental operations that transform pixel values—from simple brightness adjustments to sophisticated filtering using convolution. These are the building blocks used in every computer vision pipeline.
Why does this matter? Before any high-level analysis, images usually need preprocessing:
- Noise reduction to clean up sensor artifacts
- Contrast enhancement to make features more visible
- Edge detection to find boundaries between regions
- Frequency analysis to understand image structure at different scales
How the topics connect: We start with point operators that transform each pixel independently—simple but powerful. Then linear filtering introduces convolution, which considers neighborhoods of pixels. We explore the frequency domain where convolution becomes multiplication, enabling efficient processing. Finally, histogram analysis provides tools for contrast enhancement and image comparison.
Chapter Roadmap
Click any topic to jump in
Point Operators
Per-pixel transforms, gamma correction, and histograms — operations that don't depend on neighbors.
Color Transforms
RGB to grayscale, HSV conversion, and color matrices — changing color representations.
Linear and non-linear approaches
Linear Filtering
Convolution, separable filters, and Gaussian blur — the workhorse of image processing.
Non-linear Filtering
Median, bilateral, and morphological filters — edge-preserving operations that convolution can't do.
Frequency analysis and spatial warping
Fourier Transforms
DFT and the convolution theorem — understanding images in the frequency domain.
Geometric Transforms
Affine, bilinear interpolation, and homography — warping images to new coordinate systems.
Topics
6 topics in this chapter
The previous chapter explained how a scene becomes a grid of pixel values; this chapter begins the work of changing those values. The simplest way to change them is one pixel at a time, with an output that depends only on the single input pixel beneath it and nothing about its neighbors. That is a point operator, and despite its simplicity it covers a surprising amount of everyday image work: brightening an underexposed photo, stretching a washed-out one to full contrast, or bending midtones with a tone curve. Because each pixel is independent, these operations parallelize trivially across millions of pixels with no coordination. We build up three of them in order. First the linear transform, a gain-and-bias adjustment that scales contrast and shifts brightness. Then gamma correction, a nonlinear curve that matches the eye's response and undoes display encoding. Finally the histogram, which summarizes the whole distribution of intensities and sets up automatic contrast enhancement through equalization.
Definition
A point operator is an image transformation whose output at each pixel depends only on the input value at that same pixel, independent of every neighbor. Formally for some function applied identically everywhere. Brightness, contrast, gamma, and tone curves are all point operators.
In this topic
- 1Linear Transform
- 2Gamma Correction
- 3Histogram
Linear Transform
The linear transform is the most basic point operator, adjusting each pixel with a multiply and an add: . The gain controls contrast — values above 1 stretch the intensity range and spread pixels apart, values below 1 compress it. The bias is a brightness offset — positive shifts everything lighter, negative darker. Together they perform exposure correction and normalization. The operation is called linear because output is a straight-line function of input, so it cannot fix a nonlinear problem like a wrong gamma curve. Its most common use is contrast stretching: mapping an image's actual min and max onto the full 0 to 255 range.
The linear point operator is a scalar affine map applied independently to each pixel. In vector terms, if the image is a vector , then is an element-wise affine transform that shifts the mean by and scales the variance by . Contrast stretching is the special case that maps onto via , which is the unique affine map satisfying the two boundary conditions.
An image has pixel values in range [40, 180]. Find and to stretch this to [0, 255].
Gamma Correction
Gamma correction is a nonlinear point operator that raises the normalized pixel value to a power: . Unlike the linear transform it bends the tone curve rather than tilting it. With the curve lifts dark regions much more than bright ones, rescuing detail from underexposed shadows; with it pulls midtones down, taming overexposure. At nothing changes. The reason gamma matters is perceptual: human vision responds to light roughly logarithmically, so equal steps in encoded value look like equal steps in brightness only after a gamma curve. Standard sRGB bakes in , which is why raw linear light must be gamma-encoded before display and decoded before physically correct arithmetic.
Gamma correction applies the power-law nonlinearity , which is a monotonic concave function for and convex for . The sRGB standard uses a piecewise function combining a linear segment near zero with a power law. In information-theoretic terms, gamma encoding allocates more code values to dark tones where human contrast sensitivity is highest, effectively performing a form of perceptual quantization that minimizes visible banding for a fixed bit depth.
A pixel has intensity 100. What is its value after gamma correction with (brightening)?
Histogram
A histogram is not a transform but a summary: it counts how many pixels hold each intensity value, turning the image into a distribution. Its shape diagnoses the image at a glance. A narrow spike means low contrast, values crowded into a small band; a wide spread means the full tonal range is in use. A mass piled at the left signals a dark, underexposed frame, piled at the right an overexposed one. The histogram also drives automatic enhancement: histogram equalization computes the cumulative distribution and remaps intensities so the output histogram is as flat as possible, expanding contrast without any manual gain or bias tuning.
The histogram estimates the probability mass function of pixel intensities. Histogram equalization seeks a monotonic mapping such that the output CDF is approximately uniform: where . This is an application of the probability integral transform — for continuous random variables, if , then . The discrete version only approximates uniformity because the CDF is a step function.
A 4×4 grayscale image has values: [0,0,1,1, 0,1,2,2, 1,2,2,3, 2,3,3,3]. Compute its histogram for range [0,3].
Theory Exercise
Problem:
An 8-bit grayscale image has pixel values ranging from 50 to 150. You want to stretch this to use the full range [0, 255]. What linear transformation parameters (α, β) should you use?
Hints:
- Find the current range: max - min
- Target range is 255 - 0 = 255
- α (gain) = target_range / current_range
- β (bias) must map the minimum value to 0
Related Problems on PixelBank
Point operators in the previous topic adjusted intensity, treating each channel or a grayscale value on its own. But color carries structure that a raw red-green-blue triple hides, and reorganizing that structure is often the key to a task. This topic is about color transforms: systematic ways to move between color representations and to recombine channels. RGB is how sensors and displays work, but it entangles brightness and color in every channel, which makes it awkward for many jobs. Converting to grayscale collapses color to perceived brightness with the right perceptual weights. HSV pulls hue, saturation, and value apart so you can select or adjust a color without disturbing its brightness — ideal for segmentation and skin detection. A general color matrix expresses any linear channel mixing, from grayscale to white balance to artistic effects, as a single 3 by 3 operation. Together these give you the vocabulary to choose the representation that makes your problem simplest.
Definition
A color transform maps a pixel's color from one representation to another, either by a change of color space (RGB to grayscale, HSV, or Lab) or by a linear recombination of channels via a matrix. The goal is to expose the structure — brightness, hue, or purity — that a given task needs.
In this topic
- 1RGB to Grayscale
- 2RGB to HSV
- 3Color Matrix
RGB to Grayscale
Reducing a color pixel to a single brightness value is a weighted sum of its channels, not a plain average, because the eye does not weight red, green, and blue equally. The Rec. 601 formula gives green the largest weight, since vision is most sensitive to green, red the next, and blue the least. This produces grayscale whose light-dark relationships match what a person perceives. A naive mean of the three channels ignores this and makes blues look too bright and greens too dark, subtly corrupting anything downstream that keys off intensity. The same weights form the luminance row of the RGB-to-YCbCr transform used in video.
The luminance formula is a weighted inner product where and . These weights derive from the CIE 1931 luminous efficiency function , which peaks near 555 nm (green). The projection collapses a 3D color space onto a 1D luminance axis — geometrically, it is the orthogonal projection onto the line defined by , losing the two chrominance dimensions.
Convert RGB pixel (200, 100, 50) to grayscale using perceptual weights.
RGB to HSV
HSV re-expresses a color with three intuitive axes instead of three additive primaries. Hue is the color type — an angle on the wheel from 0 to 360 degrees, so red, green, and blue sit at 0, 120, and 240. Saturation measures purity from 0, a pure gray, to 1, a fully vivid color. Value is brightness, from 0 black to 1 maximum. The advantage over RGB is separation: you can change brightness or saturation without shifting the hue, exactly what color-based segmentation and skin detection need. Because value is the channel max and saturation a relative spread, the conversion is a coordinate change from cube to cylinder.
The RGB-to-HSV conversion is a coordinate transform from the unit RGB cube to a cylindrical coordinate system. Value is the norm of the color vector, saturation measures the relative gamut distance, and hue is the angle on the hexagonal cross-section of the RGB cube projected along the diagonal. The hexagonal geometry arises because the projection of the cube's faces creates a regular hexagon, making a piecewise-linear function of the channel ratios with period .
A pure red pixel has RGB (255, 0, 0). What are its HSV values?
Color Matrix
A color matrix generalizes channel manipulation into one linear operation: multiply the RGB vector by a 3 by 3 matrix to get new channels, . Different matrices give different effects. The identity leaves color untouched. A matrix with the perceptual weights repeated in all three rows collapses to grayscale. Blending between identity and that grayscale matrix adjusts saturation smoothly. A diagonal matrix scales each channel independently, which is exactly white balance. Because the operation is linear it composes — chaining several corrections multiplies into a single matrix applied once per pixel. This unifies color correction, artistic effects, and display calibration under one efficient, hardware-friendly primitive used throughout camera pipelines.
A color matrix defines a linear map on the RGB color space. The identity matrix preserves colors; the rank-1 matrix (where is the luminance weights) projects to grayscale. Saturation adjustment interpolates between grayscale () and identity (). White balance uses a diagonal matrix , which is a special case that preserves the principal axes of color space.
Write a color matrix that swaps red and blue channels (creates a 'negative' color effect).
Theory Exercise
Problem:
A pixel has RGB values (180, 60, 120). Convert this to HSV color space. Show all intermediate calculations.
Hints:
- First normalize RGB to [0, 1] range
- Find max and min values
- V (value) = max
- S (saturation) = (max - min) / max if max ≠ 0
- H (hue) depends on which channel is max
Related Problems on PixelBank
Point operators and color transforms both share a blind spot: they treat every pixel in isolation, so they can never respond to what surrounds a pixel. Yet almost everything interesting in an image — edges, texture, blur, noise — is defined by how a pixel relates to its neighbors. Linear filtering removes that blind spot. It computes each output pixel as a weighted sum of a small neighborhood in the input, with the weights arranged in a kernel that slides across the image. That single operation, convolution, is astonishingly versatile: choose the weights one way and you blur, another way and you sharpen, another and you detect edges. It is important enough that convolutional neural networks adopt it as their fundamental layer. We start with convolution itself and its algebraic properties, then separability, a trick that makes large kernels cheap, and finally the Gaussian filter, the single most important smoothing kernel and the gateway to scale-space.
Definition
Linear filtering replaces each pixel with a weighted sum of its neighbors, where the weights are given by a fixed kernel. The core operation is convolution: the kernel is flipped and slid over the image, and at each position the overlapping values are multiplied and summed to form one output pixel.
In this topic
- 1Convolution Operation
- 2Separable Filters
- 3Gaussian Filter
Convolution Operation
The fundamental operation in image filtering—a sliding window that computes weighted sums:
- Center the kernel at pixel
- Multiply overlapping values element-wise
- Sum all products to get the output value
Properties:
- Commutative:
- Associative:
- Distributive:
- Linear: Scaling and addition work as expected
Correlation vs Convolution: Convolution flips the kernel; correlation doesn't. For symmetric kernels, they're identical. Deep learning uses correlation but calls it 'convolution'.
Border Handling: What to do at edges? Options: zero padding, replicate, reflect, wrap.
Discrete 2D convolution is a linear operator: it maps the input image to the output through a Toeplitz (doubly-block-circulant) matrix. The operation is commutative, associative, and distributive, forming a commutative algebra. Computational complexity is for an image with a kernel. The kernel flip (using rather than ) ensures associativity; without it, chaining three filters would give different results depending on grouping.
Apply a 3×3 averaging kernel (all 1/9) to center pixel of patch: [10,20,30; 40,50,60; 70,80,90].
Separable Filters
A 2D filter that factors into two 1D filters:
- Apply horizontal 1D filter first
- Then apply vertical 1D filter
Computational savings: An kernel normally requires multiplications per pixel. Separable filtering reduces this to operations—a huge speedup for large kernels.
Which filters are separable?
- Separable: Gaussian, box, Prewitt
- Not separable: Laplacian (but can be approximated), Sobel
Testing separability: Compute SVD of kernel matrix. If rank-1 (single non-zero singular value), it's separable. The singular vectors give the 1D filters.
A 2D kernel is separable if and only if , meaning for column vector and row vector . This factorization reduces the per-pixel cost from multiplications to . The SVD of reveals separability: if with all other singular values zero, then and . The Gaussian kernel is separable because .
A 3×3 box blur has 9 multiplications per pixel. How many operations does the separable version need for a 1000×1000 image?
Gaussian Filter
The most important smoothing filter in image processing:
- (sigma): Controls blur amount—larger means more smoothing
- Bell-shaped: Nearby pixels have high weight, distant pixels have low weight
- Separable: Can be applied as two 1D filters for efficiency
- Rotationally symmetric: Same blur in all directions
- Cascade property:
Kernel size: Typically use (covers 99.7% of Gaussian).
Scale-space: Repeatedly applying Gaussian blur creates a scale pyramid, revealing features at different sizes. Foundation of SIFT and other scale-invariant methods.
The 2D Gaussian is the unique kernel that is simultaneously rotationally symmetric, separable, and self-similar under convolution: . It is the Green's function of the heat equation , so Gaussian blurring at scale is equivalent to letting the image "diffuse" for time . The Central Limit Theorem guarantees that repeated convolution with any finite-variance kernel converges to a Gaussian, making it the natural smoothing operator.
What kernel size should you use for a Gaussian filter with ?
Theory Exercise
Problem:
Apply a 3×3 Sobel edge detection filter to find the horizontal gradient:
Kernel: [-1, 0, 1; -2, 0, 2; -1, 0, 1]
Image patch: [100, 110, 120] [105, 115, 125] [110, 120, 130]
Calculate the output value at the center pixel.
Hints:
- Multiply each kernel element with the corresponding image pixel
- Sum all the products
- The result represents the horizontal edge strength
- Positive values indicate light-to-dark transition (left to right)
Related Problems on PixelBank
Linear filtering in the previous topic is powerful but has an unavoidable weakness: because every output is a fixed weighted sum, a smoothing kernel that suppresses noise also blurs the edges you want to keep. There is no linear filter that removes salt-and-pepper specks yet leaves a sharp boundary crisp. Nonlinear filters escape this trade-off by making the output depend on the neighborhood in a way that is not a simple weighted sum. This topic covers three of them. The median filter replaces each pixel with the middle value of its neighborhood, annihilating impulse outliers while preserving edges exactly. The bilateral filter smooths within uniform regions but refuses to average across an intensity jump, giving edge-preserving denoising. Morphological operations work on shape itself, growing, shrinking, and cleaning regions with a structuring element. None of these can be written as convolution, which is precisely the source of their extra power over the linear filters that came before.
Definition
A nonlinear filter computes each output pixel from its neighborhood using an operation that is not a weighted sum — such as taking a median, weighting by intensity similarity, or a min/max over a shape. This lets it remove noise or reshape regions while preserving edges that linear convolution would blur.
In this topic
- 1Median Filter
- 2Bilateral Filter
- 3Morphological Operations
Median Filter
The median filter replaces each pixel with the median of its neighborhood rather than a weighted average, and that one change gives it two properties no linear filter has. First, it destroys salt-and-pepper noise completely: an isolated black or white speck is an extreme outlier, and the median ignores outliers, so the corrupted value never appears in the output. Second, it preserves edges, because the median of a neighborhood straddling a boundary is still a real value on one side, not a blurred blend. The cost is that it requires sorting each neighborhood, making it slower than convolution, and it cannot be expressed as a linear kernel.
The median filter replaces each pixel with the -th order statistic of its neighborhood. Its breakdown point is 50% — up to half the window values can be arbitrarily corrupted without affecting the output. This is optimal among all location estimators. The operation is idempotent on binary images and has complexity per pixel naively, though Huang's algorithm achieves by maintaining a running histogram. Unlike convolution, the median is a nonlinear operator: .
Apply 3×3 median filter to center of: [100, 255, 110; 105, 0, 115; 108, 112, 120] (salt & pepper noise).
Bilateral Filter
The bilateral filter achieves edge-preserving smoothing by weighting neighbors with two Gaussians at once. The spatial Gaussian gives nearby pixels more influence, as an ordinary blur does. The range Gaussian adds a factor that gives pixels of similar intensity more influence and very different pixels almost none. Multiplied together, these weights mean a pixel is averaged only with neighbors close in both space and brightness. Inside a smooth region every neighbor qualifies and the filter blurs normally, but across an edge the large intensity difference drives the range weight to nearly zero, so the two sides never mix. This is why it denoises skin in portraits without softening boundaries.
The bilateral filter weight is the product of a spatial Gaussian and a range Gaussian. This makes it a locally adaptive, non-stationary filter — the effective kernel shape changes at every pixel depending on the local intensity landscape. Near an edge with intensity step , the range weight decouples the two sides, preventing cross-edge diffusion. The naive complexity is but fast approximations exist via bilateral grid () or permutohedral lattice.
Center pixel is 100, neighbor is 200 (across an edge). With , what's the range weight?
Morphological Operations
Morphological operations process the shape of regions rather than their pixel intensities, using a small structuring element slid over the image like a probe. Dilation expands bright regions and fills small gaps by taking the maximum under the probe; erosion shrinks bright regions and removes small specks by taking the minimum. Composing them yields the truly useful operations: opening, an erosion followed by a dilation, removes small bright noise while keeping large shapes their original size; closing, a dilation followed by an erosion, fills small dark holes. These are the workhorses of binary image cleanup, indispensable for tidying segmentation masks and extracting boundaries before higher-level analysis.
Mathematical morphology defines dilation and erosion as supremum and infimum over translated structuring elements: and . These form an adjunction: , establishing a Galois connection on the lattice of images ordered by pixel intensity. Opening is the largest -open set contained in , while closing is the smallest -closed set containing . Both are idempotent and monotone increasing.
A binary mask has a 1-pixel hole. What morphological operation fills it?
Theory Exercise
Problem:
Given a 3×3 image patch affected by salt & pepper noise:
[50, 255, 60] [55, 0, 65] [58, 62, 255]
Apply a 3×3 median filter. What is the output value at the center pixel? Compare this with a 3×3 box blur filter (average).
Hints:
- Collect all 9 pixel values from the patch
- Sort them in ascending order
- Median is the middle value (5th element)
- For comparison, box blur averages all 9 values
Related Problems on PixelBank
Every filtering technique so far has worked in the spatial domain, reasoning about pixels and their neighbors directly. This topic introduces a completely different and complementary viewpoint: the frequency domain. The Fourier transform rewrites an image as a sum of sine waves of varying frequency, revealing structure that is invisible pixel by pixel. Low frequencies describe smooth, slowly varying regions; high frequencies capture edges, fine texture, and noise. This change of perspective is not just conceptual — it has a decisive practical payoff. The convolution theorem states that convolution in space becomes simple multiplication in frequency, which turns an expensive large-kernel filter into a cheap pointwise product once you pay for the transform. We build this in three steps. First the continuous Fourier transform and what magnitude and phase each encode. Then the discrete DFT for sampled images and the FFT that makes it fast. Finally the convolution theorem, the bridge that connects the spatial filtering of earlier topics to efficient frequency-domain processing.
Definition
The Fourier transform decomposes a signal or image into a sum of sinusoids, expressing it as a function of spatial frequency rather than position. The result is complex: its magnitude says how much of each frequency is present, and its phase says where those patterns sit in the image.
In this topic
- 1Fourier Transform
- 2Discrete Fourier Transform (DFT)
- 3Convolution Theorem
Fourier Transform
Decomposes an image into its frequency components:
- Low frequencies (near center): Smooth variations, overall brightness
- High frequencies (edges): Sharp transitions, fine details, noise
Magnitude vs Phase:
- (magnitude): How much of each frequency is present
- (phase): Where patterns are located
Surprisingly, phase carries more perceptual information than magnitude. Swapping phases between two images makes them look like each other, while swapping magnitudes has less effect.
Frequency Domain Interpretation:
- Horizontal edges → vertical line in frequency domain
- Periodic patterns → dots at corresponding frequencies
- Sharp edges → energy spread across high frequencies
The 2D Fourier Transform decomposes an image into complex sinusoidal basis functions that form a complete orthonormal set in . Parseval's theorem guarantees energy conservation: . The magnitude is invariant to spatial translation (shift theorem: shifting by multiplies by , which only changes phase), while the phase encodes spatial structure and is perceptually more important than magnitude.
An image has strong horizontal stripes. Where will the energy appear in its Fourier magnitude spectrum?
Discrete Fourier Transform (DFT)
The discrete version for digital images with samples:
- Computes complex frequency coefficients from spatial samples
- naive computation, but FFT achieves
- Results are periodic—only unique frequencies (Nyquist limit)
Inverse DFT recovers the original signal:
2D DFT: For images, apply 1D DFT to rows, then to columns (or vice versa—order doesn't matter).
Implementation: Use np.fft.fft2() and np.fft.fftshift() to center the zero-frequency component.
The DFT can be written as a matrix-vector product where is the DFT matrix — a unitary matrix (up to scaling) whose columns are the -th roots of unity. The FFT exploits the factorization of into sparse butterfly matrices, reducing complexity from to . The Nyquist-Shannon theorem constrains the DFT: a signal sampled at rate can only represent frequencies up to ; higher frequencies alias to lower ones.
For a 1024×1024 image, compare FFT complexity to naive DFT.
Convolution Theorem
A fundamental property linking spatial and frequency domains:
- Convolution in space = Multiplication in frequency
- Multiplication in space = Convolution in frequency
Computational Advantage: For kernel size and image size :
- Direct convolution:
- FFT-based:
FFT is faster when (roughly for typical images).
Applications:
- Fast large-kernel blur
- Deconvolution (deblurring)
- Template matching
- Wiener filtering for noise removal
The convolution theorem states : convolution in the spatial domain equals pointwise multiplication in the frequency domain, and vice versa. This duality follows from the eigenfunction property of complex exponentials under the convolution operator. For an image with a kernel, direct convolution costs while FFT-based convolution costs — faster whenever (roughly for typical images). Deconvolution inverts the multiplication: , though this is ill-conditioned where and requires regularization (Wiener filter).
To blur with a 25×25 Gaussian, should you use direct convolution or FFT for a 512×512 image?
Theory Exercise
Problem:
A 4-point signal is given: x[n] = [1, 2, 3, 4]. Compute the first two DFT coefficients X[0] and X[1] using the formula:
X[k] = Σ(n=0 to N-1) x[n] · e^(-i2πkn/N)
where N=4.
Hints:
- X[0] is the DC component (sum of all values)
- For X[1], use k=1, N=4
- Euler's formula: e^(-iθ) = cos(θ) - i·sin(θ)
- Remember: e^(-iπ/2) = -i, e^(-iπ) = -1, e^(-i3π/2) = i
Related Problems on PixelBank
Every operation earlier in this chapter changed pixel values while leaving each pixel in place. Geometric transforms do the opposite: they move pixels to new locations, rotating, scaling, warping, or rectifying an image, while ideally leaving the underlying colors intact. This is what you need to align two photographs, correct a skewed perspective, stitch a panorama, or place a virtual object in a scene. The central difficulty is that when a source pixel maps to a fractional target location, or a target pixel pulls from between source samples, there is no exact value to copy — it must be interpolated. We develop the topic in three layers of increasing generality. Affine transformations handle translation, rotation, scale, and shear, preserving parallel lines. Bilinear interpolation solves the sampling problem cleanly and cheaply. Homographies extend to full projective warps that can even make parallel lines converge, the model behind perspective correction and planar panorama stitching.
Definition
A geometric transformation remaps pixel coordinates rather than pixel values, moving points to new positions according to a spatial mapping such as an affine or projective matrix. Because mapped positions rarely land on the integer grid, it must be paired with interpolation to compute the resampled values.
In this topic
- 1Affine Transformation
- 2Bilinear Interpolation
- 3Homography
Affine Transformation
An affine transformation is the family of geometric maps that preserve parallel lines and ratios of distances along a line. It bundles translation, rotation, scaling, and shear into a single matrix acting on homogeneous coordinates, with the last row fixed at . That structure gives it six degrees of freedom — two for translation, four in the upper 2 by 2 block for rotation, scale, and shear — so three point correspondences, each supplying two equations, solve for it. Affine transforms compose by matrix multiplication and are always invertible when the linear part is non-singular. They are the right model for image registration when camera motion is approximately planar.
An affine transformation preserves collinearity, parallelism, and ratios of distances along any line. In homogeneous coordinates, it becomes a matrix with last row , giving 6 degrees of freedom (2 for translation, 1 for rotation, 2 for scale, 1 for shear). Three point correspondences yield 6 equations (2 per point) that uniquely determine . The set of 2D affine transforms forms a group under composition (matrix multiplication), with the inverse always existing since the sub-matrix must be non-singular.
Write the affine matrix to translate by (50, -30) then scale by 2× in both directions.
Bilinear Interpolation
Bilinear interpolation estimates a pixel value at a non-integer location from its four nearest grid neighbors, and it is the default resampling method for geometric transforms. It works in two stages: interpolate linearly along one axis between the top pair and the bottom pair, then interpolate along the other axis between those two results. The effect is a smooth blend weighted by how close the query point is to each corner. Compared with nearest-neighbor it removes the blocky look of copying the closest pixel, and compared with bicubic it is faster and free of ringing. That balance makes it the standard choice for scaling and warping.
Bilinear interpolation computes where are the fractional pixel offsets. This is a tensor product of two linear interpolants, hence the name bilinear — it is linear along each axis but contains the cross-term , making it quadratic overall. The interpolation kernel in continuous form is a tensor product of triangle (hat) functions with support . The frequency response falls off as , introducing mild blurring — a known tradeoff between the blockiness of nearest-neighbor ( per pixel) and the ringing of bicubic (16-tap, per pixel but higher constant).
Find pixel value at (1.5, 0.75) given corners: f(1,0)=100, f(2,0)=120, f(1,1)=110, f(2,1)=140.
Homography
A homography is the most general planar transform, a projective mapping represented by a 3 by 3 matrix applied in homogeneous coordinates, with the result divided through by its third coordinate. Unlike an affine transform it does not preserve parallel lines — under a homography, parallel lines can converge to a vanishing point, exactly what perspective does. It has eight degrees of freedom, nine matrix entries minus one for scale, so four point correspondences, each giving two equations, determine it. Homographies exactly describe the mapping between two views of a planar scene, or between two images from a purely rotating camera, which powers panorama stitching and marker-based augmented reality.
A homography (projective transformation) is a matrix applied in homogeneous coordinates: , with the result dehomogenized by dividing by the third coordinate. It has 8 degrees of freedom (9 entries minus 1 for scale) and maps lines to lines, but unlike affine transforms, it does not preserve parallelism — parallel lines can converge to a vanishing point. Four point correspondences give 8 equations via the DLT (Direct Linear Transform), solved as the null space of an matrix. The homography is the exact model for the mapping between two views of a planar scene, or between any two views with a purely rotating camera.
How many point correspondences are needed to compute a homography? Why?
Theory Exercise
Problem:
You want to rotate an image by 30° counterclockwise around the origin, then scale it by 2× horizontally and 1.5× vertically. Write the combined transformation matrix in homogeneous coordinates.
Hints:
- Rotation matrix: [cos θ, -sin θ; sin θ, cos θ]
- Scale matrix: [sx, 0; 0, sy]
- Combined matrix = Scale × Rotation
- Use homogeneous coordinates (3×3 matrix)