Computer Vision & Convolutional Neural Networks
Learn how models convert pixels into edges, textures, objects and decisions. Calculate convolutions, trace spatial shapes and build the practical reasoning required for image classification, detection and segmentation.
ฮฃ patch ร weightHout = โ(H + 2P โ K) / Sโ + 1By the End of This Level, You Can
Six Building Blocks of Visual Learning
A computer does not see an object directly; it receives a structured tensor of measured intensities.
A grayscale pixel is one value; an RGB pixel contains three channel values.
The same learned weights slide across locations to detect local visual evidence.
Each output cell records how strongly one filter matches one receptive region.
Early channels may encode colour or edges; deeper channels encode learned patterns.
Depth, kernel size and stride determine how much context a feature can use.
A head converts learned features into classes, boxes, masks or embeddings.
Images Are Structured Tensors
Unlike a flat table row, an image preserves neighbourhood, direction and scale.
From Scene to Numbers
A digital image samples light on a rectangular grid. In machine learning, a batch is commonly represented as N ร C ร H ร W: number of images, channels, height and width. Libraries may also store images as H ร W ร C, so shape awareness is essential.
- Grayscale: one intensity channel.
- RGB: red, green and blue channels.
- Normalization: rescales values or standardizes each channel.
- Resolution: controls detail, computation and memory.
A batch of 32 RGB images sized 224ร224 has shape 32ร3ร224ร224 and contains 4,816,896 scalar values.
Always explain channel order and preprocessing when debugging a vision pipeline.
Resizing changes the measured signal; it is not merely a display operation.
Convolution: Local Connectivity with Shared Weights
A filter calculates the same local dot product at every valid spatial position.
How a Feature Map Is Calculated
Place the kernel over an image patch, multiply aligned entries, add the products and bias, then move the kernel. Weight sharing makes convolution far more parameter-efficient than connecting every pixel to every output neuron.
Y[i,j] = b + ฮฃu ฮฃv X[i+u,j+v]K[u,v]
- Kernel size: local field inspected in one operation.
- Stride: number of pixels moved between outputs.
- Padding: values added around borders.
- Dilation: spacing between kernel elements.
A 5ร5 input with a 3ร3 kernel, stride 1 and no padding produces a 3ร3 feature map.
Derive output height and width before writing a CNN architecture.
CNN libraries usually implement cross-correlation without flipping the kernel, although the operation is conventionally called convolution.
๐ Convolution & Feature-Map Workbench
Run a real two-dimensional convolution. Change the image, kernel, stride and padding; then follow every patch multiplication and compare the complete output map.
Activation, Pooling and Spatial Hierarchy
CNN blocks progressively transform raw local evidence into useful task features.
Why Convolution Alone Is Not Enough
Convolution is linear. Nonlinear activations allow layered feature composition, while pooling or strided convolution reduces spatial size and increases effective context. Modern networks often preserve more spatial detail early and reduce it deliberately later.
- ReLU: clips negative responses and introduces nonlinearity.
- Max pooling: keeps the strongest value in each window.
- Average pooling: summarizes the regional mean.
- Global average pooling: converts each final feature map into one number.
2ร2 pooling with stride 2 converts a 28ร28 feature map into 14ร14.
Discuss the trade-off between invariance, computation and localization detail.
Pooling is not automatically beneficial; excessive downsampling destroys small-object information.
CNN Shapes, Parameters and Receptive Fields
Architecture quality depends on tracking both representation size and contextual reach.
Three Calculations for Every Layer
For each convolution, calculate output shape, trainable parameters and receptive field. A standard convolution with Cin input channels, Cout filters and a KรK kernel contains (KยฒCin + 1)Cout parameters when each filter has a bias.
- Output size: depends on input, padding, dilation, kernel and stride.
- Parameters: depend on channels and kernelโnot image width and height.
- Receptive field: grows across stacked operations.
- Activation memory: often dominates training memory for large batches.
A 3ร3 convolution from 3 to 32 channels has (3ร3ร3+1)ร32 = 896 parameters.
Shape and parameter-count questions are common screening and interview tasks.
More parameters do not necessarily mean a larger receptive field.
๐๏ธ CNN Shape, Parameter & Receptive-Field Laboratory
Propagate a real image tensor through a selected architecture. Inspect output dimensions, parameter counts, activation size and receptive field at every layer.
Augmentation and Transfer Learning
Good vision performance depends as much on data and initialization as architecture.
Learn the Right Invariances
Augmentation generates plausible training variations such as crops, flips, colour shifts or rotations. Transformations must preserve the label and update boxes or masks consistently. Transfer learning starts from features learned on a larger source dataset and adapts them to the target problem.
- Feature extraction: freeze the backbone and train a new task head.
- Fine-tuning: update some or all pretrained layers using a smaller learning rate.
- Domain shift: source and target images may have different visual statistics.
- Leakage safety: split related patients, videos or objects before augmentation.
A horizontal flip is valid for many animals but may be invalid for text or asymmetric medical anatomy.
Explain when to freeze, partially unfreeze and fully fine-tune a pretrained model.
More augmentation is not always better; unrealistic transformations teach the wrong invariances.
Classification, Detection and Segmentation
The output representation and evaluation metric must match the visual task.
Three Different Prediction Contracts
- Classification: one or more labels for the complete image.
- Object detection: class scores and bounding boxes for multiple objects.
- Semantic segmentation: a class prediction for every pixel.
- Instance segmentation: separate masks for individual object instances.
Accuracy may suit balanced classification, while detection often uses intersection-over-union and mean average precision. Segmentation commonly uses IoU or Dice score because foreground pixels can be rare.
A box with intersection 40 and union 100 has IoU 0.40, which may fail a 0.50 matching threshold.
Choose metrics by task and error cost rather than using accuracy everywhere.
Image classification cannot localize an object simply because the correct class was predicted.
Training and Diagnosing Vision Models
A reliable pipeline preserves the same image contract from training to deployment.
Practical PyTorch Pattern
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
logits = model(images)
loss = criterion(logits, labels)
loss.backward()
optimizer.step()Monitor class-wise errors, confusion matrices, data quality, calibration and robustness to lighting, blur, crop and domain shift. Visual inspection of failures is essential because aggregate metrics can hide systematic problems.
If training augmentation normalizes with one mean and deployment uses another, the model receives a shifted input distribution.
Describe the complete preprocessing-to-deployment contract in project interviews.
High validation accuracy does not prove robustness if validation images share near-duplicates with training.
๐๏ธ Computer Vision Pipeline โ Visual Flow
Preserve the spatial reasoning chain from pixels to a validated task decision.
Set size, channels and normalization.
Convolve, activate and downsample.
Grow channels and receptive field.
Classify, localize or segment.
Measure errors and inspect failures.
Trace a 2D Convolution from First Principles
Follow every output row, output column, kernel row and kernel column. The cursor returns through all four loops exactly as Python calculates the feature map.
โWaiting for print(...)
Vision Logic Before Framework Calls
Use these procedure maps for revision, coding and interviews.
- Validate input, kernel, padding and stride.
- Pad the spatial borders when required.
- Move across each output row and column.
- Multiply and sum every aligned patch value.
- Add bias and apply the chosen activation.
- Record input channels, height and width.
- Apply the convolution output formula.
- Update channels to the filter count.
- Accumulate parameters and receptive field.
- Repeat before flattening or pooling globally.
- Load compatible pretrained weights.
- Replace the source prediction head.
- Train the new head as a baseline.
- Unfreeze selected deeper backbone blocks.
- Fine-tune carefully and validate domain shift.
- Separate errors by class and confidence.
- Inspect blur, lighting, crop and background.
- Check labels, duplicates and grouped splits.
- Measure task-aligned metrics and calibration.
- Change data or model using observed evidence.
๐ป Computer Vision Challenges
Attempt each program independently. Workspaces, hints and model programs remain collapsed initially.
Test Your Computer Vision Reasoning
Select one answer per question. Results show your choice, the correct answer and a clear explanation.
Diagnose Vision Systems Like an ML Engineer
Use visible evidence and task metrics before changing the network.
Check channel order, resize, padding, stride, flatten size and label shape.
Inspect duplicates, split grouping, augmentation realism, capacity and domain shift.
Review resolution, early downsampling, receptive-field scale and detection anchors or feature pyramids.
Inspect class counts, sampling, loss weighting, precision, recall and class-specific errors.
Use saliency and counterexamples to test whether contextโnot the objectโdrives predictions.
Verify colour space, normalization, resize policy, camera distribution and model mode.
๐ค Computer Vision & CNNs โ Interview Questions
Answer aloud before selecting Show Answer for each explanation.
A CNN Learns a Spatial Evidence Hierarchy
Represent pixels correctly.
Match reusable local filters.
Build deeper visual features.
Produce classes, boxes or masks.
Measure and inspect failures.
Computer vision becomes understandable when every pixel transform, spatial shape, receptive field, prediction target and evaluation decision can be explained.
Eight Practical Computer-Vision Habits
Display images after all preprocessing to verify colour, range and geometry.
Calculate every tensor shape before starting a long training run.
Split grouped sources before augmentation to prevent near-duplicate leakage.
Begin with transfer learning and a simple head when target data is limited.
Use only label-preserving augmentations appropriate to the domain.
Inspect class-wise errors and representative false positives and negatives.
Profile latency, memory and model size on the actual deployment device.
Save preprocessing, class mapping and thresholds with the model checkpoint.
Strengthen Computer-Vision Reasoning
Calculate intermediate values and defend every design decision.
- 01
Represent a 3ร3 grayscale image as a tensor.
- 02
Calculate one 2ร2 convolution output by hand.
- 03
Calculate output size for multiple padding and stride settings.
- 04
Count parameters in a 3-to-32 channel convolution.
- 05
Apply ReLU and 2ร2 max pooling to a feature map.
- 06
Trace receptive field through three convolution blocks.
- 07
Compare flattening and global average pooling.
- 08
Design valid augmentation for a medical-image dataset.
- 09
Explain feature extraction versus fine-tuning.
- 10
Calculate IoU for two bounding boxes.
- 11
Compare semantic and instance segmentation.
- 12
Diagnose a background-shortcut failure.
- 13
Write a complete PyTorch image-classification loop.
- 14
Design a deployment test for blur, lighting and resolution shift.
