TExcelTAD

Computer Vision: Introduction

A camera produces numbers: a 12-megapixel photo is 36 million integers between 0 and 255. Computer vision turns those numbers into statements about the world: "this is a cat", "there are three cars, here, here and here", "these pixels are road", "the person who left camera 2 is the one who entered camera 5". Every one of those statements is a different task with its own output format, its own models and its own way of being measured, and confusing them is the first mistake new projects make.

This course goes from the pixels up. It starts with image processing that needs no learning at all (colour spaces, filters, edges, geometry), which is still how most vision pipelines prepare and clean their input, then covers how images are annotated, and then the four big learned tasks: classification, detection, segmentation and tracking, with faces and person re-identification as two important special cases. It ends with the seven practical projects of the curriculum as guided labs.

The tasks, by what they output

classificationone labelper image detectionclass, box, scoreper object semantic seg.a class forevery pixel instance seg.a mask forevery object t1t2t3 trackingboxes linkedover frames more output per image, more expensive labels, harder evaluation: left to right
Task Output for one image Typical metric Labels cost Lessons
Classification one class (or several, multi-label) accuracy, F1 seconds per image pipeline, CNNs
Detection a variable-length list of (class, box, score) AP, mAP (detection metrics) a box per object basics, YOLO
Semantic segmentation an H×WH \times W map of class ids mean IoU, Dice (segmentation metrics) a polygon or brush stroke per region semantic, U-Net
Instance segmentation a mask, class and score per object mask AP a polygon per object instance
Tracking boxes with an identity that persists across frames MOTA, IDF1 boxes and ids in every frame tracking
Re-identification a ranking of gallery images for a query person rank-1, mAP identity labels across cameras faces, re-ID

Picking the task is a product decision before it is a modelling decision. Counting cars at a junction needs detection and tracking, not segmentation. Measuring the area of a tumour needs segmentation, because a box would overestimate it. Sorting photos into albums needs only classification. The cheapest task that answers the question is usually the right one, because labels for the richer tasks cost many times more.

An image is an array

Everything in this course starts from the same data structure. Here is one of the sample images that ship with scikit-image (a NASA portrait of the astronaut Eileen Collins, public domain), first as an array, then with a face detector that has worked since 2001 and needs no GPU:

python · try it yourself
import numpy as np
import cv2
from skimage import data
cv2.setLogLevel(0)

img = data.astronaut()                       # RGB, as scikit-image and Matplotlib use
print("shape (H, W, C):", img.shape, "| dtype:", img.dtype, "| values", img.min(), "to", img.max())
print("pixel at row 100, column 200 (R, G, B):", img[100, 200].tolist())
print("mean of each channel:", img.reshape(-1, 3).mean(axis=0).round(1).tolist())

gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)  # OpenCV knows the order only if you tell it
faces = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
for x, y, w, h in faces.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5):
    print(f"face at x={x}, y={y}, size {w} x {h} pixels")
shape (H, W, C): (512, 512, 3) | dtype: uint8 | values 0 to 255
pixel at row 100, column 200 (R, G, B): [81, 57, 17]
mean of each channel: [141.6, 105.8, 96.5]
face at x=177, y=66, size 95 x 95 pixels

Three things in those few lines recur in every lesson. The array is indexed row first (img[100, 200] is y=100y = 100, x=200x = 200), while boxes are written xx first. scikit-image gives RGB, but OpenCV assumes BGR unless told otherwise, so every conversion names its direction. And the detector returns boxes as (x, y, w, h), which is one of at least three box formats in daily use (box formats sorts them out). Digital images and colour spaces start from here.

The same image through a modern detector

The Haar cascade above is hand-designed for one thing, frontal faces. A modern detector is a convolutional network trained on a large labelled data set (here COCO, about 118,000 training images with 80 object classes) that finds many kinds of object at once. This example needs PyTorch and Ultralytics, which cannot run in a browser, so it is recorded: it was run in a Docker image on a CPU and its output saved.

python · try it yourself
import numpy as np
from ultralytics import YOLO
from skimage import data

model = YOLO("yolov8n.pt")                   # the "nano" YOLOv8: 3.2 million parameters, COCO classes
for name in ["astronaut", "coffee", "chelsea"]:
    img = getattr(data, name)()[:, :, ::-1].copy()          # RGB -> BGR, as Ultralytics expects for arrays
    result = model.predict(img, conf=0.25, verbose=False)[0]
    found = [f"{result.names[int(c)]} {float(s):.2f}" for c, s in zip(result.boxes.cls, result.boxes.conf)]
    print(f"{name:9s} {img.shape[1]} x {img.shape[0]}: {found}")
astronaut 512 x 512: ['person 0.71']
coffee    600 x 400: ['cup 0.92', 'dining table 0.72']
chelsea   451 x 300: ['cat 0.89']

A person, a cup on a table, a cat, each with a confidence score. Whether 0.71 is "sure enough" is not something the model decides: you choose a threshold from a precision-recall trade-off measured on your own data. The detection section builds every piece of such a detector from scratch (IoU, non-maximum suppression, anchors, the grid head) and Ultralytics YOLO uses it properly.

How the course is organised

  1. Images and image processing. Arrays, colour spaces, histograms and thresholds, filtering, edges, morphology, resizing and geometric transforms, and classical features (corners, keypoints, HOG). All of it runs in your browser with OpenCV and scikit-image, and each operation is first written in NumPy so that nothing is a black box.
  2. Annotation. What to label for each task, how to write guidelines and measure annotator agreement, and the file formats: Pascal VOC, COCO, YOLO, masks, polygons and run-length encoding.
  3. Classification. Classical baselines (raw pixels, HOG with a linear SVM), a CNN trained in PyTorch, the common backbones (ResNet, MobileNet, EfficientNet, ViT), and using pretrained ImageNet weights.
  4. Detection. IoU, non-maximum suppression, anchors and box encoding, two-stage (Faster R-CNN) and one-stage (YOLO, SSD) detectors, a tiny detector trained from scratch, and YOLOv8 and YOLO11 from Ultralytics.
  5. Segmentation. Thresholds and clustering, fully convolutional networks, a U-Net trained from scratch, watershed and Mask R-CNN.
  6. Video, tracking, faces and re-identification. Motion and background subtraction, the Kalman filter and SORT tracker, Haar face detection, face embeddings for verification and identification, and person re-identification across cameras.
  7. Seven projects: image classification, human detection, vehicle detection, face detection, multi-object tracking, person re-identification and real-time video analytics, each with a baseline, an improvement, an honest evaluation and a write-up template.

Training mechanics, losses and the evaluation metrics are taught in Training Mechanics, Evaluation & Model Improvement, transfer learning in Training Strategies, and the network building blocks (convolution, pooling, residual connections, the training loop in PyTorch) in Deep Learning. The math of convolution and receptive fields is derived in Convolution and Pooling and Receptive Fields, and geometric transforms as matrices in Geometric Interpretation of Linear Transformations. This course links to those lessons rather than repeating them, and concentrates on what is specific to images.

How the examples run

  • In your browser: NumPy, SciPy, scikit-learn, OpenCV 4.11 and scikit-image run in Python compiled to WebAssembly. You can edit and rerun them. Most of the course is this kind.
  • Recorded: examples that import PyTorch, torchvision or Ultralytics carry a Recorded badge. They were run on 4 CPU threads (never a GPU) in a Docker image with three pretrained models cached: ResNet-18 trained on ImageNet, and the YOLOv8n and YOLO11n detectors trained on COCO. Models whose weights are not cached (Faster R-CNN, Mask R-CNN, face and re-identification networks) appear with random weights, to show their structure and output shapes, or as code you can run on your own machine; their core algorithms are always built and run from scratch first.

Images come from skimage.data or are drawn in code: small synthetic scenes of squares, circles and triangles, a synthetic traffic video and synthetic pedestrians. Synthetic data has a big advantage for learning: the ground truth is exact, so every metric in a lesson can be checked. It also has a big limit, which the lessons say when it matters: a model that works on drawn shapes has proved nothing about photographs.

Note: Face recognition and person re-identification process biometric and personal data. The lessons on them include what the law and basic ethics require (consent, purpose limitation, bias testing); read privacy, consent and licensing before building anything that identifies people.

Test yourself

A city wants the number of cars crossing a junction per hour. Which tasks does the system need?

  1. Image classification only
  2. Object detection plus tracking, so that each car is counted once
  3. Semantic segmentation only
  4. Face recognition

img is a NumPy image of shape (512, 512, 3). What does img[100, 200] return?

  1. The pixel at x = 100, y = 200
  2. The pixel at row 100 (y = 100), column 200 (x = 200), as three channel values
  3. Row 100 and row 200
  4. A 100 x 200 crop

Why can a detector's output not be scored with plain accuracy?

  1. Detectors have no classes
  2. The number of objects varies per image, and a box can be partly right, so boxes must be matched to objects by IoU before counting hits
  3. Accuracy needs a GPU
  4. Detectors output only one box

An example in this course carries a Recorded badge. What does that mean?

  1. It is a video
  2. It imports PyTorch or Ultralytics, so the page shows output saved from a real CPU run in Docker instead of running it in the browser
  3. Its output is invented
  4. It runs on a GPU