TExcelTAD

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: 200+100=300→44200 + 100 = 300 \to 44, 200−100=100200 - 100 = 100, 100−200=−100→156100 - 200 = -100 \to 156. 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 (R,G,B)=(200,100,50)(R, G, B) = (200, 100, 50). Compute its grey value with OpenCV's weights 0.299R+0.587G+0.114B0.299R + 0.587G + 0.114B. 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

0.299⋅200+0.587⋅100+0.114⋅50=59.8+58.7+5.7=124.20.299 \cdot 200 + 0.587 \cdot 100 + 0.114 \cdot 50 = 59.8 + 58.7 + 5.7 = 124.2. With the wrong order the stored values (50,100,200)(50, 100, 200) (B, G, R) are read as R, G, B: 0.299⋅50+0.587⋅100+0.114⋅200=14.95+58.7+22.8=96.450.299 \cdot 50 + 0.587 \cdot 100 + 0.114 \cdot 200 = 14.95 + 58.7 + 22.8 = 96.45. 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 3×33 \times 3 kernel slides over a 12×1212 \times 12 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 5×55 \times 5 kernel and stride 2 without padding?

Answer

Output side =⌊(n+2p−k)/s⌋+1= \lfloor (n + 2p - k)/s \rfloor + 1: (12−3)/1+1=10(12 - 3)/1 + 1 = 10; with p=1p = 1, 1212; for k=5,s=2k = 5, s = 2: ⌊7/2⌋+1=4\lfloor 7/2 \rfloor + 1 = 4. 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 [−101−202−101]\begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix} 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 1+2+1=41 + 2 + 1 = 4. Column 2: left 0, right 10, so 4⋅(10−0)=404 \cdot (10 - 0) = 40. 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 640×480640 \times 480 image (width by height) is letterboxed to 320×320320 \times 320: scaled to fit, then padded equally top and bottom. A box is [100,50,300,250][100, 50, 300, 250] in the original. Where is it in the letterboxed image?

Answer

Scale =min⁡(320/640,320/480)=0.5= \min(320/640, 320/480) = 0.5, so the image becomes 320×240320 \times 240 and is padded by (320−240)/2=40(320 - 240)/2 = 40 pixels at the top and bottom. Box: xx values times 0.5, yy values times 0.5 plus 40: [50,65,150,165][50, 65, 150, 165]. To map predictions back, subtract the padding first, then divide by the scale (resizing and geometry).

8. HOG size. skimage.feature.hog on a 32×3232 \times 32 grey image with 9 orientations, 8×88 \times 8 pixel cells and 2×22 \times 2 cell blocks: how many numbers does it return?

Answer

4×44 \times 4 cells, so 3×33 \times 3 overlapping block positions, each with 2⋅2⋅9=362 \cdot 2 \cdot 9 = 36 numbers: 9⋅36=3249 \cdot 36 = 324 (classical features).

Check exercises 1, 2, 4, 5 and 8:

python · try it yourself
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 [x1,y1,x2,y2]=[40,30,100,90][x_1, y_1, x_2, y_2] = [40, 30, 100, 90] in a 200×120200 \times 120 image (width by height). Write it as a COCO bbox and as a YOLO line for class 2.

Answer

COCO: [x,y,w,h]=[40,30,60,60][x, y, w, h] = [40, 30, 60, 60]. YOLO: centre (70,60)(70, 60), normalised by width 200 and height 120: 2 0.35 0.5 0.3 0.5. Normalising yy values by the width is the classic bug (box formats).

10. COCO RLE. A 3×33 \times 3 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 [3,2,1,1,2][3, 2, 1, 1, 2]. Row-major order would give a different, wrong encoding (masks and RLE).

11. Agreement. Two annotators draw boxes [10,10,50,50][10, 10, 50, 50] and [14,12,54,52][14, 12, 54, 52] for the same object. What is their IoU, and would this pass a 0.7 agreement threshold?

Answer

Intersection [14,12,50,50][14, 12, 50, 50]: 36⋅38=136836 \cdot 38 = 1368. Each box has area 16001600; union 3200−1368=18323200 - 1368 = 1832; IoU ≈0.747\approx 0.747, 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).

python · try it yourself
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 3×33 \times 3 convolution from 64 to 128 channels have (with bias)? And a depthwise separable version (3×33 \times 3 depthwise on 64 channels, then 1×11 \times 1 to 128, both with bias)?

Answer

Standard: 3⋅3⋅64⋅128+128=73,8563 \cdot 3 \cdot 64 \cdot 128 + 128 = 73{,}856. Depthwise: 3⋅3⋅64+64=6403 \cdot 3 \cdot 64 + 64 = 640; pointwise: 64⋅128+128=8,32064 \cdot 128 + 128 = 8{,}320; total 8,9608{,}960, 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 224×224224 \times 224 input and for a 640×640640 \times 640 input, and what does that mean for a 20-pixel object?

Answer

7×77 \times 7 and 20×2020 \times 20. 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 (0.485,0.456,0.406)(0.485, 0.456, 0.406) and divide by the standard deviation (0.229,0.224,0.225)(0.229, 0.224, 0.225) 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 [0,0,10,10][0, 0, 10, 10] score 0.9, B [1,1,11,11][1, 1, 11, 11] score 0.8, C [20,0,30,10][20, 0, 30, 10] score 0.7. Which survive NMS at IoU threshold 0.5? And at 0.7?

Answer

IoU(A, B): intersection 9⋅9=819 \cdot 9 = 81, union 200−81=119200 - 81 = 119, ≈0.681\approx 0.681. IoU(A, C) =0= 0. 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 (50,50)(50, 50), width 40, height 20. A ground-truth box has centre (54,48)(54, 48), width 60, height 20. Compute (tx,ty,tw,th)(t_x, t_y, t_w, t_h) with tx=(x−xa)/wat_x = (x - x_a)/w_a, ty=(y−ya)/hat_y = (y - y_a)/h_a, tw=ln⁡(w/wa)t_w = \ln(w/w_a), th=ln⁡(h/ha)t_h = \ln(h/h_a).

Answer

tx=4/40=0.1t_x = 4/40 = 0.1, ty=−2/20=−0.1t_y = -2/20 = -0.1, tw=ln⁡1.5≈0.405t_w = \ln 1.5 \approx 0.405, th=ln⁡1=0t_h = \ln 1 = 0. 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 640×640640 \times 640 input, YOLOv8 predicts at strides 8, 16 and 32, one prediction per grid cell. How many predictions is that?

Answer

802+402+202=6400+1600+400=840080^2 + 40^2 + 20^2 = 6400 + 1600 + 400 = 8400. 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).

python · try it yourself
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 =60/(100+100−60)=60/140≈0.429= 60 / (100 + 100 - 60) = 60/140 \approx 0.429; Dice =2⋅60/(100+100)=0.6= 2 \cdot 60 / (100 + 100) = 0.6. Dice is always at least IoU for the same masks, Dice=2 IoU/(1+IoU)\text{Dice} = 2\,\text{IoU}/(1 + \text{IoU}) (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 x=100x = 100 with velocity v=3v = 3 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

x=103x = 103, then 106106: 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=1−(15+10+3)/200=1−0.14=0.86\text{MOTA} = 1 - (15 + 10 + 3)/200 = 1 - 0.14 = 0.86. 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 S(x,y)=∑x′<x, y′<yI(x′,y′)S(x, y) = \sum_{x' < x,\, y' < y} I(x', y'), any rectangle sum is S(D)−S(B)−S(C)+S(A)S(D) - S(B) - S(C) + S(A) 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 10−410^{-4} gives about one false match per probe on average (1−(1−10−4)10000≈0.631 - (1 - 10^{-4})^{10000} \approx 0.63 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 1/21/2 and 2/42/4, so AP =(0.5+0.5)/2=0.5= (0.5 + 0.5)/2 = 0.5. CMC rewards finding one match early; mAP rewards ranking all of them high (person re-ID).

python · try it yourself
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 3×33 \times 3 kernel with stride 1 and no padding runs over a 28×2828 \times 28 image. What is the output size?

  1. 28×2828 \times 28
  2. 26×2626 \times 26
  3. 25×2525 \times 25
  4. 14×1414 \times 14

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 [x1,y1,x2,y2][x_1, y_1, x_2, y_2]?

  1. [40,15,60,35][40, 15, 60, 35]
  2. [40,40,60,60][40, 40, 60, 60]
  3. [45,20,55,30][45, 20, 55, 30]
  4. [50,25,70,45][50, 25, 70, 45]

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?

  1. As a true positive
  2. As a false positive, because the object is already matched
  3. It is ignored
  4. As a false negative

Which metric best rewards a tracker for keeping the same id on the same person for the whole sequence?

  1. MOTA
  2. IDF1
  3. Pixel accuracy
  4. mAP@0.5

Why can a pretrained ImageNet classifier give poor predictions without any error message?

  1. It only accepts JPEG files
  2. Wrong preprocessing (BGR order, 0-255 range, missing normalisation) produces valid tensors that the network does not expect
  3. It needs a GPU
  4. ImageNet has only 10 classes