Unit 1: Foundations of Computer Vision and Deep Learning
1. Introduction to Computer Vision and the Deep Learning Paradigm
1.1 The Nature and Scope of Computer Vision
Computer Vision (CV) is the interdisciplinary field of artificial intelligence and computer science focused on developing mathematical models and computational algorithms that enable digital systems to extract high-level, meaningful, and actionable insights from multidimensional visual data (images and video streams).
- Core Objective: Map an input visual signal to a structured semantic output , which may range from discrete categorical labels (image classification) to spatial coordinates (object localization and bounding box detection), pixel-dense label arrays (semantic and instance segmentation), or high-dimensional synthesized images (generative modeling).
- Inherent Challenges:
- Semantic Gap: The profound conceptual disparity between low-level numerical pixel values (e.g., integer intensity arrays ) and the rich semantic interpretation humans naturally perceive (e.g., distinguishing a domestic cat from a dog).
- Viewpoint Variation: Rotations, translations, and perspective transformations drastically alter individual pixel coordinates while preserving underlying semantic identity.
- Illumination Changes: Variations in scene lighting (specular reflections, shadows, color temperature) alter absolute pixel values across orders of magnitude.
- Deformation and Scale: Non-rigid bodies (animals, clothing) change shape dynamically, and subjects appear at wildly differing spatial scales depending on camera proximity.
- Occlusion and Background Clutter: Objects are frequently partially obscured by foreground obstacles or blend into visually intricate surroundings.
1.2 The Paradigm Shift: Hand-Crafted Features vs. Learned Representations
Historically, classical computer vision relied on a two-stage pipeline:
- Manual Feature Engineering: Domain experts designed heuristic feature extractors to detect localized geometric or statistical primitives invariant to specific photometric and geometric perturbations:
- SIFT (Scale-Invariant Feature Transform): Uses Difference-of-Gaussians (DoG) scale-space pyramids to identify scale-invariant keypoints, computing gradient orientation histograms within local patches.
- SURF (Speeded-Up Robust Features): Accelerates scale-space detection using box filters and integral images.
- HOG (Histogram of Oriented Gradients): Evaluates normalized local histograms of image gradient orientations in dense grids, widely adopted for human pedestrian detection.
- Haar-like Features & AdaBoost: Integral-image box difference filters used in real-time face detection cascades (Viola-Jones).
- Shallow Machine Learning Classifiers: The extracted feature descriptors were aggregated (e.g., Bag-of-Visual-Words) and fed into classical classifiers such as Support Vector Machines (SVM) or Random Forests.
- The Modern Deep Learning Shift:
Beginning with AlexNet in the 2012 ImageNet challenge, End-to-End Deep Learning superseded manual feature design. Neural networks optimize continuous parameterized functions that learn hierarchical visual representations directly from raw pixel arrays through gradient descent:- Low-Level Layers: Learn universal spatial primitives (Gabor-like edge detectors, color gradients, corners).
- Mid-Level Layers: Synthesize edges into textures, motifs, contours, and object parts.
- High-Level Layers: Compose parts into holistic semantic object classes and scene abstractions.
2. Digital Image Formation, Representation, and Color Spaces
2.1 From Continuous Light to Numerical Tensors
Visual imaging begins with electromagnetic radiation reflecting off physical surfaces. An optical lens focuses incident light onto a photosensitive sensor array (CCD or CMOS):
- Spatial Sampling: Discretizes the continuous spatial domain into a regular two-dimensional grid of finite picture elements (pixels) of size .
- Quantization: Converts the continuous analog electrical charge accumulated per sensor photodiode into a discrete numerical integer level. In standard 8-bit unsigned integer encoding (
uint8), the continuous radiometric luminance is mapped to discrete levels: .
Tensor Formats in Deep Learning Frameworks
In deep learning frameworks, image collections are organized as 4-dimensional numerical tensors:
- NCHW Format (Channels-First): Shape
(Batch_Size, Channels, Height, Width). Default format for PyTorch and NVIDIA cuDNN, maximizing memory cache spatial locality during matrix convolution routines. - NHWC Format (Channels-Last): Shape
(Batch_Size, Height, Width, Channels). Default format for TensorFlow/Keras and standard image processing libraries (OpenCV, PIL).
2.2 Color Spaces and Representations
- Grayscale (Single Channel): Represents monochrome intensity . Standard weighted luminance conversion from linear RGB follows ITU-R Recommendation BT.601:
(Reflecting the human eye's peak photoreceptor sensitivity to green wavelengths). - RGB Color Space: An additive color model where red, green, and blue primary wavelengths combine to produce any visible color. Each pixel is a vector . While intuitive for display hardware, RGB channels are highly correlated, meaning illumination changes affect all three channels simultaneously.
- HSV / HSL Color Space:
- Hue (): Identifies the dominant spectral wavelength (color tint).
- Saturation (): Denotes color purity or vibrancy (distance from neutral gray).
- Value (): Represents overall brightness or intensity.
- Advantage: Separates chromaticity (Hue and Saturation) from luminance (Value), allowing color-based thresholding and tracking invariant to lighting shifts.
- and LAB Spaces:
- : Used in JPEG compression and digital broadcasting; isolates luma () from blue-difference chroma () and red-difference chroma (), facilitating chroma subsampling (e.g., 4:2:0).
- CIE : Perceptually uniform color space where Euclidean distances directly correspond to perceived perceptual color differences.
3. Image Preprocessing, Scaling, and Augmentation Pipelines
3.1 Geometric Transformations and Spatial Interpolation
Deep neural networks require fixed-dimension tensor inputs across mini-batches. Converting raw, arbitrarily sized images requires spatial resizing governed by interpolation algorithms:
- Nearest-Neighbor Interpolation: Assigns each output pixel the intensity of the nearest input coordinate. Extremely fast (), but produces severe blocky pixelation and jagged staircase artifacts.
- Bilinear Interpolation: Computes an intensity value using a distance-weighted linear combination of the nearest neighborhood pixels:
Provides smooth edge transitions with low computational cost; default for standard vision networks. - Bicubic Interpolation: Uses a cubic spline weighting over a pixel neighborhood. Preserves high-frequency details and fine textures, widely utilized in super-resolution preprocessing.
3.2 Radiometric Normalization and Standardization
Raw integer pixel inputs in present severe optimization challenges for gradient descent: large input magnitudes create steep, ill-conditioned loss surfaces, causing saturated activations or exploding gradients.
Min-Max Rescaling
Linearly scales values into a normalized floating-point range:
Channel-Wise Z-Score Standardization
Transforms the data to have zero mean () and unit variance () per color channel:
For models pretrained on ImageNet:
Standardization centers the optimization landscape around the origin, accelerating gradient descent convergence and mitigating internal covariate shift.
3.3 Data Augmentation Strategies
Data augmentation artificially expands the effective size and diversity of training datasets to prevent overfitting and enforce geometric and photometric invariance:
- Spatial / Geometric Augmentations: Random horizontal flipping (), random affine scaling, random rotations (), random cropping (e.g., RandomResizedCrop to ), and perspective distortion.
- Photometric / Color Augmentations: Color jitter (randomly altering brightness, contrast, saturation, and hue by ), random grayscale conversion, Gaussian blur, and motion blur.
- Advanced Compositional Augmentations:
- Cutout: Randomly zeros out square rectangular regions, forcing networks to utilize diverse context rather than relying on isolated visual features.
- MixUp: Generates synthetic training samples by linearly interpolating both images and their one-hot target labels:
- CutMix: Replaces a randomly cut-out bounding patch of image with the corresponding patch from , mixing class labels proportional to patch area.
4. Feedforward Neural Networks and the Multilayer Perceptron (MLP)
4.1 Biological Inspiration to Artificial Neurons
The fundamental computational unit of deep learning is the artificial neuron (perceptual unit), which computes a linear combination of its -dimensional input vector weighted by learnable parameters and an additive scalar bias , followed by an activation function :
Matrix Formulation of a Fully Connected Layer
For an input vector mapped to an output layer of dimension :
where is the weight matrix and is the bias vector.
In mini-batch matrix form with batch size ():
4.2 Why Flat MLPs Fail on High-Dimensional Image Data
Attempting to process raw digital images directly with Multilayer Perceptrons (MLPs) suffers from three catastrophic structural limitations:
- Destruction of 2D Spatial Locality: Flattening an image tensor into a 1D vector of length discards spatial neighborhood topology. Pixels that were directly adjacent vertically are separated by elements in the flattened vector.
- Exploding Parameter Complexity: A modest RGB image produces an input vector of length . Connecting this input to a single hidden layer of neurons requires:
This causes extreme memory consumption, slow computation, and massive overfitting. - Lack of Translation Invariance: In an MLP, each weight connects to a fixed pixel coordinate. If an object shifts by even a few pixels, its values activate completely different weights, preventing the network from recognizing objects across different positions without millions of redundant training examples.
(This structural inadequacy motivated the creation of Convolutional Neural Networks, which enforce weight sharing and local receptive fields).
5. Non-Linear Activation Functions and Gradient Dynamics
5.1 The Mathematical Necessity of Non-Linearity
If all activation functions in a deep neural network are linear identity mappings (), a multi-layer composition of layers:
collapses algebraically into a single affine transformation:
Regardless of depth, an un-activated network cannot represent non-linear decision boundaries or solve problems as simple as XOR. Non-linear activations empower networks to act as Universal Function Approximators.
5.2 Comparative Analysis of Activation Functions
1. Sigmoid (Logistic Function)
- Output Range: — naturally interprets activations as probabilities for binary classification.
- Critical Flaws:
- Vanishing Gradients: The derivative has a maximum value of at and rapidly approaches for . In deep networks, multiplying these fractional derivatives through backpropagation causes gradients at earlier layers to shrink exponentially to zero.
- Non-Zero Centered Outputs: Since , all inputs to downstream layers are strictly positive, causing weight gradients during backpropagation to take either all-positive or all-negative steps (zigzagging optimization dynamics).
2. Hyperbolic Tangent (Tanh)
- Output Range: — zero-centered, mitigating the zigzag gradient dynamics of Sigmoid.
- Limitation: Still suffers from vanishing gradients when saturated ().
3. Rectified Linear Unit (ReLU)
- Advantages:
- Constant gradient of for all positive inputs (), eliminating the vanishing gradient problem along active paths.
- Fast computation: evaluated with a simple hardware threshold comparison.
- Enforces biological sparsity: roughly of neurons produce zero activations.
- The Dying ReLU Problem: If a large gradient updates weights such that a neuron outputs for all training inputs, its gradient becomes permanently , leaving the neuron inactive for the rest of training.
4. Leaky ReLU and Parametric ReLU (PReLU)
- Fixes the dying ReLU issue by assigning a small non-zero slope () to negative inputs.
- In PReLU, is treated as a learnable parameter updated via backpropagation.
5. Exponential Linear Unit (ELU) & Gaussian Error Linear Unit (GELU)
- ELU: Smooths negative inputs using for , bringing mean unit activations closer to zero.
- GELU: Weights inputs by their cumulative probability under a normal distribution: . Standard activation for modern Vision Transformers (ViT) and state-of-the-art vision models.
6. Softmax Activation (Multi-Class Probability Distribution)
For a vector of unnormalized logits :
- Maps arbitrary real logits into a normalized categorical probability distribution: with all values .
6. Loss Functions, Optimization, and Generalization
6.1 Loss Functions for Computer Vision
1. Mean Squared Error (MSE / Loss)
- Used primarily in continuous regression tasks: bounding box coordinate regression, keypoint estimation, and autoencoder reconstruction. Heavily penalizes large outlier errors due to quadratic squaring.
2. Smooth Loss (Huber Loss)
- Combines the smooth behavior of near zero with the outlier robustness of for large errors; standard loss in object detection systems (Fast R-CNN, Faster R-CNN).
3. Binary Cross-Entropy (BCE Loss)
- Standard for binary classification and multi-label classification tasks.
4. Categorical Cross-Entropy Loss (Softmax Loss)
For mutually exclusive multi-class classification with classes and one-hot target vector :
- Gradient with respect to logit :
Yields an intuitive error signal: the gradient is the difference between predicted probability and ground-truth indicator.
6.2 Backpropagation and Optimization Dynamics
Backpropagation via the Multivariate Chain Rule
Backpropagation recursively calculates gradients of scalar loss with respect to all network weights by traversing the computational graph in reverse (Reverse-Mode Automatic Differentiation):
where the upstream error delta satisfies:
Gradient Descent Optimization Algorithms
- Stochastic Gradient Descent (SGD) with Momentum:
Accumulates velocity in directions of consistent gradients, dampening high-frequency oscillations across steep ravine loss surfaces. - RMSprop:
Maintains an exponentially decaying average of squared gradients and updates parameters by , providing adaptive per-parameter learning rates. - Adam (Adaptive Moment Estimation):
Combines momentum (first moment ) and RMSprop (second moment ) with bias correction:
- AdamW (Decoupled Weight Decay):
Applies weight decay directly to weights rather than mixing it into the gradient moments, preventing regularization distortion in adaptive optimizers.
6.3 Regularization and Evaluation Metrics
- Regularization (Weight Decay): Penalizes large weights by adding to the loss, driving weights closer to zero and smoothing decision surfaces.
- Dropout: Randomly deactivates neurons with probability during each training forward pass, preventing co-adaptation and approximating an ensemble of exponentially many sub-networks.
- Core Vision Evaluation Metrics: