Computer Vision
A complete guide to Computer Vision: digital pixels, Convolutional Neural Networks (CNNs), kernels, pooling, and the visual taxonomy (Classification, Object Detection YOLO, Semantic Segmentation).
When you look at a photo of a puppy running across a green lawn, understanding the scene feels effortless. In a fraction of a second, your eyes and visual cortex recognize the dog's floppy ears, bright eyes, golden coat, and the grass beneath its paws. Even if the puppy turns around, steps into a shadow, or runs behind a garden bench, you still recognize it immediately. Now, how does a digital computer see that same photo? The computer has no eyes, retina, or biological visual memory. To a computer, an image is simply a grid of numbers: a multi-dimensional array of integers between 0 and 255 representing the brightness of Red, Green, and Blue (RGB) light for every single pixel. If the puppy takes two steps to the left, every single pixel value in that grid changes. If a computer relied on fixed pixel positions, it would fail completely. Computer Vision (CV) is the science of turning these raw grids of pixel values into meaningful visual understanding: teaching computers to see, recognize, locate, and track objects in images and real-time video just like human vision.
Definition
Computer Vision is a field of artificial intelligence and digital image processing that builds algorithms and deep learning models to extract semantic understanding, spatial structure, and actionable insights from digital images and video streams.
Why It Matters
Visual perception is essential for interacting with the physical world. Autonomous and automated systems depend on vision across many industries: • Self-driving cars rely on cameras to detect lane markers, pedestrians, cyclists, and traffic signals in real time. • Radiologists use computer vision tools to spot subtle anomalies and tumors on medical scans. • Manufacturing plants use high-speed optical inspection to detect microscopic flaws on circuit boards. Computer Vision provides the visual perception needed for modern robotics, healthcare devices, security tools, and spatial computing headsets.
How It Works
Let us examine how computers store images and how Convolutional Neural Networks (CNNs) process them: 1. How Digital Images Are Stored: An image is stored as a 3D array of dimensions $(Height \times Width \times Channels)$: • Grayscale Images: A 2D grid of shape $(H, W)$ where each pixel is an integer from 0 (black) to 255 (white). • Color RGB Images: A 3D tensor of shape $(H, W, 3)$ with separate channels for Red, Green, and Blue. • A standard smartphone photo can easily contain tens of millions of numerical values. 2. Why Traditional Dense Networks Struggle with Images: • Too Many Parameters: If you flatten a 1,000x1,000 color image into a single input vector, you get 3,000,000 numbers. Connecting that to 1,000 hidden neurons would require 3 billion weights in the first layer alone, making the model slow and prone to overfitting. • Sensitivity to Object Position: If an object shifts from the top-left corner to the bottom-right, a fully connected network treats the new pixels as completely unfamiliar inputs. 3. The Convolutional Neural Network (CNN) Approach: Inspired by how biological visual systems process spatial information, CNNs use three core concepts: • The Convolution Operation: A small matrix called a Filter or Kernel (such as $3 \times 3$ pixels) slides across the image, computing dot products at each step to produce a Feature Map. - A filter designed to detect vertical edges will find vertical edges wherever they occur in the photo, giving the model Spatial Translation Invariance. • Stride and Padding: - Stride: The number of pixels the filter shifts at each step (stride of 1 moves one pixel at a time; stride of 2 halves the dimensions). - Padding: Adding a border of zeros around the image so the filter can scan edge pixels without shrinking the feature map. • Pooling Layers (Downsampling): - Max Pooling ($2 \times 2$): Slides across the feature map and keeps the highest value in each window. This halves spatial dimensions, lowers compute demands, and makes the model less sensitive to small shifts. 4. The Main Computer Vision Tasks: • Image Classification: What is in this picture? Outputs a single class label, such as 'Cat'. • Object Detection: What is in the picture and where is it located? Outputs class labels and bounding box coordinates: ['Pedestrian' at (x, y, w, h)]. A widely used framework is YOLO (You Only Look Once). • Semantic Segmentation: Labels every single pixel in the image by class (for example, road pixels in green, vehicle pixels in blue, and sky in gray). A common architecture is U-Net. • Instance Segmentation: Separates different individual instances within the same class (such as distinguishing between Car 1 and Car 2). A common model is Mask R-CNN.
Convolutional Neural Network (CNN) Visual Hierarchy
Key Points
- Computers interpret images as 2D or 3D matrices of numerical pixel intensities.
- Convolutional Neural Networks (CNNs) reduce parameter counts and provide spatial translation invariance.
- Kernels slide across images to extract feature maps representing edges, textures, and shapes.
- Max Pooling downsamples feature maps while preserving the strongest activations.
- Core computer vision tasks include Image Classification, Object Detection (YOLO), and Segmentation (U-Net).
Steps
Image Preprocessing & Normalization
Resize images to uniform dimensions (such as 224x224). Scale pixel values from [0, 255] down to [0.0, 1.0] or standardize using benchmark dataset means and standard deviations.
Apply Data Augmentation
Expand dataset variety and curb overfitting by adding random horizontal flips, small rotations (-15° to +15°), brightness adjustments, and crops.
Choose Backbone Architecture
For mobile or embedded hardware, use lightweight backbones like MobileNet. For general production workloads, use ResNet-50. For top accuracy benchmarks, consider Vision Transformers (ViT) or ConvNeXt.
Select Task-Specific Prediction Head
Attach a Softmax classification head for category labeling, bounding box regressors for YOLO object detection, or transposed convolution decoders for segmentation.
Quantization and Edge Optimization
Quantize model weights from FP32 to INT8 using tools like TensorRT or ONNX Runtime to support fast real-time inference on cameras, drones, or phones.
Formula
2D Discrete Cross-Correlation / Convolution:
(I * K)(i, j) = \sum_{m} \sum_{n} I(i + m, j + n) K(m, n)
Convolution Layer Output Dimension Formula:
O = \left\lfloor \frac{W - K + 2P}{S} \right\rfloor + 1
where W is input spatial dimension, K is kernel size, P is padding, and S is stride.
Intersection over Union (IoU) for Object Detection:
\text{IoU} = \frac{\text{Area of Overlap}}{\text{Area of Union}} = \frac{|B_p \cap B_{gt}|}{|B_p \cup B_{gt}|}Examples
The Sobel Edge Detection Filter
A standard 3x3 filter: `[[-1, 0, +1], [-2, 0, +2], [-1, 0, +1]]`. When applied across an image, it calculates horizontal changes in brightness, turning a photo into a clear outline of vertical edges.
Real-Time Object Detection in Autonomous Vehicles
An autonomous vehicle processes camera frames with YOLO in about 12 milliseconds. The single detector outputs bounding boxes labeled with detected items: 'Car' (99%), 'Truck' (95%), 'Speed Limit Sign' (98%), and 'Pedestrian' (91%).
Real-World Examples
Camera-Based Vision in Autonomous Vehicles
Some modern autonomous driving architectures use synchronized optical camera feeds without relying on radar. Deep neural networks fuse video streams into a unified 3D spatial occupancy grid in real time, tracking road boundaries, vehicles, and pedestrians 360 degrees around the car.
Automated Inspection in Semiconductor Manufacturing
Chip makers produce silicon wafers with billions of microscopic transistors. High-resolution electron microscope cameras stream images to convolutional vision models, catching microscopic manufacturing defects in fractions of a second.
Technical Examples
import torch
import torch.nn as nn
class SimpleCNN(nn.Module):
"""Convolutional Neural Network for Image Classification (e.g., CIFAR-10)"""
def __init__(self, num_classes=10):
super(SimpleCNN, self).__init__()
# Feature Extraction Backbone
self.features = nn.Sequential(
# Block 1: Input 3 channels -> 16 filters, 3x3 kernel, padding=1
nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2), # Halves dimensions: 32x32 -> 16x16
# Block 2: 16 channels -> 32 filters, 3x3 kernel, padding=1
nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2) # Halves dimensions: 16x16 -> 8x8
)
# Classification Head
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(32 * 8 * 8, 64),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(64, num_classes)
)
def forward(self, x):
features = self.features(x)
logits = self.classifier(features)
return logits
# Instantiate CNN
model = SimpleCNN(num_classes=10)
dummy_batch = torch.randn(4, 3, 32, 32) # 4 color images of size 32x32
logits = model(dummy_batch)
print("Input Batch Shape: ", dummy_batch.shape)
print("Output Logits Shape:", logits.shape) # Shape: [4, 10] class predictionsImage Classification vs Object Detection (e.g., YOLO)
| Aspect | Image Classification | Object Detection (e.g., YOLO) |
|---|---|---|
| Primary Goal | Identifies what is in the image (one overall class label) | Identifies what is in the image AND where each object is located |
| Output Format | A single class label and confidence score: 'Dog (98%)' | A list of bounding boxes: `[class, confidence, x_min, y_min, x_max, y_max]` |
| Number of Objects | Assumes one primary subject per image | Finds and separates multiple overlapping objects in a single image |
| Evaluation Metric | Top-1 Accuracy, Top-5 Accuracy, F1-Score | Mean Average Precision (mAP) across Intersection over Union (IoU) thresholds |
| Common Applications | Photo categorization, medical scan triage | Autonomous driving, security camera monitoring, retail checkout |
Residual Skip Connections (ResNet) & The Degradation Problem
Convolutional Networks (CNN) vs Vision Transformers (ViT)
Advantages
- Parameter sharing keeps model sizes manageable compared to fully connected layers.
- Translation invariance allows models to identify objects regardless of where they appear.
- Capable of processing high-resolution video streams in real time on modern hardware.
- Powers key automated systems including medical imaging, autonomous vehicles, and robotics.
Limitations
- Requires large volumes of labeled training data and strong data augmentation.
- Can be fooled by adversarial noise patterns that are imperceptible to human eyes.
- Visual performance can drop in poor conditions like heavy rain, glare, or darkness.
- Multi-camera, high-resolution video processing requires substantial compute resources.
Interview Questions
What are the two key mathematical properties of Convolutional Layers that make them superior to Dense Layers for images?
The two main properties are: 1) Parameter Sharing (Weight Sharing): the same small filter kernel (such as $3 \times 3$) is reused across the entire image. When a filter learns to spot an edge, it spots that edge everywhere without needing unique weights for each pixel location, keeping parameter counts low; and 2) Local Receptive Fields (Sparsity of Connections): each neuron in a convolutional layer connects only to a small neighborhood of adjacent pixels rather than the whole image at once. This aligns with natural images, where nearby pixels are strongly correlated while distant pixels are mostly independent.
Explain what Intersection over Union (IoU) is and how it is used in Object Detection.
Intersection over Union (IoU) measures how much a predicted bounding box ($B_p$) overlaps with the actual ground-truth box ($B_{gt}$): $\text{IoU} = \frac{\text{Area}(B_p \cap B_{gt})}{\text{Area}(B_p \cup B_{gt})}$. A score of 1.0 means perfect alignment, while 0 means no overlap at all. In benchmark evaluations like COCO, a prediction is considered correct only if the class matches and the IoU is above a threshold, such as 0.50. During inference, IoU is also used in Non-Maximum Suppression (NMS) to remove duplicate overlapping boxes around the same object.
Practice Questions
- Given an input image of size $28 \times 28 \times 1$, a convolution layer with 16 filters of size $3 \times 3$, stride 1, and no padding, calculate the exact spatial dimensions of the output feature map.
- Explain how Non-Maximum Suppression (NMS) cleans up multiple overlapping bounding boxes in object detection.
