Chapter 2: Image Formation
Understanding how images are formed through geometric transformations, camera projections, the physics of light interaction with surfaces, how digital cameras capture the visual world, and how infrared cameras image heat.
- Topics
- 7
- Videos
- 7
- Min read
- 71
Chapter Overview
How does a 3D world become a 2D image? This fundamental question is at the heart of computer vision.
What is this chapter about? We study the complete image formation pipeline—from geometric transformations that describe how objects move in space, to camera models that project 3D points onto 2D images, to the physics of how light interacts with surfaces.
Why does this matter? Understanding image formation is essential for:
- 3D reconstruction: Inverting the projection to recover 3D from 2D
- Camera calibration: Measuring camera parameters for accurate measurements
- Augmented reality: Placing virtual objects correctly in real scenes
- Multi-view geometry: Understanding relationships between multiple views
How the topics connect: We start with geometric transformations in 2D and 3D—the mathematics of position and motion. Then we model cameras as projection systems that map 3D to 2D. We explore how light and color form the actual pixel values. Then we understand how digital sensors sample this continuous signal into discrete pixels. Finally, we step beyond visible light into infrared, where scenes emit their own light and pixels encode temperature as well as reflectance.
Chapter Roadmap
Click any topic to jump in
2D/3D Transforms
Homogeneous coordinates, rotation matrices, and composition — geometric transformations in 2D and 3D.
Projection and distortion
3D to 2D Projection
Camera intrinsics, extrinsics, perspective vs orthographic — how 3D worlds become 2D images.
Lens Distortion
Radial and tangential distortion, undistortion — correcting real camera imperfections.
Light and color
Lighting & Reflectance
Lambertian, specular, Phong, and BRDF models — how light interacts with surfaces.
Color & Camera
Bayer patterns, color spaces, white balance, gamma — how cameras capture color.
Sampling & Aliasing
Nyquist theorem, aliasing, anti-aliasing, and image pyramids — the signal processing foundation of CV.
Infrared Imaging
NIR vs thermal bands, IR-cut filters and day/night cameras, RGB-IR sensors, blackbody emission, emissivity, NUC, and active NIR depth (ToF, structured light) — imaging beyond visible light.
Topics
7 topics in this chapter
Point a camera at a scene, take a step sideways, and every object lands somewhere new in the frame; tilt the camera and the whole picture rotates. Before we can model a camera at all, we need a precise language for this shuffling of points in space — where things are, and how they move. Chapter 1 left off with the mathematical foundations: images as arrays of numbers and the vectors and matrices that act on them. This topic turns those matrices into geometric verbs. The awkward fact driving everything here is that rotation and scaling are matrix multiplications, but translation is addition, so a chain of moves cannot be written as one product. We fix that first with homogeneous coordinates, which absorb translation into a single matrix. From there we build up 2D rotations, then their far richer 3D cousins where order suddenly matters, and finally composition — stacking many transforms into one matrix you apply once. Get fluent here, because cameras, image warping, and 3D reconstruction are all just these operations wearing different names.
Definition
Geometric transformations map points from one coordinate system to another. In computer vision, these transformations are fundamental for modeling camera motion, object pose, image warping, and augmented reality applications.
The key transformations are:
- Translation: Shifting all points by a fixed offset
- Rotation: Rotating points around an axis
- Scaling: Changing the size of objects
- Affine: Preserves parallel lines (includes shear)
- Projective: Most general, used for camera models
In this topic
- 1Homogeneous Coordinates
- 2Rotation Matrix
- 33D Rotations
- 4Transformation Composition
Homogeneous Coordinates
Standard 2D transformations like rotation and scaling can be represented as 2×2 matrix multiplications. However, translation cannot—it requires addition. Homogeneous coordinates solve this by adding an extra dimension:
- 2D point becomes
- Now ALL transformations (including translation) can be expressed as matrix multiplications
- This allows us to chain transformations by multiplying matrices
The extra coordinate is typically 1. To convert back:
Points at Infinity: When , we get points at infinity—useful for representing directions and vanishing points in perspective geometry.
Transformation Hierarchy:
- Euclidean (3 DOF): Rotation + translation, preserves distances
- Similarity (4 DOF): + uniform scale, preserves angles
- Affine (6 DOF): General 2×3 matrix, preserves parallel lines
- Projective (8 DOF): Full 3×3 matrix, only preserves straight lines
Appending a coordinate turns the Euclidean group into a matrix group: in lets translations become linear. The projective equivalence is what makes perspective projection a matrix multiply — dividing by the third coordinate recovers pixel positions from homogeneous vectors.
Translate point by using a homogeneous transformation matrix.
Rotation Matrix
A 2D rotation by angle (counterclockwise) is represented by an orthogonal matrix with determinant 1. Key properties:
- (inverse is transpose)
- (preserves area, proper rotation)
- (improper rotation, includes reflection)
- Columns are orthonormal vectors (form an orthonormal basis)
- Composing rotations:
The Special Orthogonal Group SO(2): All 2D rotation matrices form a mathematical group called SO(2). This has important implications for interpolating between rotations and understanding motion.
Small Angle Approximation: For small (radians): Useful for linearizing rotation in optimization.
Rotation matrices live in SO(2): orthogonal () with . The orthogonality constraint means , so inverting a rotation is free — just transpose. The single-parameter family forms a group: composing two rotations is adding angles, .
Rotate the unit vector by counterclockwise.
3D Rotations
In 3D, rotations are more complex and form the group SO(3) (3 degrees of freedom despite 9 matrix elements). Common representations:
-
Rotation Matrices: 3×3 orthogonal matrices with det=1. Easy to compose but have 9 params for 3 DOF.
-
Euler Angles: Three sequential rotations (e.g., roll-pitch-yaw). Intuitive but suffer from gimbal lock where you lose a degree of freedom.
-
Axis-Angle: Rotation by angle around unit axis . Rodrigues' formula converts to matrix: where is the skew-symmetric matrix of .
-
Quaternions: 4D unit vectors with . Best for interpolation (SLERP) and avoids gimbal lock. Standard in robotics and 3D vision.
Lie Algebra: The tangent space of SO(3) at identity, denoted , is the space of skew-symmetric matrices. This is key for optimization on rotations.
3D rotations live in SO(3), a 3-dimensional manifold parameterized by 3 angles but embedded in with 6 constraints (). Unlike 2D rotations, 3D rotations do not commute: . This non-commutativity is why rotation order matters and why Euler angles suffer from gimbal lock.
What rotation matrix rotates around the z-axis (yaw)?
Transformation Composition
Multiple transformations can be combined by matrix multiplication. The order matters—transformations are applied right-to-left:
means: first Scale, then Rotate, then Translate
Rotating Around a Point P:
- Translate P to origin:
- Rotate:
- Translate back:
Combined:
Inverse Transformations: To undo :
Camera Transforms: World → Camera uses extrinsics , then Camera → Image uses intrinsics .
Composition is matrix multiplication: applying transform then gives (right-to-left). This associativity means you can precompute once and apply it to millions of points — the cost is one matrix multiply per point regardless of how many transforms were composed.
To rotate around point by , what sequence of transforms is needed?
Theory Exercise
Problem:
A robot arm needs to:
- Rotate 45° counterclockwise
- Then translate by (10, 5)
Write the combined transformation matrix in homogeneous coordinates. Then apply it to the point (2, 0) and find the final position.
Hints:
- Remember: apply rotation first, then translation
- For 45°: cos(45°) = sin(45°) = √2/2 ≈ 0.707
- The combined matrix is T · R
Related Problems on PixelBank
The previous topic gave us transformations that move points around within a space of fixed dimension. But a camera does something more destructive: it takes the three-dimensional world and flattens it onto a two-dimensional sensor, throwing away depth in the process. How exactly does a point floating in front of the lens end up at a specific pixel? Answering that is the whole game, because almost every 3D vision task — reconstruction, calibration, augmented reality — is really the job of running this flattening backwards. We build the model in layers. First the pinhole idea and perspective projection, where dividing by depth explains why far things look small. Then we split the camera's parameters into two groups: intrinsics, the fixed internal geometry captured by the matrix , and extrinsics, the rotation and translation that place the camera in the world. Multiplying them gives the full projection matrix. Finally we contrast perspective with orthographic projection, so you know when the simpler, depth-free model is a safe approximation and when it quietly lies.
Definition
Camera projection transforms 3D world coordinates into 2D image coordinates. This is the fundamental operation that explains how cameras capture images.
The pinhole camera model is the simplest projection model: light rays pass through a single point (the optical center or pinhole) and project onto the image plane. While real cameras use lenses, the pinhole model captures the essential geometry and is widely used in computer vision.
In this topic
- 1Perspective Projection
- 2Camera Intrinsic Matrix (K)
- 3Camera Extrinsic Matrix
- 4Orthographic vs Perspective
Perspective Projection
where is the focal length
In perspective projection, a 3D point projects to 2D image coordinates based on similar triangles. Objects further from the camera appear smaller—this is the foreshortening effect that gives images their sense of depth.
The projection divides by , which creates the depth-dependent scaling. This is a nonlinear operation, which is why we use homogeneous coordinates to represent it as a linear matrix multiplication.
In Homogeneous Coordinates: where is the 3×4 projection matrix.
Depth Ambiguity: A fundamental limitation—we lose depth information in projection. Points along the same ray through the camera center all project to the same pixel. This is why we need multiple views or other cues for 3D reconstruction.
Perspective maps 3D to 2D via division: , . The division by creates the depth-dependent scaling that makes distant objects appear smaller. In homogeneous coordinates this becomes linear: , and the nonlinearity hides in the final dehomogenization step.
A point at meters is viewed by a camera with focal length mm. Find the projected position.
Camera Intrinsic Matrix (K)
The intrinsic matrix encodes the internal camera parameters that map normalized camera coordinates to pixel coordinates:
- : Focal length in pixels. where is physical focal length and is pixels per mm.
- : Principal point—where the optical axis intersects the image plane (often near image center)
- : Skew parameter (usually 0 for modern cameras with rectangular pixels)
Degrees of Freedom: 5 parameters (4 if skew is 0)
Calibration Methods:
- Zhang's method: Multiple views of a planar checkerboard
- Tsai's method: Uses 3D calibration target
- Self-calibration: From scene structure (more complex)
IMPORTANT: K depends on resolution! If you resize the image, scale , , , proportionally.
The upper-triangular matrix encodes 5 internal parameters: focal lengths , principal point , and skew . It maps normalized camera coordinates to pixel coordinates: . Calibrating is essential because all metric reconstruction depends on knowing these parameters.
A 640×480 image has principal point at center and 35mm focal length with 100 pixels/mm. What is K?
Camera Extrinsic Matrix
The extrinsic parameters describe the camera's position and orientation in the world:
- : 3×3 rotation matrix (camera orientation) — 3 DOF
- : 3×1 translation vector — 3 DOF
Total: 6 DOF for camera pose.
Two Interpretations:
- transforms world points to camera frame
- Camera center in world coords:
Full Projection Matrix:
This 3×4 matrix has 11 DOF (12 entries - 1 for scale) and encodes everything needed to project 3D world points to 2D pixels.
Decomposing P: Given , you can recover , , using QR decomposition on the left 3×3 block.
The extrinsic is a rigid transform from world to camera frame. Combined with intrinsics: . This projection matrix has 11 degrees of freedom (6 extrinsic + 5 intrinsic) and can be estimated from 6 or more 2D-3D point correspondences using DLT.
If and (identity), where is the camera in world coordinates?
Orthographic vs Perspective
Orthographic projection ignores depth—objects maintain their size regardless of distance:
Useful for:
- Technical drawings and CAD
- Satellite/aerial imagery (objects very far from camera)
- Telecentric lenses in industrial inspection
- Approximate model for far objects with small depth variation
Weak Perspective (scaled orthographic): where is constant for all points. Useful approximation when depth variation is small relative to average depth.
Affine Camera: A generalization that includes orthographic and weak perspective.
Perspective Effects:
- Parallel lines converge at vanishing points
- Objects appear smaller with distance (foreshortening)
- Vanishing line: All vanishing points of parallel planes lie on a line (e.g., horizon)
Orthographic projection drops entirely: , . Mathematically, it is the limit of perspective as focal length and distance with constant. The projection matrix becomes — no division, so depth has zero effect on image position.
Two points at and are projected. How do they differ in orthographic vs perspective ()?
Theory Exercise
Problem:
A camera has the following intrinsic parameters:
- Focal length: pixels
- Principal point:
A 3D point in camera coordinates is at meters.
a) Write the intrinsic matrix b) Project the 3D point to pixel coordinates c) If the point moves to meters (same X, Y), what are the new pixel coordinates? What does this demonstrate?
Hints:
- Use the projection formulas: x = fx * X/Z + cx
- The intrinsic matrix has zeros in the skew position for most cameras
- Doubling Z should halve the distance from the principal point
Related Problems on PixelBank
The projection model from the previous topic assumed a perfect pinhole: every straight line in the world stays straight in the image. Real lenses break that promise. To gather enough light across a wide field of view, they bend rays by slightly different amounts at the edges than at the center, so a straight fence rail bows into a curve near the frame's border. Feed such an image to any algorithm that trusts the pinhole model — triangulation, homography estimation, pose recovery — and the geometry is subtly wrong, with errors that compound. This topic explains the distortion and how to remove it. We start with radial distortion, the dominant effect, modeled as a polynomial in the distance from the image center. Then tangential distortion, the smaller error from a lens not sitting parallel to the sensor. Next comes undistortion, the practical procedure of measuring the coefficients by calibration and remapping pixels back to where the pinhole model says they belong. We close on why all of this matters: which downstream tasks quietly fail when distortion is left uncorrected.
Definition
Real camera lenses introduce geometric distortions that cause straight lines in the world to appear curved in the image. Understanding and correcting these distortions is essential for accurate geometric measurements and 3D reconstruction.
The two main types are:
- Barrel distortion: Lines bow outward from center (common in wide-angle lenses)
- Pincushion distortion: Lines bow inward toward center (common in telephoto lenses)
In this topic
- 1Radial Distortion
- 2Tangential Distortion
- 3Distortion Correction (Undistortion)
- 4Why Distortion Matters
Radial Distortion
Radial distortion is the dominant lens imperfection, a byproduct of grinding elements into spherical rather than ideal shapes. It displaces every point along the line joining it to the image center, by an amount that grows with the radius — the distance from that center. The model multiplies the ideal radius by , whose coefficients are recovered by calibration. When , points far from the center are pulled inward: straight lines bow outward, giving the barrel distortion typical of wide-angle lenses. When , outer points are pushed outward: lines bow inward, the pincushion effect of telephotos. (This is the forward model used by OpenCV and Brown–Conrady: ideal → distorted.) Because the terms scale with even powers of , the effect vanishes at the center and peaks at the corners — exactly where it breaks the pinhole model's straight-line guarantee.
Radial distortion is modeled as a polynomial in the squared radius : . The first coefficient dominates — barrel distortion () bows lines outward, pincushion () bows inward. Higher-order terms matter only near image edges where is large.
A point at normalized radius with (pincushion). What's the distorted radius?
Tangential Distortion
Tangential distortion, also called decentering distortion, appears when the lens elements are not perfectly parallel to the image sensor — a small manufacturing misalignment. Unlike radial distortion, which pushes points straight toward or away from the center, it shifts them sideways, and is captured by two parameters and in the model and its vertical mirror. The displacements are typically ten to a hundred times smaller than the radial ones, so casual photography ignores them. But for precision work — photogrammetry, sub-pixel feature matching — leaving them out is a systematic bias, so calibration toolkits estimate alongside the radial coefficients.
Tangential distortion arises from lens elements not being perfectly parallel to the sensor. The model adds two parameters: . These terms are typically 10-100x smaller than radial distortion but matter for precision applications like photogrammetry where sub-pixel accuracy is required.
With , at point , what is the tangential displacement?
Distortion Correction (Undistortion)
Undistortion is the step that turns a physically distorted photograph back into one the pinhole model can trust. It has three parts. First, calibration: photograph a known pattern such as a checkerboard from several angles and solve for the intrinsic matrix and distortion coefficients that best explain the corner positions. Second, build a remapping: for every output pixel, use the model to compute which distorted source location it came from. Third, interpolate, because that source rarely lands on an integer pixel, so bilinear sampling fills the value. OpenCV wraps this in cv2.undistort. The result restores straight lines, the precondition every geometric algorithm downstream silently assumes.
Undistortion inverts the distortion function: given distorted coordinates, find the undistorted ones. Since the polynomial is not analytically invertible, OpenCV uses iterative fixed-point iteration: . Convergence is fast (3-5 iterations) because distortion coefficients are small.
A pixel appears at (505, 300) due to distortion but should be at (500, 300). How is undistortion applied?
Why Distortion Matters
Uncorrected distortion quietly poisons any computation that assumes straight lines and linear projection. In structure from motion it warps the recovered 3D geometry; in visual SLAM it shows up as slow localization drift; in augmented reality it makes virtual objects float off their anchors; in stereo it turns into depth error. The common thread is that distortion bends straight world lines into curves, invalidating epipolar geometry, homography fitting, and triangulation alike — all built on the pinhole model from earlier. The practical rule follows: undistort first, then do any geometric reasoning, because no downstream math recovers information the bent lens already scrambled.
Distortion breaks the linear projection model . Straight lines in 3D project to curves in the distorted image, invalidating algorithms that assume collinearity (epipolar geometry, homography estimation). Correcting distortion restores the pinhole model and is a prerequisite for any geometric reconstruction.
A corner appears 10 pixels away from true position due to distortion. How does this affect stereo depth at 5m?
Theory Exercise
Problem:
A camera has radial distortion coefficient (pincushion distortion). A point at normalized coordinates is observed.
a) Calculate the undistorted radius b) Apply the distortion model to find the distorted position c) How much displacement (in normalized units) does the distortion cause?
Hints:
- The radius r = sqrt(x² + y²)
- The distortion factor is (1 + k₁r²)
- Displacement = sqrt((x_d - x)² + (y_d - y)²)
Related Problems on PixelBank
So far this chapter has been about geometry: where a 3D point lands on the sensor. But that only fixes the location of a pixel, not its brightness. The previous topic corrected the lens so lines are straight; now we ask what actually determines the number stored at each pixel. The answer is the interplay of two things — the light falling on a surface and the way that surface reflects it. The same mug looks glossy under a hard lamp and flat under an overcast sky, because reflectance and illumination combine before the camera ever sees them. This topic builds that model from simple to general. We begin with Lambertian reflectance, the matte ideal where brightness depends only on the angle to the light. Then specular reflection adds mirror-like highlights that move with the viewer. The Phong model fuses ambient, diffuse, and specular into the workhorse of real-time shading. Finally the BRDF frames all of these as special cases of one general reflectance function, the language physically based rendering and inverse rendering both speak.
Definition
The appearance of objects in images depends on two factors: how light sources illuminate them (lighting) and how their surfaces reflect light (reflectance). Understanding these interactions is crucial for:
- Shape from shading: Recovering 3D shape from shading patterns
- Relighting: Changing illumination in images
- Material recognition: Identifying surface properties
- Photometric stereo: Using multiple light sources for 3D reconstruction
In this topic
- 1Lambertian Reflectance (Diffuse)
- 2Specular Reflectance
- 3The Phong Reflection Model
- 4BRDF (Bidirectional Reflectance Distribution Function)
Lambertian Reflectance (Diffuse)
Lambertian surfaces are ideal diffuse reflectors that appear equally bright from all viewing angles. The reflected intensity depends only on the angle between the surface normal and light direction .
Examples: matte paint, paper, unpolished wood, cloth
Physical Basis: Light penetrates the surface, scatters internally, and exits uniformly in all directions. The factor (dot product) accounts for the projected area receiving light.
Shape from Shading: This is the foundation—brighter regions face the light more directly. Under Lambertian assumption with known lighting, intensity variations directly reveal surface orientation.
Limitations: No real surface is perfectly Lambertian. Even matte surfaces have some specular component at grazing angles (Fresnel effect).
Lambert's cosine law states that reflected intensity is proportional to , where is the surface normal and is the light direction. This dot product means Lambertian appearance is view-independent — the surface looks the same from all angles. This simplicity is why Lambertian is the default assumption in shape-from-shading.
Light direction , normal (45° tilt), . Find intensity.
Specular Reflectance
Reflection:
Specular reflection is mirror-like reflection that creates bright highlights. The intensity depends on the angle between the reflection direction and view direction .
The shininess exponent controls highlight sharpness:
- Low (1-10): Rough surfaces, broad highlights
- High (100+): Polished surfaces, sharp highlights
- : Perfect mirror
Fresnel Effect: Real specular reflection increases at grazing angles. Even non-metals become mirror-like when viewed at steep angles (think of a road surface far away).
Blinn-Phong Variant: Uses half-vector : More efficient and often looks better than original Phong.
Specular reflection follows Snell's law: the reflected direction is the mirror of the incident light about the normal. The intensity seen by the viewer falls off as where controls shininess. High concentrates the highlight into a tight cone — the surface appears glossy.
If with and shininess , what is the specular intensity?
The Phong Reflection Model
The Phong model combines three components:
- Ambient: Constant approximating indirect light
- Diffuse: Lambertian from surface
- Specular: Highlight
Material Properties:
- : Ambient, diffuse, specular coefficients (sum ≤ 1)
- Metals: Low diffuse, colored specular
- Plastics: High diffuse, white specular
- Matte surfaces: High diffuse, low specular
Physically-Based Alternatives:
- Cook-Torrance: Microfacet model for rough surfaces
- Oren-Nayar: Better diffuse model for rough surfaces
- Disney BRDF: Artist-friendly PBR model
Phong decomposes observed intensity as . Each term handles a different physical phenomenon: ambient fills in shadows, diffuse captures matte shading, specular adds highlights. Despite being a simplified model, Phong captures the dominant visual effects and remains widely used in real-time rendering.
A plastic sphere: , , , . With and , find total intensity.
BRDF (Bidirectional Reflectance Distribution Function)
The BRDF is a general function describing how light is reflected by a surface:
Properties:
- Reciprocity:
- Energy conservation:
- Positivity:
Common BRDFs:
- Lambertian: (constant)
- Phong: Not actually a valid BRDF (violates energy conservation)
- GGX/Trowbridge-Reitz: Modern microfacet model
Measuring BRDFs: Real materials are measured using gonioreflectometers (MERL database) or inferred from photographs under controlled lighting.
Rendering Equation: The full light transport equation uses BRDF:
The BRDF generalizes all reflectance models: it maps an incoming light direction to outgoing radiance in direction . Lambertian is (constant), Phong adds a specular lobe. Physical BRDFs satisfy reciprocity () and energy conservation ().
For a Lambertian surface with albedo , what is the BRDF value?
Theory Exercise
Problem:
A Lambertian sphere is illuminated by a distant light source from direction (directly behind the camera). The sphere has diffuse coefficient .
a) What is the intensity at the point where the surface normal is ? b) What is the intensity where (45° from light)? c) What is the intensity where (perpendicular to light)? d) Draw conclusions about how a sphere would appear.
Hints:
- For Lambertian: I = kd * (n · l)
- Dot product of unit vectors = cos(angle between them)
- cos(0°) = 1, cos(45°) ≈ 0.707, cos(90°) = 0
Related Problems on PixelBank
The reflectance model in the previous topic told us how much light leaves a surface toward the camera. This topic follows that light through the sensor and asks how it becomes the colored pixels you actually store. The surprise is that a camera does not measure color the way your eye does. Its sensor counts photons but is colorblind, so a mosaic of tiny red, green, and blue filters is laid over the pixels, and each site records just one of the three. Everything else is inference and encoding. We trace that pipeline in order. First the Bayer pattern and demosaicing, which reconstruct three colors per pixel from one measurement each. Then color spaces — RGB, HSV, YCbCr, Lab — and why segmentation and compression each prefer a different one. Grayscale conversion shows why a perceptual weighting beats a naive average. White balance removes the color cast of the light source. Finally gamma correction explains why raw pixel values are nonlinear, and why forgetting that quietly corrupts any arithmetic you do on them.
Definition
Digital cameras capture color using sensor arrays with color filters. Understanding how cameras perceive and encode color is essential for:
- Color correction: Adjusting white balance and color profiles
- Image processing: Working with different color spaces
- Computer vision: Color-based segmentation and detection
- Raw processing: Converting sensor data to viewable images
In this topic
- 1Bayer Pattern and Demosaicing
- 2Color Spaces
- 3Grayscale Conversion
- 4White Balance
- 5Gamma Correction
Bayer Pattern and Demosaicing
Bayer pattern arrangement:
A camera sensor measures light intensity but not its color, so a Bayer color filter is bonded over the pixels, letting each site see only red, green, or blue. The pattern uses 50 percent green and 25 percent each of red and blue, because vision resolves detail mostly through the green-dominated luminance channel. Demosaicing, or debayering, fills the two missing colors at every pixel by interpolating from neighbors that did record them. Simple bilinear averaging is fast but blurs edges and can produce colored fringes along sharp boundaries. Better algorithms first estimate edge direction and interpolate along it rather than across it.
The Bayer pattern samples green at 2x the rate of red and blue, matching human visual sensitivity. Each pixel records only one color, so demosaicing interpolates the missing two channels. Bilinear interpolation uses the 4-neighbor average, but edge-aware methods (adaptive homogeneity) check gradient direction first to avoid interpolating across edges, which causes color fringing.
A pixel is at a 'red' position in the Bayer pattern with 4 green neighbors (values 100, 110, 105, 95). Estimate its green value.
Color Spaces
Different color spaces serve different purposes:
RGB: Additive color model (displays, cameras)
- R + G + B = White, absence = Black
HSV/HSL: Hue, Saturation, Value/Lightness
- Intuitive for humans, useful for color selection
- Hue = color type (0-360°)
YCbCr: Luminance + Chrominance
- Used in video compression (JPEG, MPEG)
- Separates brightness from color
Lab: Perceptually uniform
- L = lightness, a = green-red, b = blue-yellow
- Equal distances = equal perceived differences
Color spaces are coordinate systems on the 3D color solid. RGB is a cube, HSV is a cylinder, and LAB is designed so Euclidean distance correlates with perceived color difference. The transform between spaces is a well-defined function — linear for RGB-to-XYZ, nonlinear for RGB-to-HSV. Choosing the right space makes your problem axis-aligned.
Why does JPEG use YCbCr instead of RGB for compression?
Grayscale Conversion
(Rec. 601 luma coefficients)
Collapsing red, green, and blue into a single brightness value seems trivial, but the obvious choice — averaging the three channels — looks wrong, because the eye is far more sensitive to green than to blue. The standard luminance formula , from the Rec. 601 standard, weights the channels by their perceived contribution to brightness: green carries most, red less, blue least. These are the same weights that form the luma row of the RGB-to-YCbCr transform used in video. Using them yields grayscale whose light-dark relationships match perception, whereas a flat average makes blues look implausibly bright and greens too dark, distorting every operation that keys off intensity.
The luminance formula is the first row of the RGB-to-YCbCr transform matrix. The weights come from the CIE 1931 color matching functions and model how human cone cells combine signals. Using equal weights ignores perceptual sensitivity and produces visually incorrect grayscale where blues appear too bright.
Pure green (0, 255, 0) vs pure blue (0, 0, 255). Which appears brighter in grayscale?
White Balance
Light sources are not neutral: incandescent bulbs glow warm and orange near 2700 K, overcast shade is cool and blue near 7000 K, so a white wall reflects a colored cast into the camera. White balance is the correction that makes surfaces we know to be white render as white again. The camera multiplies each color channel by its own gain, scaling the recorded values so a neutral reference comes out equal across red, green, and blue. Automatic methods estimate those gains via the gray-world assumption that an image's average should be neutral. Shooting raw preserves the original values so the balance can be redone later.
White balance is a per-channel diagonal scaling that normalizes the illuminant to appear white. The gray-world assumption estimates gains as , forcing each channel's mean to match the global mean. This is a first-order correction; the full chromatic adaptation (Bradford transform) is a matrix.
Under incandescent light, a white card reads (255, 200, 150) instead of (255, 255, 255). What multipliers fix this?
Gamma Correction
Pixel values are not proportional to physical light. Encoded images apply a nonlinear map, roughly value equals linear light raised to the power one over 2.2, so limited bits are spent where the eye is most sensitive — the dark tones. This originated with the response curve of CRT displays but survives because it matches human perception. The consequence trips up almost everyone: most image operations, from blending to blurring to resizing, assume light adds linearly, yet the stored values do not. The correct workflow is to linearize by removing gamma, do the arithmetic, then re-encode. Skip that and averages, filters, and blends all come out subtly wrong.
Gamma maps linear light to display values via with . The power function allocates more bits to dark tones where human perception is most sensitive (Weber's law). Forgetting to linearize before arithmetic operations causes systematic errors: averaging two gamma-encoded pixels gives the wrong result because .
An sRGB image has value 128 (mid-gray). What is the linear light value (0-1 scale)?
Theory Exercise
Problem:
An image has a pixel with RGB values (200, 100, 50).
a) Convert to grayscale using the luminance formula b) If we want to brighten this pixel by 50% in linear space, what's the correct approach? (Consider gamma) c) What would be wrong with simply multiplying the RGB values by 1.5?
Hints:
- Use weights: 0.299R + 0.587G + 0.114B
- sRGB values need to be linearized: V_linear = V^2.2
- Operations in gamma-encoded space are not physically correct
Related Problems on PixelBank
Every earlier topic in this chapter treated the image as if it already existed as a grid of pixels. This topic asks where that grid comes from, and what it costs. The world radiates a continuous field of light, but a sensor can only measure it at discrete points, and a screen can only redisplay discrete samples. Sampling is that conversion from continuous to discrete, and when it is done carelessly it fails in a spectacular and irreversible way: fine detail masquerades as coarse detail, so a striped shirt shimmers with false bands and a diagonal edge breaks into stairsteps. That failure is aliasing. We build the theory needed to prevent it. First the Nyquist-Shannon theorem, which pins down the minimum sampling rate for a given level of detail. Then aliasing itself, seen in Moire patterns and jaggies. Next the anti-aliasing strategies that blur away unrepresentable frequencies before sampling. Finally image pyramids, the multi-resolution structure that samples correctly at every scale and underpins scale-invariant feature detection across the rest of computer vision.
Definition
Sampling is the process of converting a continuous signal (like light) into discrete values (pixels). If not done correctly, aliasing occurs—high-frequency details get misrepresented as lower frequencies, causing artifacts like moiré patterns, jagged edges, and false colors.
The Nyquist-Shannon theorem tells us the minimum sampling rate needed to accurately capture a signal without aliasing.
In this topic
- 1Nyquist-Shannon Sampling Theorem
- 2Aliasing in Images
- 3Anti-Aliasing Strategies
- 4Image Pyramids
Nyquist-Shannon Sampling Theorem
Aliasing occurs when
The world radiates a continuous light field, but a sensor only measures it at discrete points, and reconstructing the original faithfully is not always possible. The Nyquist-Shannon theorem gives the condition: to capture a signal without error you must sample at more than twice its highest frequency component, so . Half the sampling rate is the Nyquist frequency, the ceiling on what the grid can represent. Anything above it does not vanish — it aliases, folding down to masquerade as a lower frequency that was never there. For images the sampling rate is the pixel density, so detail smaller than two pixels is what violates the bound.
The theorem states that a bandlimited signal with maximum frequency is perfectly recoverable from samples taken at rate . For images, this means pixel spacing must be at most where is the highest spatial frequency in the scene. Violating this creates aliasing — frequencies above fold back and masquerade as lower frequencies.
A 1000×1000 image samples a 50cm scene. What's the smallest feature it can capture without aliasing?
Aliasing in Images
Aliasing is what Nyquist violation looks like in practice: content above the Nyquist frequency does not disappear but reappears disguised as a lower frequency. In images it takes several forms. Moire patterns emerge when you photograph a regular structure — a brick wall, a fabric weave, a screen — and its fine repetition beats against the pixel grid into broad false bands. Diagonal edges break into visible stair-steps, the jaggies. In a Bayer sensor high-frequency detail can even alias between color channels, adding false color. The damage is permanent, since the true frequency can no longer be separated from its alias.
Aliased signals satisfy at all sample points when . In images, this frequency folding produces Moire patterns (on brick walls, fabric) and jagged edges (staircasing on diagonal lines). The effect is irreversible — once aliased, the original high-frequency content cannot be separated from the low-frequency alias.
Why do TV screens show rainbow patterns when photographed with a phone camera?
Anti-Aliasing Strategies
Since aliasing is caused by frequencies above Nyquist, the cure is to remove those frequencies before sampling, or to sample densely enough that they fall below the limit. Cameras add an optical low-pass filter in front of the sensor to blur away unresolvable detail, and some oversample then downscale. Graphics offers supersampling, which renders at higher resolution and averages down, multisampling, which samples only along edges, and cheaper post-process filters like FXAA that smooth detected edges. In image processing the standard move is a Gaussian blur before downsampling, plus proper interpolation. Every one of these band-limits the signal to what the target sampling rate can honestly represent.
Anti-aliasing applies a low-pass filter before sampling: . The ideal filter is a sinc function, but it has infinite support. Practical approximations include the Gaussian (smooth, fast) and Lanczos (sharper, more ringing). The filter width must match the sampling rate — downsampling by requires a filter that cuts off at of the original bandwidth.
To downsample an image by 4×, what Gaussian blur σ should be applied first?
Image Pyramids
An image pyramid is a stack of the same picture at successively coarser resolutions, built so each level is correctly band-limited and free of aliasing. A Gaussian pyramid makes each level by blurring with a Gaussian, which acts as the anti-alias filter, then downsampling by two. A Laplacian pyramid instead stores the difference between each level and the upsampled level above it, capturing band-pass detail; from those residuals the original reconstructs exactly, useful for seamless blending and compression. Because every level is a legitimately downsampled view, pyramids let algorithms search across scale, which is why scale-invariant detectors such as SIFT are built directly on top of them.
A Gaussian pyramid recursively applies blur-then-subsample: . Each level halves the resolution, giving a multi-scale representation. The Laplacian pyramid stores band-pass residuals , enabling perfect reconstruction. Scale-space theory proves that Gaussian blurring is the unique kernel that does not create spurious features at coarser scales.
A 1024×1024 image has a 4-level Gaussian pyramid. What are the level dimensions?
Theory Exercise
Problem:
A camera sensor has 4000 pixels across a 24mm sensor (typical APS-C).
a) What is the pixel pitch (distance between pixel centers)? b) According to the Nyquist theorem, what is the finest detail (in line pairs/mm) this sensor can resolve? c) If photographing a fabric with a 0.5mm stripe pattern from 1 meter away with a 50mm lens, will aliasing occur? (Hint: calculate the pattern size on the sensor)
Hints:
- Pixel pitch = sensor width / pixel count
- Nyquist limit for spatial frequency = 1 / (2 × pixel pitch)
- Magnification for thin lens: m = focal_length / distance
Related Problems on PixelBank
A pedestrian steps off a curb at night, beyond the reach of the headlights. Every topic so far in this chapter assumed the scene is lit: Lighting and Reflectance modelled light bouncing off surfaces, Color and the Digital Camera turned that light into RGB values, and Sampling and Aliasing turned it into a pixel grid. In the dark there is nothing to reflect, so a visible camera records almost nothing. Yet the pedestrian is glowing brightly the whole time, at wavelengths about twenty times longer than the eye can see.
Infrared imaging is the family of cameras and models that capture that light. We build it in the order a CV engineer meets it. First the spectrum: why near-infrared behaves like visible light while long-wave infrared does not, and which detector each band needs. Then the IR-cut filter that keeps NIR out of colour cameras by day, the day/night cameras that swing it away at night, and the RGB-IR and monochrome sensors that avoid moving parts. Then blackbody physics, which explains why warm objects emit on their own. Emissivity and reflection come next, because they decide whether a pixel is really a temperature. Then the thermal sensor pipeline, with its non-uniformity correction and 14-bit contrast mapping. Finally active near-infrared: the illuminators, structured light and time-of-flight that let phones and robots see depth.
Definition
Infrared (IR) imaging forms images from electromagnetic radiation between roughly 0.75 μm and 14 μm in wavelength. The short-wave bands (NIR, SWIR) are dominated by reflected light and behave much like visible imaging. The mid- and long-wave bands (MWIR, LWIR) are dominated by thermal emission, so a pixel encodes a mix of surface temperature, emissivity and reflected surroundings rather than reflectance alone.
In this topic
- 1The Infrared Bands and Their Detectors
- 2IR-Cut Filters: Keeping NIR Out of Colour Images
- 3Day/Night Cameras: Switching the Filter Without Losing Focus
- 4RGB-IR and Monochrome Sensors in Embedded Vision
- 5Blackbody Radiation: Planck, Wien and Stefan-Boltzmann
- 6Emissivity, Reflection and Radiometric Temperature
- 7Thermal Sensors: Microbolometers, NUC and Contrast Mapping
- 8Active NIR: Illumination, Structured Light and Time-of-Flight
The Infrared Bands and Their Detectors
Infrared is several different worlds. Near-infrared (NIR, 0.75-1.4 μm) and short-wave (SWIR, 1.4-3 μm) images are mostly reflected light. Mid-wave (MWIR, 3-5 μm) and long-wave (LWIR, 8-14 μm) images are mostly light the scene emits, in two windows where air is transparent. A photon of wavelength carries energy ( is Planck's constant, the speed of light), and a semiconductor detects it only if exceeds its bandgap , which sets the cutoff . Silicon stops near 1.1 μm, so the sensor from Color and the Digital Camera sees NIR but never heat. Glass blocks LWIR, so thermal lenses use germanium.
Compare the LWIR photon energy with the thermal energy of the detector itself. At 300 K, eV, only about a fifth of a 10 μm photon's 0.124 eV, so a narrow-gap photon detector at room temperature is flooded by thermally generated carriers; that is why photon-counting LWIR and MWIR cameras are cooled to around 77 K. The same bandgap arithmetic explains the IR-cut filter in every colour camera: the Bayer dyes are largely transparent in NIR, so without the filter all three channels pick up NIR and colours wash out. The next three concepts cover that filter, the day/night cameras that swing it away after dark, and the sensors that do without it.
Silicon has eV and InGaAs has eV. Which sensor can image a 1.55 μm laser, and can either one see the 10 μm emission from a human body?
IR-Cut Filters: Keeping NIR Out of Colour Images
The eye sees roughly 380-750 nm, but the silicon sensor from Color and the Digital Camera responds out to about 1.1 μm. Each channel value integrates the scene spectrum times the filter's transmission times the channel's quantum efficiency , the Bayer dye and silicon together. The dyes turn transparent in NIR, red first from about 700 nm and green and blue above roughly 800 nm, so without a filter every channel collects NIR. Saturation drops, hues shift, and foliage and dark fabrics, which reflect strongly in NIR, turn pinkish or grey. The IR-cut filter is a flat plate between lens and sensor that passes visible light and blocks from about 650 nm. Absorptive filters are blue optical glass that absorbs NIR: a gentle cutoff that barely changes with angle. Reflective filters are short-pass interference coatings: a sharp cutoff, reflecting NIR instead of absorbing it. That is the same hot mirror that keeps the heat of bright incandescent lamps off optics. Hybrids stack both. They matter most where colour is the product, such as video-conferencing cameras that must render skin tones accurately across a wide, low-distortion field of view.
An interference filter's edge depends on the angle at which light crosses it: , with the coating's effective index. With , a 650 nm edge moves to 643 nm at 15°, 632 nm at 25° and 616 nm at 35°. In a wide-angle lens the corner rays cross the filter steeply, so the corners lose deep red and turn cyan. This colour shading is calibrated out by the ISP's lens-shading tables, or avoided by using absorptive glass, whose cutoff barely moves with angle. That is why wide-field conferencing and phone cameras often use hybrid filters.
Through an IR-cut filter, a leaf gives . Without the filter, its strong NIR reflection adds 0.25 to R, whose dye opens earliest, and 0.15 to G and B. Compare the HSV hue and saturation, and say why white balance cannot undo the change.
Day/Night Cameras: Switching the Filter Without Losing Focus
A security camera cannot keep its IR-cut filter in all the time. At night there is little visible light, and the main source is NIR, often from the camera's own 850 or 940 nm illuminators (see Active NIR below). Day/night cameras, sold as true day/night (TDN), use a removable IR-cut filter (ICR): a small motor or latching electromagnet slides it in and out of the light path between lens and sensor. By day it is in and the image is colour. At night it swings out, so NIR and the remaining visible light reach the sensor, and the camera switches to monochrome. Under NIR the three channels respond almost alike, so colour carries no information, and dropping it also removes chroma noise. Two optical side effects come with the swap. A glass plate of thickness and index in a converging beam pushes the focus back by , so the mechanism swaps the filter for clear glass of the same thickness instead of leaving a gap. And lens glass is dispersive: focal length scales as , so NIR, where is lower, focuses further back. Day/night cameras therefore use IR-corrected lenses that bring visible and NIR to a common focus.
Deciding when to switch is a control problem. The trigger is a photodiode or the image's own mean brightness, and it needs hysteresis: switch to night below one threshold, back to day only above a higher one, after a hold time. Without it the camera oscillates. Its IR illuminator turns on, the scene brightens, the camera decides it is day and reinserts the filter, and the image goes dark again. For a vision pipeline the switch is a domain shift: colour turns to monochrome and the brightness changes abruptly, so background-subtraction models must be reset at each switch, and detectors trained only on daytime RGB tend to degrade on NIR night frames.
A 4 mm, f/2.0 BK7 singlet is focused at 550 nm () on a sensor with 2 μm pixels, behind a 0.3 mm IR-cut plate. BK7 has at 850 nm. Taking the circle of confusion as 2 pixels, the depth of focus is μm. Where does 850 nm focus, and what happens if the night mode simply removes the plate?
RGB-IR and Monochrome Sensors in Embedded Vision
Moving parts wear out, so many embedded cameras avoid the switch with a different sensor. A monochrome sensor has no colour filter array, so no light is lost to dyes, and NIR-enhanced pixels push its sensitivity further into NIR. That makes it the usual choice for low-light and NIR-lit vision such as eye tracking, gesture sensing and machine inspection. An RGB-IR sensor replaces one of the two green pixels in each 2×2 Bayer cell with an NIR pixel (4×4 layouts also exist). In place of a full IR-cut it sits behind a dual-band-pass filter that passes the visible band plus a narrow notch at the illuminator's 850 or 940 nm. Every colour pixel still sees some of that NIR, so the ISP estimates it from the neighbouring IR pixel and subtracts a calibrated fraction from each channel . One sensor then delivers colour by day, NIR by night, and both at once for driver monitoring and face unlock, where an NIR flash lights the face while the cabin video stays in colour.
The deployments come down to the same physics. Surveillance: 850 nm illuminators glow faintly red and are visible to anyone looking at the camera; 940 nm is covert, but silicon's quantum efficiency there is roughly half. Under an on-camera source a diffuse target's pixel signal falls as , so the same LEDs reach only about percent of the range. Monochrome NIR cameras still need an IR-cut by day, or sunlit NIR washes out their contrast. Automatic number-plate recognition (ANPR) finds the plate, segments the characters and reads them. Most plates are retroreflective, so an on-axis NIR flash makes the reflective ground bright and the characters dark whatever the paint colour, and a short exposure freezes motion and suppresses headlights. Plates with light characters on a dark ground invert this, so the segmenter must check text polarity first. By day, putting the IR-cut back in lets the system also report plate and vehicle colour.
In daylight an RGB-IR pixel reads , , electrons, and the neighbouring IR pixel reads . Take and shot noise only ( equals the signal). Compute the corrected values and their SNR, and compare a camera with an IR-cut filter that collects only the visible part.
Blackbody Radiation: Planck, Wien and Stefan-Boltzmann
Everything above absolute zero glows. A blackbody, an ideal absorber, emits a spectrum fixed by its temperature alone. Planck's law gives its spectral radiance , with the wavelength, the temperature in kelvin and Boltzmann's constant. The spectrum peaks at Wien's , and integrating over all wavelengths gives the emitted power per unit area, , with in SI units. Skin at 307 K peaks at 9.4 μm, inside the LWIR window, so LWIR is the default band for people and buildings, while hot engines shift toward MWIR. This emission is the term Lighting and Reflectance left out.
What a camera can resolve depends on how steeply its band radiance changes with temperature. Near 300 K the 8-14 μm band radiance rises about 1.5 percent per kelvin, slightly faster than the 1.3 percent () of total emission, while the 3-5 μm band rises about 3.6 percent per kelvin because it sits on the steep short-wavelength flank of the Planck curve, where is far below μm K. MWIR therefore gives more contrast per kelvin, but LWIR collects far more photons from room-temperature scenes. Either way the lens and housing also radiate, which is why thermal cameras are calibrated against reference blackbodies.
Where do the spectra of skin (307 K) and the Sun (5778 K) peak, and what fraction of each one's emission falls in the LWIR window (8-14 μm)?
Emissivity, Reflection and Radiometric Temperature
Treating a thermal pixel as a thermometer is the most common mistake in infrared vision. Emissivity , between 0 and 1, is the fraction of blackbody emission a surface actually radiates; for an opaque surface, Kirchhoff's law makes its reflectivity , the reflection term of Lighting and Reflectance. The camera measures : emission at plus reflected surroundings at , both scaled by atmospheric transmission , plus the air path's own glow at . Skin, paint, water and most non-metals have of 0.9-0.98 and read nearly true. Polished metals, near 0.05-0.1, act as mirrors that show their surroundings. Window glass is opaque in LWIR.
Solving for divides by , so errors in the reflected term are amplified by roughly : 0.05 for paint, 9 for polished aluminium. Concretely, misjudging the room by 1 K moves the painted pipe's corrected reading by 0.04 K but the aluminium pipe's by about 6 K. Emissivity also falls at grazing angles beyond roughly 60 degrees, so curved objects read cooler at their silhouettes. Real cameras invert a calibrated band-radiance curve instead of , but the structure, and the error amplification, is identical.
A pipe at 60 °C sits in a 20 °C room (), viewed by a camera that assumes . What does it read if the pipe is black paint () versus polished aluminium ()?
Thermal Sensors: Microbolometers, NUC and Contrast Mapping
Most thermal cameras in vision use uncooled microbolometers: each pixel is a suspended vanadium-oxide membrane whose resistance changes as absorbed LWIR warms it, read as 14-bit counts. Sensitivity is quoted as NETD, the temperature difference equal to the noise, commonly 30-60 mK. But every pixel has its own gain and offset, drifting with the camera's temperature, so raw frames show a fixed pattern stronger than the scene. Two-point non-uniformity correction (NUC) images cold and hot references and , records each pixel's raw readings and , and solves for gain and offset . It is white balance from Color and the Digital Camera, done per pixel.
After NUC a second problem appears: the 14-bit range holds 16,384 levels, but a typical scene spans a few hundred counts. Mapping the full range linearly to 8 bits squeezes 500 counts into about 8 grey levels, and min-max scaling is hijacked by one hot spot, as the coding exercise shows. Automatic gain control clips percentiles or equalizes the histogram, but it changes the temperature-to-grey mapping every frame. For detection and measurement, keep the 14-bit radiometric frames and use one fixed normalization, rather than training on AGC video.
Two pixels view uniform plates that should read 7,000 and 8,000 counts. Pixel A reads 6,900 and 7,950; pixel B reads 7,100 and 8,020. Both then view the same scene point and read 7,425 and 7,560. Correct them.
Active NIR: Illumination, Structured Light and Time-of-Flight
NIR, unlike thermal, can be lit invisibly by 850 or 940 nm LEDs and lasers that silicon still detects. That powers night CCTV, driver monitoring and depth sensors. Structured light projects a known dot pattern and triangulates depth from each dot's shift, exactly like stereo. Continuous-wave time-of-flight (ToF) modulates the light at and measures the phase shift of the return, giving distance ( is the speed of light). Because phase wraps at , anything beyond folds back to a nearer range, the aliasing of Sampling and Aliasing. Sunlight's NIR swamps both methods outdoors; 940 nm helps because water vapour absorbs sunlight there.
Both the range and the depth noise scale as : . Multi-frequency unwrapping escapes the trade-off, because two frequencies agree only at multiples of their greatest common divisor; 80 and 100 MHz together unwrap to the 7.5 m range of 20 MHz while keeping 100 MHz precision. Two failure modes remain. Multipath, light bouncing off a second surface before returning, arrives late and bows depth outward in corners. Returned power also falls with the square of distance, so dark and distant surfaces are noisy.
A ToF camera modulates at 20 MHz. What is its unambiguous range, what distance does a measured phase of mean, and where does a wall at 9 m appear?
Code Examples
Why day/night lenses must be IR-corrected
import numpy as np
# Sellmeier coefficients for Schott N-BK7 (wavelength in um)
B = (1.03961212, 0.231792344, 1.01046945)
C = (0.00600069867, 0.0200179144, 103.560653)
def n_bk7(lam_um):
l2 = lam_um ** 2
return np.sqrt(1 + sum(b * l2 / (l2 - c) for b, c in zip(B, C)))
f_design, N, pixel = 4.0, 2.0, 2.0e-3 # 4 mm f/2.0 singlet focused at 550 nm, 2 um pixels (mm)
n0 = n_bk7(0.55)
dof = 2 * N * pixel # +- N*c with a circle of confusion c of 2 pixels
for lam in [0.45, 0.65, 0.85, 0.94]:
dz = f_design * (n0 - 1) / (n_bk7(lam) - 1) - f_design
blur_px = abs(dz) / N / pixel
print(f"{lam*1000:4.0f} nm: n={n_bk7(lam):.4f} focus shift {dz*1000:+6.1f} um, blur {blur_px:4.1f} px (DOF +-{dof*1000:.0f} um)")
t = 0.3 # IR-cut plate thickness, mm
print(f"removing a {t} mm plate moves focus {t * (1 - 1 / n0) * 1000:.1f} um toward the lens")
Uses the Sellmeier equation for BK7 to find where a 4 mm f/2.0 singlet, focused at 550 nm, brings other wavelengths to focus. 850 nm lands 68 um behind the sensor (a 17-pixel blur against a depth of focus of +-8 um) and 940 nm 80 um behind it. The singlet is also badly out of focus across the visible band (-52 um at 450 nm), which is why real lenses are achromats; an achromat fixes the visible spread, but NIR still needs explicit correction. Removing a 0.3 mm IR-cut plate shifts the focus another 102 um, which is why day/night switchers swap in clear glass of equal thickness.
Where blackbody energy lands: skin, a room and the Sun
import numpy as np
h, c, k = 6.626e-34, 2.998e8, 1.381e-23
sigma = 5.670e-8
def planck(lam, T):
# spectral radiance, W / (m^2 sr m)
return 2 * h * c**2 / lam**5 / np.expm1(h * c / (lam * k * T))
lam = np.linspace(0.2e-6, 200e-6, 400_000)
for name, T in [("skin", 307), ("room", 293), ("sun", 5778)]:
L = planck(lam, T)
total = np.trapezoid(L, lam)
def frac(a, b):
m = (lam >= a * 1e-6) & (lam <= b * 1e-6)
return np.trapezoid(L[m], lam[m]) / total
peak = lam[np.argmax(L)] * 1e6
print(f"{name:5s} T={T}K peak={peak:.2f}um "
f"visible={frac(0.4, 0.7):.4f} MWIR={frac(3, 5):.4f} LWIR={frac(8, 14):.4f}")
Integrates Planck's law across each band. Skin at 307 K peaks at 9.44 um and puts 38 percent of its emission into 8-14 um, 1.5 percent into 3-5 um and none into the visible band. The Sun peaks at 0.50 um with 37 percent in the visible band and only 0.1 percent in LWIR, which is why daytime LWIR images are dominated by emission, not reflected sunlight.
Why a hot metal pipe looks cold
import numpy as np
sigma = 5.670e-8
to_K = lambda C: C + 273.15
def apparent_temp(T_obj_C, eps, T_refl_C):
# what a camera that assumes eps = 1 reports
W = eps * sigma * to_K(T_obj_C)**4 + (1 - eps) * sigma * to_K(T_refl_C)**4
return (W / sigma) ** 0.25 - 273.15
def true_temp(T_app_C, eps, T_refl_C):
# invert the measurement once eps and the reflected temperature are known
W = sigma * to_K(T_app_C)**4
return ((W - (1 - eps) * sigma * to_K(T_refl_C)**4) / (eps * sigma)) ** 0.25 - 273.15
for surface, eps in [("black paint", 0.95), ("oxidised steel", 0.80), ("polished aluminium", 0.10)]:
app = apparent_temp(60.0, eps, 20.0)
print(f"{surface:18s} eps={eps:.2f} camera reads {app:5.1f} C, corrected {true_temp(app, eps, 20.0):5.1f} C")
A 60 C pipe in a 20 C room, read by a camera that assumes emissivity 1. Black paint reads 58.3 C, oxidised steel 53.1 C and polished aluminium only 24.8 C. Inverting the measurement with the correct emissivity and reflected temperature recovers 60.0 C in every case.
Theory Exercise
Problem:
A pedestrian-detection rig mounts an RGB camera and an LWIR camera side by side with a 5 cm baseline. Both are resampled to 640 pixels wide with a 32° horizontal field of view. You align the two images with a single homography fitted on a calibration target at 10 m.
a) What is the focal length in pixels? b) What misalignment remains for a pedestrian at 2 m and at 20 m? c) Why does an ordinary printed checkerboard fail as the calibration target, and how would you fix the rig?
Hints:
- Use $f = (W/2)/\tan(\text{FOV}/2)$.
- Disparity is $f b / Z$. A homography fitted at one depth removes exactly that depth's disparity.
- A calibration target must show contrast in both bands.
Coding Exercise
Problem:
Simulate a 160 x 120 microbolometer with per-pixel gain (mean 1, std 0.05) and offset (std 150 counts) plus read noise. Calibrate a two-point NUC from uniform 7,000- and 8,000-count reference frames, then image a scene with a 7,400-count background, a 7,900-count person and a tiny 12,000-count hot spot. Print the background standard deviation before and after NUC, then convert the corrected frame to 8 bits with min-max scaling and with 1st-99th percentile clipping, and print the person-versus-background grey-level gap for each.
Hints:
- Per pixel, the gain is (Y_h - Y_c) divided by (hot reading - cold reading), and the offset is Y_c minus gain times the cold reading.
- Measure fixed-pattern noise as the standard deviation over a patch that contains only background.
- np.percentile(img, [1, 99]) gives clip limits that ignore a handful of extreme pixels.