Exercises
These exercises cover the whole course, in its order. Work each one on paper or in a playground first, then open the answer. Every answer links to the lesson that explains it. Some sections end with a runnable check that computes the answers of that section, so you can compare numbers.
Images and image processing
1. uint8 arithmetic. Two uint8 pixels hold 200 and 100. What do a + b, a - b and b - a give in NumPy, and what is the safe way to average them?
Answer
uint8 wraps modulo 256: , , . Convert first: (a.astype(np.int16) + b) // 2 or work in float32 and convert back with clipping (digital images).
2. Grey from colour. A pixel is . Compute its grey value with OpenCV's weights . Then: if the array was loaded with cv2.imread (BGR) but converted with COLOR_RGB2GRAY, which weights does each channel get, and what value comes out?
Answer
. With the wrong order the stored values (B, G, R) are read as R, G, B: . No error is raised; red and blue just swap weights (colour spaces).
3. Hue wraps. In OpenCV's 8-bit HSV, hue runs from 0 to 179. Write a mask condition for "red" that keeps hues within 10 of pure red.
Answer
Red sits at both ends of the hue circle, so two ranges are needed: (h <= 10) | (h >= 170), together with a minimum saturation and value so that greys and blacks (whose hue is meaningless) are excluded (colour spaces).
4. Filter output size. A kernel slides over a image with stride 1. How big is the output with no padding, and with one pixel of zero padding on every side? What about a kernel and stride 2 without padding?
Answer
Output side : ; with , ; for : . The convolution lab of image filtering shows the first two cases.
5. Sobel on a step. A grey image is 0 in columns 0 to 2 and 10 in columns 3 to 5, the same in every row. What does the Sobel x kernel give at a pixel in column 2, column 3 and column 4 (away from the top and bottom borders)?
Answer
Each row of the kernel sees (left, right) neighbours; the weights add up to . Column 2: left 0, right 10, so . Column 3: left 0, right 10, also 40. Column 4: left 10, right 10, so 0. The edge between columns 2 and 3 gives a two-pixel-wide response, which is why Canny thins edges with non-maximum suppression (edge detection).
6. Opening and closing. You thresholded an image and got foreground objects with a few isolated noise pixels outside them and a few small holes inside them. Which morphological operation removes each problem?
Answer
Opening (erosion then dilation) removes small specks of foreground; closing (dilation then erosion) fills small holes in the foreground. Apply opening, then closing, with a structuring element larger than the specks and holes but smaller than the objects (morphology).
7. Letterbox and boxes. A image (width by height) is letterboxed to : scaled to fit, then padded equally top and bottom. A box is in the original. Where is it in the letterboxed image?
Answer
Scale , so the image becomes and is padded by pixels at the top and bottom. Box: values times 0.5, values times 0.5 plus 40: . To map predictions back, subtract the padding first, then divide by the scale (resizing and geometry).
8. HOG size. skimage.feature.hog on a grey image with 9 orientations, pixel cells and cell blocks: how many numbers does it return?
Answer
cells, so overlapping block positions, each with numbers: (classical features).
Check exercises 1, 2, 4, 5 and 8:
import numpy as np
from skimage.feature import hog
a, b = np.array([200], np.uint8), np.array([100], np.uint8)
print("1:", (a + b).item(), (a - b).item(), (b - a).item(), "| safe mean:", ((a.astype(np.int16) + b) // 2).item())
w = np.array([0.299, 0.587, 0.114])
print("2:", round(float(w @ [200, 100, 50]), 2), "| BGR read as RGB:", round(float(w @ [50, 100, 200]), 2))
side = lambda n, k, p, s: (n + 2 * p - k) // s + 1
print("4:", side(12, 3, 0, 1), side(12, 3, 1, 1), side(12, 5, 0, 2))
img = np.tile([0, 0, 0, 10, 10, 10], (5, 1)).astype(float)
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
print("5:", [float((img[1:4, c - 1:c + 2] * sobel_x).sum()) for c in (2, 3, 4)])
print("8:", hog(np.zeros((32, 32)), orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2)).size)1: 44 100 156 | safe mean: 150
2: 124.2 | BGR read as RGB: 96.45
4: 10 12 4
5: [40.0, 40.0, 0.0]
8: 324
Annotation
9. Box formats. An object occupies in a image (width by height). Write it as a COCO bbox and as a YOLO line for class 2.
Answer
COCO: . YOLO: centre , normalised by width 200 and height 120: 2 0.35 0.5 0.3 0.5. Normalising values by the width is the classic bug (box formats).
10. COCO RLE. A binary mask is [[0, 1, 1], [0, 1, 0], [0, 0, 0]]. Write its uncompressed COCO RLE counts.
Answer
COCO reads the mask column by column (Fortran order) and the counts start with a run of zeros: column 0 is 0 0 0, column 1 is 1 1 0, column 2 is 1 0 0, giving the sequence 0 0 0 1 1 0 1 0 0, so counts . Row-major order would give a different, wrong encoding (masks and RLE).
11. Agreement. Two annotators draw boxes and for the same object. What is their IoU, and would this pass a 0.7 agreement threshold?
Answer
Intersection : . Each box has area ; union ; IoU , which passes 0.7. Agreement thresholds should be set from measured annotator-to-annotator IoU, because the model cannot be expected to agree with the labels better than the labellers agree with each other (annotation).
import numpy as np
x1, y1, x2, y2, W, H = 40, 30, 100, 90, 200, 120
print("9: COCO", [x1, y1, x2 - x1, y2 - y1], "| YOLO 2", (x1 + x2) / 2 / W, (y1 + y2) / 2 / H, (x2 - x1) / W, (y2 - y1) / H)
def rle_counts(mask):
flat = np.asarray(mask).ravel(order="F") # column by column
counts, current, run = [], 0, 0
for v in flat:
if v != current:
counts.append(run); current, run = v, 0
run += 1
return counts + [run]
print("10:", rle_counts([[0, 1, 1], [0, 1, 0], [0, 0, 0]]))
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
print("11:", round(iou([10, 10, 50, 50], [14, 12, 54, 52]), 3))9: COCO [40, 30, 60, 60] | YOLO 2 0.35 0.5 0.3 0.5
10: [3, 2, 1, 1, 2]
11: 0.747
Classification and backbones
12. Parameters of a convolution. How many parameters does a convolution from 64 to 128 channels have (with bias)? And a depthwise separable version ( depthwise on 64 channels, then to 128, both with bias)?
Answer
Standard: . Depthwise: ; pointwise: ; total , about 8.2 times fewer. That ratio is the whole idea of MobileNet (vision backbones).
13. Output stride. A backbone has output stride 32. What size is its last feature map for a input and for a input, and what does that mean for a 20-pixel object?
Answer
and . A 20-pixel object is smaller than one cell of the last map, which is why detectors take features from earlier, finer stages too (feature pyramids, strides 8 and 16) (vision backbones, YOLO).
14. Preprocessing. A ResNet-18 pretrained on ImageNet is fed images that are BGR, in the 0 to 255 range, and not normalised. Name the three fixes, and say which one an error message would catch.
Answer
Reverse the channels to RGB; divide by 255; subtract the ImageNet mean and divide by the standard deviation per channel. None raises an error: the network accepts any float tensor of the right shape and silently returns worse predictions (pretrained models and transfer).
15. Which transfer strategy? You have 400 labelled microscope images in 4 classes and an ImageNet backbone. What do you try first, and what second?
Answer
First, feature extraction or training only a new head on the frozen backbone (few labels, so few trainable parameters), with augmentation that is valid for microscopy (rotations and flips usually are). Second, unfreeze the last stage with a small learning rate, if validation shows the frozen features are not enough, because microscopy is far from ImageNet photos. Compare both against a classical baseline (pretrained models and transfer, transfer learning).
Detection
16. Greedy NMS by hand. Three boxes of class "car": A score 0.9, B score 0.8, C score 0.7. Which survive NMS at IoU threshold 0.5? And at 0.7?
Answer
IoU(A, B): intersection , union , . IoU(A, C) . At 0.5: keep A, drop B (0.681 above 0.5), keep C. At 0.7: B is not suppressed (0.681 below 0.7), so A, B and C all survive, and B becomes a duplicate detection, a false positive in AP (NMS).
17. Box encoding. An anchor has centre , width 40, height 20. A ground-truth box has centre , width 60, height 20. Compute with , , , .
Answer
, , , . The logarithm makes the width target symmetric for growing and shrinking and keeps the decoded width positive (anchors and box encoding).
18. Predictions of a YOLOv8 head. For a input, YOLOv8 predicts at strides 8, 16 and 32, one prediction per grid cell. How many predictions is that?
Answer
. After the score threshold and NMS, a typical image keeps a handful (one-stage detectors).
19. Two-stage or one-stage. Name the job of the region proposal network in Faster R-CNN, and why RoI Align replaced RoI pooling.
Answer
The RPN scores anchors as object or not and refines them into a few hundred class-agnostic proposals, which the second stage classifies and refines. RoI pooling rounds box coordinates to the feature grid twice, shifting small boxes by up to a stride; RoI Align samples the features at exact positions with bilinear interpolation, which matters most for masks and small objects (Faster R-CNN).
import numpy as np
def iou(a, b):
ix = max(0, min(a[2], b[2]) - max(a[0], b[0])); iy = max(0, min(a[3], b[3]) - max(a[1], b[1]))
inter = ix * iy
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter)
def nms(boxes, scores, thr):
order, keep = list(np.argsort(scores)[::-1]), []
while order:
i = order.pop(0); keep.append(int(i))
order = [j for j in order if iou(boxes[i], boxes[j]) <= thr]
return keep
boxes = [[0, 0, 10, 10], [1, 1, 11, 11], [20, 0, 30, 10]]
scores = np.array([0.9, 0.8, 0.7])
print("16: IoU(A, B) =", round(iou(boxes[0], boxes[1]), 3), "| keep at 0.5:", nms(boxes, scores, 0.5), "| at 0.7:", nms(boxes, scores, 0.7))
xa, ya, wa, ha = 50, 50, 40, 20
x, y, w, h = 54, 48, 60, 20
print("17:", [round(float(v), 3) for v in [(x - xa) / wa, (y - ya) / ha, np.log(w / wa), np.log(h / ha)]])
print("18:", sum((640 // s) ** 2 for s in (8, 16, 32)))16: IoU(A, B) = 0.681 | keep at 0.5: [0, 2] | at 0.7: [0, 1, 2]
17: [0.1, -0.1, 0.405, 0.0]
18: 8400
Segmentation
20. Semantic or instance? For each task, say which segmentation it needs: (a) the share of an aerial photo covered by forest; (b) counting cells in a microscope image where cells touch; (c) a self-driving car's drivable area.
Answer
(a) semantic: only the class per pixel matters; (b) instance: touching cells must be separated to be counted (watershed or Mask R-CNN); (c) semantic: the road region has no instances (semantic, instance).
21. Why U-Net has skip connections. What would the decoder lack without them?
Answer
The encoder downsamples, so its deepest features know what is in a region but have lost where its boundary is to within a few pixels. Skip connections hand the decoder the high-resolution features of the same scale, so it can place the boundaries precisely (U-Net).
22. Dice and IoU. A predicted mask and a true mask each have 100 pixels and overlap in 60. Compute IoU and Dice.
Answer
IoU ; Dice . Dice is always at least IoU for the same masks, (segmentation metrics).
Video, tracking, faces and re-identification
23. Background subtraction. A fixed camera watches a car park. Why does a running-average background model slowly make a parked car disappear from the foreground, and is that a bug?
Answer
The model keeps blending new frames into the background, so anything that stops moving becomes background after a time set by the learning rate. It is a design choice: good for counting moving traffic, wrong for "how long has this car been parked", where you need detection on single frames or a slower background (video and motion).
24. Kalman prediction. A track with a constant-velocity model is at with velocity pixels per frame. The detector misses it for two frames. Where does SORT predict it, and what limits how long the track is kept alive?
Answer
, then : the filter keeps predicting with growing uncertainty. The track is deleted after max_age frames without a matched detection; a larger value survives longer occlusions but risks linking a different object to the old identity (tracking).
25. MOTA. A sequence has 200 ground-truth boxes over all frames. The tracker produces 15 false negatives, 10 false positives and 3 identity switches. Compute MOTA.
Answer
. MOTA weighs detection errors far more than identity errors; IDF1 is the metric that rewards keeping the same id (tracking).
26. Integral image. Why does a Haar cascade compute an integral image first, and how many lookups give the sum over any rectangle?
Answer
Haar-like features are differences of rectangle sums, evaluated thousands of times per window at many scales. With the integral image , any rectangle sum is from its four corners: four lookups, whatever its size (face detection).
27. Verification versus identification. A face system compares embeddings by cosine similarity with a threshold of 0.5. A user unlocks their phone (1:1); a camera searches a watch-list of 10,000 people (1:N). Why does the same false-accept rate per comparison mean very different things in the two settings?
Answer
In 1:N search, each probe is compared with 10,000 entries, so a per-comparison false-accept rate of gives about one false match per probe on average ( chance of at least one). Identification needs far stricter thresholds, and its errors fall on people who never consented; bias across demographic groups multiplies with it (face recognition).
28. CMC and mAP. A re-ID query has two true matches in a gallery of 6. The ranked gallery is: wrong, right, wrong, right, wrong, wrong. What are rank-1, rank-5 and the average precision of this query?
Answer
Rank-1: 0 (the top result is wrong). Rank-5: 1 (a true match is among the top 5). AP: precision at the true matches is and , so AP . CMC rewards finding one match early; mAP rewards ranking all of them high (person re-ID).
import numpy as np
inter = 60
print("22: IoU", round(inter / (100 + 100 - inter), 3), "Dice", 2 * inter / 200)
print("24:", [100 + 3 * k for k in (1, 2)])
print("25: MOTA", 1 - (15 + 10 + 3) / 200)
print("27: P(at least one false match in 10000)", round(1 - (1 - 1e-4) ** 10000, 3))
ranked = np.array([0, 1, 0, 1, 0, 0]) # 1 = true match
hits = np.flatnonzero(ranked) + 1 # ranks of the true matches
print("28: rank-1", int(ranked[0]), "rank-5", int(ranked[:5].any()), "AP", np.mean(np.arange(1, len(hits) + 1) / hits))22: IoU 0.429 Dice 0.6
24: [103, 106]
25: MOTA 0.86
27: P(at least one false match in 10000) 0.632
28: rank-1 0 rank-5 1 AP 0.5
Putting it together
29. Design a pipeline. A shop wants to know how many people enter per hour through one door, from a ceiling camera, and must not store anything that identifies a person. Sketch the pipeline and its evaluation.
Answer
Detect people per frame (a COCO person detector such as YOLO; from above, check it on your own footage, because COCO is mostly side views), track them with SORT (tracking), and count tracks that cross a virtual line in the entering direction (video analytics). Keep only counts and timestamps; no frames, crops, faces or embeddings, and no re-identification. Evaluate on hand-counted hours across lighting and crowding conditions: count error per hour, plus missed and double counts at busy times, and say how many hours were checked. Document the purpose and retention (privacy).
30. Read a result critically. A team reports "our detector reaches 0.95 mAP". List four questions you ask before believing it matters for your use.
Answer
Which mAP (VOC @0.5 or COCO @[.5:.95]) (detection metrics)? On which test set, and is it from the same cameras, places and time as deployment, or split by source so no near-duplicates leak (split strategies)? Per class and per size: are the small or rare objects you care about inside the average? Was anything tuned on the test set, and how large is it (the uncertainty of the number)? The mini project shows a 0.985 that becomes 0.612 on the deployment camera.
Test yourself
A kernel with stride 1 and no padding runs over a image. What is the output size?
Which box is the YOLO line 0 0.5 0.5 0.2 0.4 in a 100 x 50 image (width x height), as ?
NMS with IoU threshold 0.5 keeps two boxes on the same object whose IoU is 0.45. How is the second one counted in AP?
- As a true positive
- As a false positive, because the object is already matched
- It is ignored
- As a false negative
Which metric best rewards a tracker for keeping the same id on the same person for the whole sequence?
- MOTA
- IDF1
- Pixel accuracy
- mAP@0.5
Why can a pretrained ImageNet classifier give poor predictions without any error message?
- It only accepts JPEG files
- Wrong preprocessing (BGR order, 0-255 range, missing normalisation) produces valid tensors that the network does not expect
- It needs a GPU
- ImageNet has only 10 classes