Object detection and tracking
UAT 456 Artificial Intelligence, Machine Learning and Computer Vision for UAS
Lesson
By the end of this module you will be able to
- Explain object detection from sliding windows with a classifier to one-stage detectors in the YOLO family
- Convert boxes from tiles to full-image coordinates and merge duplicates with IoU and IoS
- Match tracks to detections with the Hungarian method on an IoU matrix and explain the track life cycle
- Count objects crossing a count line without double counting even when track IDs break
- Explain the tracking metrics MOTA, IDF1 and HOTA
Why this matters
The farm needs two numbers every day. The first is the number of cattle in each paddock, from still images. The second is the number of cattle passing through the pen gate when the herd is brought in each evening, from video taken by a hovering drone. The first task must detect every animal without double counting where tiles overlap; the second must know that a cow in this frame is the same one as in the last frame so it is not counted twice. This module builds on UAT 307, which taught the Kalman filter and MOTA, and focuses on what makes counting go wrong in the field.
From classification to detection
Object detection must give both the class and the location of every object in an image, as a box with a confidence score. The classical approach slides windows of several sizes across the image and lets a module 2 classifier judge each one, which is how Dalal and Triggs used HOG. It is slow because tens of thousands of windows must be classified.
One-stage detectors such as YOLO use a single network to predict boxes and class probabilities from the whole image in one pass, so they are fast enough for video (Redmon et al., 2016). Current models such as YOLO11 and YOLO26 come in several sizes to trade speed against accuracy (Ultralytics). Two-stage detectors first propose regions likely to hold objects and then classify each one; they are often more accurate but slower. Either way the raw output has several overlapping boxes per object, which are cut with a minimum confidence and non-maximum suppression (NMS), as taught in UAT 306 module 4.
Merging results from overlapping tiles
When an image is tiled (module 1), boxes come out in tile coordinates; adding the tile’s top-left corner converts them to full-image coordinates, and then duplicates in the overlap must be merged. The problem is that a cow cut by a tile edge yields a half box in one tile and a full box in the other. Their may fall below the NMS threshold even though it is the same animal. IoS (intersection over smaller) is therefore preferred, since it equals 1 when the small box lies entirely inside the large one. This kind of merging is used in slicing-based small-object detection (Akyon et al., 2022).
Example 1 Is one cow counted twice?
Tile A has its top-left corner at (0, 0) and tile B at (512, 0). The detector returns four boxes; tile A’s second box is cut by the tile’s right edge (assumed).
# merge boxes from overlapping tiles into full-image coordinates and remove duplicates (assumed values)
def inter(a, b):
return max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(0, min(a[3], b[3]) - max(a[1], b[1]))
def area(a): return (a[2] - a[0]) * (a[3] - a[1])
def iou(a, b): return inter(a, b) / (area(a) + area(b) - inter(a, b))
def ios(a, b): return inter(a, b) / min(area(a), area(b)) # intersection over smaller
offset = {"A": (0, 0), "B": (512, 0)} # top-left corner of each tile in the full image
dets = [("A", (300, 200, 380, 232), 0.91), ("A", (596, 100, 640, 130), 0.62),
("B", (78, 98, 160, 131), 0.88), ("B", (300, 400, 332, 480), 0.85)]
boxes = []
for t, (x1, y1, x2, y2), s in dets:
ox, oy = offset[t]
boxes.append(((x1 + ox, y1 + oy, x2 + ox, y2 + oy), s))
print("global boxes:", [b for b, s in boxes])
print(f"cut box vs full box: IoU {iou(boxes[1][0], boxes[2][0]):.3f}, IoS {ios(boxes[1][0], boxes[2][0]):.3f}")
def merge(boxes, overlap, thr):
keep = []
for b, s in sorted(boxes, key=lambda x: -x[1]): # highest score first
if all(overlap(b, k) < thr for k, _ in keep):
keep.append((b, s))
return keep
print("cows with NMS IoU 0.5:", len(merge(boxes, iou, 0.5)))
print("cows with IoS 0.6 :", len(merge(boxes, ios, 0.6)))
global boxes: [(300, 200, 380, 232), (596, 100, 640, 130), (590, 98, 672, 131), (812, 400, 844, 480)]
cut box vs full box: IoU 0.488, IoS 1.000
cows with NMS IoU 0.5: 4
cows with IoS 0.6 : 3
The half box (596, 100, 640, 130) and the full box (590, 98, 672, 131) are the same cow, but their IoU is only 0.488, below the 0.5 NMS threshold, so 4 cows are counted. With IoS, which is 1.000 because the half box lies entirely inside the full box, the system keeps 3 cows, which is correct. This error hits every animal standing across a tile edge, and an image has 77 tiles, so left unfixed it inflates the count systematically. Beware that too low an IoS threshold can merge two cows standing on top of each other into one, so choose the threshold on the validation set.
Consecutive still images overlap too: one cow may appear in two neighbouring images, and cattle move between shots. Barbedo et al. (2020) therefore used image matching to account for overlap between images when counting cattle. A simpler practical approach is to convert boxes to ground coordinates and merge boxes closer together than the distance a cow could walk in the time between the two images.
Tracking by detection
Tracking by detection runs the detector on every frame and matches new boxes to existing tracks. SORT (Bewley et al., 2016) is a simple, fast model with four steps per frame:
- Predict each track’s box in this frame with a Kalman filter (UAT 307 module 3)
- Associate tracks with detected boxes by building an IoU matrix between predicted and detected boxes and finding the matching with the highest total IoU
- Update matched tracks with their new boxes
- Manage the life cycle: a box with no track starts a new tentative track (confirmed after several consecutive hits); a track with no box for more than a set number of frames is deleted
The simplest matching picks the highest-IoU pair first, one pair at a time (greedy), but a good early choice can leave another track without a partner. The Hungarian method finds the one-to-one matching with the best total over the whole set in polynomial time (Kuhn, 1955); in SciPy it is linear_sum_assignment (SciPy developers).
Example 2 Two cows walking side by side into the pen
Tracks T1 and T2 have predicted boxes; the new frame has detections D1 and D2. The team sets a minimum IoU of 0.3 (assumed) and uses the iou function from Example 1.
import numpy as np
from scipy.optimize import linear_sum_assignment
# predicted boxes of two tracks and two detections in the new frame (two cows walking close together)
tracks = {"T1": (300, 200, 380, 232), "T2": (300, 212, 380, 244)}
dets = {"D1": (298, 208, 378, 240), "D2": (292, 218, 372, 250)}
M = np.array([[iou(t, d) for d in dets.values()] for t in tracks.values()])
print("IoU matrix (rows T1 T2, columns D1 D2):")
print(np.round(M, 3))
min_iou = 0.3
used, greedy = set(), {}
for v, i, j in sorted(((M[i, j], i, j) for i in range(2) for j in range(2)), reverse=True):
if v >= min_iou and i not in greedy and j not in used:
greedy[i] = j; used.add(j)
print("greedy :", {f"T{i + 1}": f"D{j + 1}" for i, j in greedy.items()}, "total", round(sum(M[i, j] for i, j in greedy.items()), 3))
r, c = linear_sum_assignment(M, maximize=True)
ok = [(i, j) for i, j in zip(r, c) if M[i, j] >= min_iou]
print("Hungarian:", {f"T{i + 1}": f"D{j + 1}" for i, j in ok}, "total", round(sum(M[i, j] for i, j in ok), 3))
IoU matrix (rows T1 T2, columns D1 D2):
[[0.576 0.245]
[0.744 0.576]]
greedy : {'T2': 'D1'} total 0.744
Hungarian: {'T1': 'D1', 'T2': 'D2'} total 1.153
Greedy matching takes T2 with D1 first because 0.744 is the highest IoU. T1 is then left with only D2 at 0.245, below the threshold, so T1 gets no match and D2 starts a new track: the same cow gets a new number, an ID switch. The Hungarian method pairs T1 with D1 and T2 with D2 for a total of 1.153, and every track is matched. Here the two cows move in almost the same way, so the tracks continue; the closer the animals walk, the more whole-set matching matters.
When animals crowd and hide each other for long periods, IoU alone is not enough, so newer systems add appearance features of each animal (such as coat colour and markings) to the matching cost; the principle of predict, associate, update and manage the life cycle stays the same.
Counting with a count line
Counting the number of track IDs ever seen looks easy, but every broken ID inflates the total. A sturdier method places a count line across the path and counts tracks whose centre crosses it in the chosen direction, once per track. A cow loitering on the line is not counted again, and an ID that breaks before reaching the line does not inflate the count because the old ID never crosses.
Example 3 Four cows pass the gate; the system sees six IDs
Cows A to D walk down across a count line at row y = 360 pixels. Cows B and D are briefly hidden and get new IDs; cow C loiters on the line (assumed).
# count cattle crossing the count line at row y = 360 px from tracks (first frame seen, centre y in every frame)
line = 360
tracks = {1: (0, [300, 330, 350, 372, 395, 420]),
2: (0, [250, 280, 310]), # cow B lost behind another animal
3: (1, [340, 355, 362, 358, 366, 380]), # cow C loiters on the line
4: (2, [200, 240, 290]), # cow D lost behind another animal
5: (5, [352, 368, 390, 410]), # cow B returns with a new ID
6: (6, [330, 350, 371, 395])} # cow D returns with a new ID
def crossings(ys): return sum(1 for a, b in zip(ys, ys[1:]) if a < line <= b)
print("unique track IDs :", len(tracks))
print("every downward crossing :", sum(crossings(ys) for _, ys in tracks.values()))
counted = [tid for tid, (_, ys) in tracks.items() if crossings(ys) > 0]
print("count each ID once :", len(counted), "IDs", counted)
unique track IDs : 6
every downward crossing : 5
count each ID once : 4 IDs [1, 3, 5, 6]
Counting IDs gives 6, two too many because of broken IDs. Counting every downward crossing gives 5, because cow C crosses down twice (355 to 362 and 358 to 366). Counting each track once gives 4, which is correct: IDs 2 and 4 vanish before the line and are not counted, while IDs 5 and 6, which are cows B and D, cross and are counted instead. The case this method still misses is an ID breaking exactly as the animal crosses: the new ID starts below the line and is never counted. Real systems therefore use a two-line band, or count tracks that were once above the band and end below it.
Measuring tracking quality
A good detector does not guarantee good tracking, because tracking can fail in detection or in association. Three metrics are common:
| Metric | What it measures | Watch out |
|---|---|---|
| MOTA | Misses, false boxes and ID switches combined, relative to the number of real objects (Bernardin and Stiefelhagen, 2008) | Dominated by detection; ID switches barely affect it |
| IDF1 | Share of boxes given the correct ID consistently along the track | Emphasises ID continuity |
| HOTA | Geometric mean of detection accuracy DetA and association accuracy AssA, , averaged over localisation thresholds (Luiten et al., 2021) | Balances detection and association |
Counting cattle through a gate depends heavily on ID continuity, so report IDF1 or HOTA alongside MOTA, together with the error in the final count (module 5), because that number is what users care about most.
Evaluating a detector: precision, recall and average precision
A detector returns boxes with confidence scores, so one precision and one recall value cannot summarise it: both change with the confidence cut-off. The standard summary walks down the detections from the most to the least confident. A detection is a true positive if its IoU with a cow not yet claimed is above a threshold (0.5 by default in the PASCAL VOC protocol) and a false positive otherwise, including a second box on a cow already claimed (Detectron2, n.d.). After each detection the running precision and recall are noted, which draws the precision-recall curve. Average precision (AP) is the area under that curve after each precision is replaced by the best precision at the same or a higher recall, which equals the sum of the recall increases weighted by precision (scikit-learn, n.d.; Detectron2, n.d.). The COCO evaluation reports AP at an IoU of 0.50, at 0.75 and averaged over ten thresholds from 0.50 to 0.95, and splits objects by area in pixels into small (below 32²), medium (up to 96²) and large (pycocotools, n.d.). It samples recall at 101 points, so its values can differ slightly from the area method used here. With several classes, AP is averaged over the classes to give mean AP.
Example 4 Is the cattle detector as good at a strict IoU?
One test tile holds five cows. The detector returns seven boxes with confidence scores (assumed). Boxes 3, 6 and 7 are shifted by 5 to 10 pixels, box 4 is a second box on the cow of box 1, and box 5 lies on bare soil.
def box_iou(p, q):
ix = max(0, min(p[2], q[2]) - max(p[0], q[0]))
iy = max(0, min(p[3], q[3]) - max(p[1], q[1]))
inter = ix * iy
area = lambda r: (r[2] - r[0]) * (r[3] - r[1])
return inter / (area(p) + area(q) - inter)
def match(dets, gts, thr):
"""Go down the detections by confidence; a box is TP if it overlaps an unclaimed cow by more than thr."""
claimed, flags = set(), []
for conf, box in sorted(dets, key=lambda d: -d[0]):
j, best = max(((j, box_iou(box, g)) for j, g in enumerate(gts)), key=lambda t: t[1])
hit = best > thr and j not in claimed # a second box on a claimed cow is a false positive
if hit:
claimed.add(j)
flags.append(hit)
return flags
def curve(flags, n_gt):
tp = fp = 0
rec, pre = [], []
for hit in flags:
tp, fp = tp + hit, fp + (not hit)
rec.append(tp / n_gt)
pre.append(tp / (tp + fp))
return rec, pre
def average_precision(flags, n_gt):
rec, pre = curve(flags, n_gt)
rec, pre = [0.0] + rec + [1.0], [0.0] + pre + [0.0]
for i in range(len(pre) - 2, -1, -1): # envelope: best precision at this recall or higher
pre[i] = max(pre[i], pre[i + 1])
return sum((rec[i + 1] - rec[i]) * pre[i + 1] for i in range(len(rec) - 1))
gts = [(100, 100, 180, 132), (300, 150, 380, 182), (500, 300, 580, 332), (120, 400, 200, 432), (420, 420, 500, 452)]
dets = [(0.95, (102, 101, 182, 134)), (0.90, (298, 152, 379, 181)), (0.85, (505, 305, 585, 337)),
(0.80, (101, 102, 181, 135)), (0.70, (700, 50, 780, 82)), (0.65, (125, 405, 205, 437)),
(0.55, (430, 430, 510, 462))]
flags = match(dets, gts, 0.5)
rec, pre = curve(flags, len(gts))
print("outcome :", " ".join("TP" if f else "FP" for f in flags))
print("recall :", " ".join(f"{r:.2f}" for r in rec))
print("precision:", " ".join(f"{p:.2f}" for p in pre))
for thr in (0.5, 0.75):
print(f"AP at IoU > {thr}: {average_precision(match(dets, gts, thr), len(gts)):.3f}")
aps = [average_precision(match(dets, gts, 0.5 + 0.05 * k), len(gts)) for k in range(10)]
print(f"mean over IoU 0.50 to 0.95: {sum(aps) / len(aps):.3f}")
outcome : TP TP TP FP FP TP FP
recall : 0.20 0.40 0.60 0.60 0.60 0.80 0.80
precision: 1.00 1.00 1.00 0.75 0.60 0.67 0.57
AP at IoU > 0.5: 0.733
AP at IoU > 0.75: 0.400
mean over IoU 0.50 to 0.95: 0.453
At an IoU of 0.5 the AP is 0.733: the duplicate (rank 4) and the soil box (rank 5) pull precision down before the sixth box finds a fourth cow, and the seventh box misses the fifth cow because its IoU is only 0.43. At 0.75 the AP falls to 0.400, since only the two accurately placed boxes count, and the mean over 0.50 to 0.95 is 0.453. A detector that finds the same cows with looser boxes therefore scores well at 0.5 and poorly on the strict average. Head counting needs the loose threshold and duplicate control; measuring a cow’s size from its box does not. A cow covers 2,560 px² here, which COCO calls medium; had the whole image been shrunk to 640 pixels (module 1) it would cover about 35 px², small, the case that tiling is meant to avoid.
Module lab
Lab: detecting, tracking and counting in drone video
- Train or use a YOLO-family detector you have the right to use on the module 1 images, both by shrinking whole images and by tiling, and compare the number of boxes
- Merge tile boxes with the code in Example 1, try several IoU and IoS thresholds, and compare the count with a count made by eye
- Record or use a sample video of people or vehicles passing a point in the training area (without identifying individuals), run the detector on every frame and match with the Hungarian method from Example 2
- Count with a count line as in Example 3 and compare with counting IDs and counting by eye
- Log the events where IDs break and propose one fix
Common mistakes
Watch out
- Forgetting to add the tile’s corner coordinates, so every box piles up in the top-left of the image
- Merging tile boxes with IoU-based NMS alone, so half boxes survive and the count is too high
- Matching tracks greedily when objects are close together, causing ID switches
- Counting the number of track IDs, which grows with every broken ID
- Counting every line crossing, so loitering objects are counted again
- Reporting only MOTA, which barely reflects ID switches
Summary
- Detectors give a class, a box and a confidence; one-stage detectors such as YOLO are fast enough for video
- Tile boxes must be converted to full-image coordinates, and half and full boxes merged with IoS
- Tracking by detection has four steps: predict, associate, update and manage the track life cycle
- The Hungarian method finds the matching with the highest total IoU, reducing ID switches when objects are close
- Count with a count line once per track, and measure tracking with IDF1 or HOTA as well as MOTA
Check your understanding
- A tile’s top-left corner is at (1024, 512) and a box in the tile is (10, 20, 90, 52). What is it in full-image coordinates?
- Box A, 40 wide and 30 high, lies entirely inside box B, 80 wide and 33 high. What are IoU and IoS?
- An IoU matrix has row T1 = 0.9, 0.8 and row T2 = 0.7, 0.1 (columns D1, D2). With a 0.3 minimum, what do greedy and Hungarian matching give?
- Why does counting each track once at the line not over-count when an ID breaks before the line?
- A system has DetA 0.81 and AssA 0.64. What is HOTA?
Answers
- IoU and IoS
- Greedy: T1 with D1 (0.9), then T2 is left with D2 at 0.1, below the threshold, so T2 is unmatched. Hungarian: T1 with D2 (0.8) and T2 with D1 (0.7), total 1.5, more than 0.9, and every track is matched
- The old ID disappears before crossing and is not counted; the new ID crosses once and is counted once, so the animal is counted exactly once
Key formulas
| Intersection over union | |
| Intersection over smaller box | |
| Best assignment | |
| HOTA |
Key references
- Redmon, J., Divvala, S., Girshick, R., & Farhadi, A. (2016). You only look once: Unified, real-time object detection. In Proceedings of CVPR 2016 (pp. 779–788). link
- Ultralytics. Models supported by Ultralytics (YOLO11, YOLO26). Ultralytics documentation. link
- Dalal, N., & Triggs, B. (2005). Histograms of oriented gradients for human detection. In 2005 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'05) (Vol. 1, pp. 886–893). IEEE. https://doi.org/10.1109/CVPR.2005.177 link
- Akyon, F. C., Altinuc, S. O., & Temizel, A. (2022). Slicing aided hyper inference and fine-tuning for small object detection. In 2022 IEEE International Conference on Image Processing (ICIP) (pp. 966–970). IEEE. https://doi.org/10.1109/ICIP46576.2022.9897990 link
- Bewley, A., Ge, Z., Ott, L., Ramos, F., & Upcroft, B. (2016). Simple online and realtime tracking. In 2016 IEEE International Conference on Image Processing (pp. 3464–3468). link
- Kuhn, H. W. (1955). The Hungarian method for the assignment problem. Naval Research Logistics Quarterly, 2(1–2), 83–97. link
- SciPy developers. scipy.optimize.linear_sum_assignment. SciPy v1.18 reference guide. link
- Luiten, J., Ošep, A., Dendorfer, P., Torr, P., Geiger, A., Leal-Taixé, L., & Leibe, B. (2021). HOTA: A higher order metric for evaluating multi-object tracking. International Journal of Computer Vision, 129(2), 548–578. https://doi.org/10.1007/s11263-020-01375-2 link
- Bernardin, K., & Stiefelhagen, R. (2008). Evaluating multiple object tracking performance: The CLEAR MOT metrics. EURASIP Journal on Image and Video Processing, 2008, 246309. link
- Barbedo, J. G. A., Koenigkan, L. V., Santos, P. M., & Ribeiro, A. R. B. (2020). Counting cattle in UAV images: Dealing with clustered animals and animal/background contrast changes. Sensors, 20(7), 2126. https://doi.org/10.3390/s20072126 link
- scikit-learn developers. (n.d.). sklearn.metrics.average_precision_score. scikit-learn documentation. link
- Meta AI Research. (n.d.). pascal_voc_evaluation.py (voc_eval, voc_ap) [Source code]. Detectron2, GitHub. link
- COCO Consortium. (n.d.). cocoeval.py (COCOeval) [Source code]. cocoapi PythonAPI, GitHub. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
การวิเคราะห์วิดีโออัจฉริยะ
Training and evaluating object detection
Ultralytics YOLO
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results