Guide to AI and Data Courses · Lecture Notes

Chapter 18: Computer Vision

When your phone frames a face, or a car notices a pedestrian in the front camera and issues a brake warning, the computer is looking at nothing more than a table of numbers; yet from that table it concludes "someone is there, 8 meters away". Computer vision is the course about this road from pixels to meaning: understanding with geometry how an image is formed, finding reliable points and patterns in it, recognizing objects and saying where they are, and measuring success honestly. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.

Learning outcomes

The camera model
Use the pinhole model to compute the pixel at which a 3D point appears in an image.
Stereo depth
Recover depth from disparity and show why depth error grows with distance.
Features
Tell a corner, an edge and a flat region apart from the structure tensor with the Harris measure; compute the ratio test and the number of RANSAC iterations.
Evaluation
Compute the IoU of two boxes, a non-maximum suppression step and the average precision (AP) by hand.
Place of the course
State what separates computer vision from image processing, deep learning, computer graphics and pattern recognition.

18.1What question does the course ask?

How does a computer understand what is in an image or a video?

Computer vision studies how to extract meaning from an image or video: which objects are there, where they are, what 3D structure the scene has. The input is an image, but the output is not an image: it is a label, a box, a mask or depth. Transforming the image is the job of image processing.

An image arrives with one dimension lost to the world: the camera projects a three-dimensional scene onto a two-dimensional table, and depth is thrown away on the way. The question of computer vision is to undo that loss and extract something meaningful from the table: which objects are in the scene, where they are, how far from the camera. The difficulty is that the same object produces very different pixel patterns depending on light, viewpoint and background; the human eye handles this effortlessly, but for a computer it is an engineering problem.

The methods of the course come from two roots. The first is geometry: the camera model, calibration, stereo and multi-view geometry write the relation between image and world in mathematics. The second is learning: features and convolutional networks learn from examples to produce labels, boxes and masks from an image. The output is always information extracted from the image, not the image itself; transforming the image is the subject of Image Processing.

18.1.1Three tasks, three outputs

Three different questions can be asked of the same photograph. Classification gives one label to the whole image ("street scene"). Object detection gives a box and a label for every object ("pedestrian, this rectangle"). Segmentation gives a class to every pixel ("this pixel is road, this one is pedestrian"). The more detailed the output, the more expensive the labeling; drawing a box takes longer than giving one label, and drawing a mask takes longer than drawing a box. How convolutional networks are trained is covered in Deep Learning; in this course networks are used as a ready-made tool applied to vision problems.

18.1.2At a glance

CriterionComputer Vision
Approachextracting meaning from images
Inputimage or video
Outputlabel, box, depth, 3D structure
Success measureaccuracy, mAP, IoU
Math loadhigh: geometry, linear algebra
Data needsmany labeled images

18.2A short history

YearMilestone
1963Larry Roberts's PhD thesis recovers 3D blocks from line drawings: the field's first work.
1966MIT's "Summer Vision Project" expects to solve vision in one summer; it does not.
1982Marr's book Vision appears, describing vision as a layered computational process.
1999Lowe introduces SIFT features: local point matching invariant to scale and rotation.
2001Viola and Jones publish a real-time face detector; it ships in digital cameras.
2012AlexNet wins ImageNet by a wide margin; the deep learning era in vision begins.

18.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Local featuresCorners and keypoints: Harris, SIFT, ORB.
ClassificationOne label for the whole image: "cat".
Object detectionA box and label per object: YOLO, Faster R-CNN.
Semantic segmentationA class for every pixel: road, pedestrian, car.
Camera modelPinhole model, calibration, intrinsics and extrinsics.
Multi-view geometryStereo, epipolar geometry, structure from motion.
Motion and trackingOptical flow; following an object frame to frame.
Convolutional networksCNNs and vision transformers (ViT).

18.4The camera model and stereo depth

The simplest model of how a camera forms an image is the pinhole model: every point in the scene falls on the image plane along a ray through the camera center. If a point in camera coordinates is (X, Y, Z) (Z is the distance from the camera, the depth), the pixel position is found by dividing by Z.

Definition 18.1 (Pinhole projection)

u = fx · X / Z + cx, v = fy · Y / Z + cy. Here fx, fy are the focal lengths in pixels and (cx, cy) is the principal point of the image (usually its center). These numbers are the camera's intrinsic parameters; calibration means measuring them.

Example 18.1: Projecting a point to a pixel

Let the intrinsics be fx = fy = 800 pixels and (cx, cy) = (320, 240). Take the point (X, Y, Z) = (0.5, 0.25, 5) meters in camera coordinates (Y increases downward).

  1. Horizontal position. u = 800 · 0.5 / 5 + 320 = 80 + 320 = 400.
  2. Vertical position. v = 800 · 0.25 / 5 + 240 = 40 + 240 = 280.
  3. Moving away. With the same X, Y and Z = 10, u = 360 and v = 260: the point moves toward the image center, that is, distant things look smaller.

Because Z is in the denominator, depth cannot be recovered from a single image. A second view is needed. In stereo vision two cameras a distance B apart (the baseline) see the same scene. The same point lands on different columns in the two images; the difference is the disparity d. If the cameras are aligned:

Definition 18.2 (Depth in stereo)

Z = f · B / d. A large disparity means the point is near, a small one means it is far.

Example 18.2: From disparity to depth

f = 800 pixels, B = 0.12 m. The product f · B = 96 pixel·meters.

  1. A near point. For d = 16 pixels, Z = 96 / 16 = 6 m.
  2. Farther points. d = 8 gives Z = 12 m; d = 4 gives Z = 24 m.
  3. A one-pixel error. If 15 is measured instead of d = 16, Z = 6.4 m: an error of 0.4 m. If 3 is measured instead of d = 4, Z = 32 m: an error of 8 m.

The same one-pixel error causes a 0.4 m mistake at 6 meters and an 8 m mistake at 24 meters. Depth error grows with the square of the distance; this is why stereo cameras are reliable at short range and long range needs a wider baseline or other sensors.

Common mistake

Believing that depth can also be estimated from a single image. In the camera above, the point (0.5, 0.25, 5) and the point twice as far, (1, 0.5, 10), both land on the pixel (u, v) = (400, 280): all points on the same ray give the same pixel. Depth comes only from a second image, from the known size of an object, or from learned prior knowledge.

18.5Local features: corners, matching and RANSAC

To relate several images (panoramas, stereo, structure from motion) we first need points that can be found again in each of them. A patch of flat wall is hard to tell apart; a window slid along an edge does not change either. A good feature is a place where the appearance changes noticeably when the window is shifted in every direction: a corner. The Harris method measures this with a 2×2 matrix built from the gradients inside the window.

Definition 18.3 (Structure tensor and the Harris measure)

Over a window, form the matrix M = [ ΣIx2  ΣIxIy ; ΣIxIy  ΣIy2 ] (Ix, Iy are the horizontal and vertical gradients). The Harris response is R = det(M) − k · trace(M)2, with k usually between 0.04 and 0.06. A large positive R means a corner, a large negative R an edge, and R near zero a flat region. If both eigenvalues of the matrix are large it is a corner; if only one is large it is an edge.

Example 18.3: Harris response in three windows

Take k = 0.05. Let the structure tensors of three windows be as follows (the values are illustrative).

WindowMdettraceREigenvalues
Corner[100 20; 20 80]76001805980112.4 and 67.6
Edge[200 10; 10 4]700204−1380.8200.5 and 3.5
Flat[2 0; 0 3]654.753 and 2

For the corner, R = 7600 − 0.05 · 1802 = 7600 − 1620 = 5980; for the edge, R = 700 − 0.05 · 2042 = 700 − 2080.8 = −1380.8; for the flat window, R = 6 − 0.05 · 25 = 4.75. On the edge one eigenvalue is very large and the other very small; because the determinant stays small, the measure turns negative.

18.5.1Matching and the ratio test

Once corners are found, each is described by a descriptor vector (SIFT, ORB) and the nearest descriptors are matched between two images. But the nearest neighbor is often wrong, especially with repeating patterns. The ratio test proposed by Lowe divides the distance to the nearest neighbor by the distance to the second nearest and discards the match if the ratio is above about 0.8. If a match has distances 0.30 and 0.80, the ratio is 0.30 / 0.80 = 0.375 and the match is accepted: the nearest neighbor is clearly better. If another match has 0.55 and 0.60, the ratio is 0.917 and it is discarded: the two candidates are almost equally good and the choice is unreliable.

18.5.2RANSAC

Even among the matches that pass the test, some are wrong. RANSAC copes with such outliers: it draws the smallest possible random sample from the data (4 matches for a homography), builds the model, counts how many matches agree with it, repeats this, and keeps the model with the most support. If the fraction of correct matches is w, the sample size is s and the desired success probability is p, the number of iterations needed is N = log(1 − p) / log(1 − ws). With half the matches correct (w = 0.5), s = 4 and p = 0.99, N = log(0.01) / log(1 − 0.0625) ≈ 71.4, so 72 iterations suffice. If the correct fraction rises to 0.7, only 17 iterations are needed.

Common mistake

Counting the nearest neighbor as a match and skipping geometric verification. If the image has a repeating pattern (the windows of a building facade), many matches are wrong; the ratio test and RANSAC together remove these by checking whether the matches agree with a single geometric transformation.

18.6Evaluating detection: IoU, suppression and AP

In classification a prediction is simply right or wrong; in detection the prediction is a box, and to be counted as right it must overlap the true box enough. Overlap is measured by the ratio of the intersection area of two boxes to their union area.

Definition 18.4 (IoU (intersection over union))

IoU = intersection area / union area. The value lies between 0 and 1; 1 means the boxes coincide, 0 that they do not overlap at all. A common rule counts a prediction as correct when IoU ≥ 0.5.

Example 18.4: IoU and removing duplicate boxes

Let boxes be given as (x1, y1, x2, y2). The true box is G = (0, 0, 10, 10); a network produces these three boxes with their confidences: A = (0, 0, 10, 10) (0.9), B = (1, 1, 11, 11) (0.8) and C = (20, 20, 30, 30) (0.7).

  1. A and B. The intersection is 9 × 9 = 81, the union 100 + 100 − 81 = 119; IoU = 81 / 119 ≈ 0.68.
  2. Suppression (NMS). Boxes are sorted by confidence. A is highest and is kept. B overlaps A by 0.68 (threshold 0.5), so it counts as a second guess for the same object and is dropped. C does not overlap A at all (IoU = 0) and is kept.
  3. Result. Two boxes remain: A (IoU = 1 with the true box, correct) and C (overlaps no true object, a false positive).

For each class a precision–recall curve is drawn: predictions are sorted by confidence, and as the threshold is lowered, precision (how many of the boxes are right) and recall (how many of the real objects were found) are computed at every step. The area under the curve is the average precision (AP); its mean over classes is mAP.

Example 18.5: A small AP calculation

A class has 4 true objects. The network's predictions, sorted by confidence, turn out as: correct, correct, wrong, correct, wrong.

RankOutcomePrecisionRecall
1correct1/1 = 1.001/4 = 0.25
2correct2/2 = 1.002/4 = 0.50
3wrong2/3 ≈ 0.670.50
4correct3/4 = 0.753/4 = 0.75
5wrong3/5 = 0.600.75

For each recall level we take the highest precision reached at that level or beyond: 1 for 0.25, 1 for 0.50, 0.75 for 0.75. The fourth object is never found, so recall never reaches 1. The area is AP = 0.25 · 1 + 0.25 · 1 + 0.25 · 0.75 = 0.6875.

Common mistake

Settling for a single number such as "the network is 95 percent accurate". In detection, which IoU threshold is used, at which confidence threshold one looks, and how large the object is all change the result a great deal; for small objects the same network can have a markedly lower AP. In safety-critical uses the average AP is not enough: every missed pedestrian counts separately.

18.7How is the course taught?

18.7.1A typical workflow

Capturecamera,videoPreprocessimage proc.stepsExtractfeaturesfeatures,CNNInterpretclass, box,depthDecidebrake, alarm,count
Figure 18.1: A typical workflow in Computer Vision

A driver assistance system grabs a frame from the front camera, balances brightness, extracts features with a convolutional network and marks pedestrians with boxes; it also estimates their distance from a stereo camera. The output is not an image but the fact "pedestrian at 8 meters"; the system issues a brake warning accordingly.

18.7.2Topics over the semester

  1. Image formation and the camera model
  2. Filters and edge detection (image processing review)
  3. Local features: corners, SIFT, ORB
  4. Feature matching and RANSAC
  5. Homographies and panorama stitching
  6. Camera calibration and stereo vision
  7. Structure from motion and multi-view geometry
  8. Optical flow and object tracking
  9. Classification with convolutional networks
  10. Object detection: the R-CNN family, YOLO
  11. Semantic and instance segmentation
  12. Vision-language models and current trends

This is a typical semester; the order and coverage vary between universities.

18.7.3Skills you will gain

  • OpenCV
  • using and fine-tuning pretrained models in PyTorch
  • camera calibration
  • preparing labeled data
  • evaluating with IoU and mAP

18.7.4Try it yourself

The Try It: Find the Rings in the Image slide in the presentation lets you solve a typical problem of this course yourself: On an assembly line a camera must count the ring-shaped gaskets on the belt. A template slides over every position and similarity is measured. Change the confidence threshold and suppression, and check the boxes.

18.8Are you ready for this course?

18.8.1Prerequisites

CourseWhy it is needed
Image Processingedges, filters, segmentation
Linear algebramatrices, eigenvalues and projection: the language of camera geometry
Programmingarray operations and using libraries in Python
Algorithmssearch, matching and complexity: feature matching and tracking

18.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you explain matrix multiplication, inverses and eigenvalues?Linear Algebra
Do you know that an image is a matrix of pixels, and what convolution does?Image Processing
Can you explain how a neural network is trained with a loss and gradient descent?Artificial Neural Networks
Can you work with NumPy arrays in Python?An intro programming course, then a short NumPy tutorial

18.9Neighboring courses

Image ProcessingDeep LearningComputer GraphicsPattern RecognitionMedical ImagingRemote SensingRoboticsBiometricsComputer Vision
subfieldbuilds onshares methodsapplication
Figure 18.2: Neighbors of Computer Vision and the kind of relation

18.9.1Where it overlaps

RelationCourseShared ground
builds onThis course builds on Image Processingedges, filters, segmentation
applicationMedical Image Processing applies the methods of this courselesion detection, classification
applicationRemote Sensing applies the methods of this courseland cover classification, change detection
applicationBiometric Systems applies the methods of this courseface recognition
shares methodsShares methods with Deep Learningconvolutional neural networks, vision transformers
shares methodsShares methods with Pattern Recognitionobject classification
shares methodsShares methods with Computer Graphicscamera model; graphics renders scenes, vision recovers them
shares methodsShares methods with Robotics and Robot Visionrobot vision, SLAM

18.9.2Where it differs

  • Image Processing: In image processing both input and output are images; in computer vision the input is an image and the output is meaning: a label, a box, depth.
  • Deep Learning: Deep learning is a general tool; vision uses it together with camera geometry, multi-view and motion knowledge.
  • Computer Graphics: Graphics produces an image from a scene description; vision does the reverse, rebuilding the scene from the image.
  • Pattern Recognition: Pattern recognition classifies any kind of measurement; vision treats classification together with spatial structure, position and 3D.

18.10In practice

18.10.1Applications

AreaWhat is done
Autonomous drivingDetecting lanes, pedestrians and traffic signs.
Face recognitionPhone unlock, access control.
RetailCheckout-free stores, shelf monitoring.
Augmented realityLocating the camera and adding objects to the scene.
IndustrySpotting defective products and removing them from the line.
Sports analyticsTracking players and the ball, statistics.

18.10.2Risks and ethics

RiskExplanation
Face recognition and surveillanceIdentifying people in a crowd can turn into tracking without consent; many countries restrict its use in public spaces.
Unequal performanceError rates can be markedly higher for skin tones and age groups that are under-represented in the training data.
Adversarial examplesA small sticker the human eye ignores can make a model read a stop sign as a different sign.
Safety-critical failuresIn self-driving, a single missed pedestrian is a cost that average accuracy does not show.

These issues are discussed in depth in Explainable AI and AI Ethics.

18.10.3Tools and datasets

Tools: OpenCV, PyTorch / torchvision, Ultralytics YOLO, Detectron2, COLMAP, Open3D.

Well-known datasets: ImageNet, COCO, PASCAL VOC, KITTI, Cityscapes, ADE20K.

Unlike image processing, vision needs many labeled images; in COCO the box and mask of every object were drawn by hand.

18.11Common misconceptions

Common mistake

Computer vision is another name for image processing.

Image processing transforms the image; vision extracts meaning from it. Vision uses image processing as a first step.

Common mistake

Vision is a solved problem.

Networks can still fail noticeably when the lighting, weather or camera differs from the training data.

Common mistake

Vision is just deep learning.

Calibration, stereo, SLAM and 3D reconstruction rest largely on geometry.

Common mistake

A model "sees" an object the way a human does.

Networks can over-rely on texture and context; a small pixel change can flip a decision.

18.12Summary

  • Computer vision extracts meaning from images: the output is a label, a box, a mask or depth; transforming the image is the job of image processing.
  • The pinhole model projects a point to a pixel with u = f · X / Z + c; depth is lost and is recovered in stereo with Z = f · B / d. Depth error grows with the square of the distance.
  • A good feature is a corner: the Harris measure finds windows where both eigenvalues of the structure tensor are large.
  • Matches are filtered by the ratio test, and RANSAC selects those that are geometrically consistent; the number of iterations follows from the inlier fraction and the sample size.
  • Detection is evaluated with IoU (overlap), suppression of duplicate boxes and the area under the precision–recall curve (AP, mAP).

18.13Test Yourself

  1. A camera has f = 500 pixels and (cx, cy) = (320, 240). At which pixel does the point (X, Y, Z) = (0.4, 0.2, 4) m in camera coordinates land?

    Answer

    u = 500 · 0.4 / 4 + 320 = 50 + 320 = 370, v = 500 · 0.2 / 4 + 240 = 25 + 240 = 265. The point is at pixel (370, 265).

  2. In a stereo pair f = 700 pixels, B = 0.5 m and a point has disparity d = 35 pixels. What is the depth? What happens if the disparity is measured wrongly by one pixel (34 or 36)?

    Answer

    Z = 700 · 0.5 / 35 = 350 / 35 = 10 m. For d = 34, Z = 350 / 34 ≈ 10.29 m; for d = 36, 350 / 36 ≈ 9.72 m. A one-pixel error causes about a 0.3 m mistake; the farther the point, the larger it gets.

  3. A window has structure tensor M = [50 0; 0 50] and k = 0.05. What is the Harris response, and is the window a corner, an edge or flat?

    Answer

    det = 2500, trace = 100, R = 2500 − 0.05 · 1002 = 2500 − 500 = 2000. A large positive value and two equal large eigenvalues (50 and 50): a corner.

  4. 70 percent of the matches are correct, 4 matches are sampled for a homography, and we want a 0.99 probability that at least one sample is all correct. How many RANSAC iterations are needed?

    Answer

    ws = 0.74 ≈ 0.2401. N = log(0.01) / log(1 − 0.2401) ≈ 4.605 / 0.2745 ≈ 16.8; rounding up gives 17 iterations.

  5. Two boxes (0, 0, 4, 4) and (2, 2, 6, 6) are given. What is the IoU; with a threshold of 0.5, is the prediction counted as correct?

    Answer

    The intersection is 2 × 2 = 4, the union 16 + 16 − 4 = 28; IoU = 4 / 28 ≈ 0.14. Far below the threshold: the prediction is not counted as correct.

  6. In each case, is the output classification, object detection or segmentation? (a) "This photo is a beach." (b) A rectangle for every face in a photo. (c) Marking every pixel that belongs to a tumor in a medical scan.

    Answer

    (a) Classification: one label for the whole image. (b) Object detection: a box and a label per object. (c) Segmentation: a class per pixel. The more detailed the output, the more expensive it is to prepare the labeled data.

18.14After this course

Computer vision is the center of the third part: robotics, biometrics, medical image processing and remote sensing apply its methods to their own domains. To go deeper, continue with deep learning and generative models; on the geometry side, with computer graphics and robotics.

Courses that build on or extend this one: Medical Image Processing, Remote Sensing, Biometric Systems.

Related careers: Computer vision engineer, Autonomous systems engineer, AR/VR developer, Robotics perception engineer, Researcher.

18.15Further reading

  • R. Szeliski, Computer Vision: Algorithms and Applications (2nd ed., 2022): a reference book covering the camera model, features, matching and detection in depth and with many examples.
  • R. Hartley and A. Zisserman, Multiple View Geometry in Computer Vision (2nd ed., 2004): gives the mathematical foundation of camera geometry, homographies and stereo.
  • S. J. D. Prince, Computer Vision: Models, Learning, and Inference (2012): presents vision through probabilistic models and learning.

18.16References

  1. Szeliski, Computer Vision: Algorithms and Applications, 2nd ed., Springer, 2022.
  2. Hartley and Zisserman, Multiple View Geometry in Computer Vision, 2nd ed., Cambridge University Press, 2004.
  3. Prince, Computer Vision: Models, Learning, and Inference, Cambridge University Press, 2012.
  4. Marr, Vision, W. H. Freeman, 1982.

Related pages: Slides · Slides (PDF) · Course page