Tuesday , December 1 2026
Object detection explained: IoU and NMS implemented in tested NumPy, detection and custom training with Ultralytics YOLO26, mAP evaluation and detector families.

Object Detection with YOLO in Python (IoU, NMS and YOLO26)

Updated: 29 November 2026Level: IntermediateReading time: about 11 minutesNumPy · tested + Ultralytics YOLO26

Object detection finds where objects are in an image and what they are, drawing a labelled bounding box around each. It powers traffic cameras, retail shelf monitoring, crop inspection and self-driving cars. YOLO (“You Only Look Once”) is the most popular real-time family of detectors.

What You Will Learn

  • Classification vs detection vs segmentation
  • Intersection over Union (IoU)
  • Non-Maximum Suppression (NMS) in NumPy
  • Detect objects with Ultralytics YOLO26
  • Train on your own dataset and evaluate with mAP

Prerequisites

Image Classification, CNN.

Vision Tasks

Task Output Example
Classification One label per image “Car”
Detection Boxes + labels + scores 3 cars, 1 bus with coordinates
Segmentation Label for every pixel – see Image Segmentation Exact car outline
Pose / keypoints Body or object keypoints Player skeleton in sports

IoU: How Good Is a Box?

Example
def iou(a, b):                                   # boxes as [x1, y1, x2, y2]
    x1, y1 = max(a[0], b[0]), max(a[1], b[1])
    x2, y2 = min(a[2], b[2]), min(a[3], b[3])
    inter = max(0, x2 - x1) * max(0, y2 - y1)
    union = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    return inter / union

print(round(iou([50, 50, 150, 150], [60, 60, 170, 160]), 3),
      round(iou([50, 50, 150, 150], [200, 200, 250, 250]), 3))
Output
0.628 0.0

Explanation: IoU = overlap area ÷ combined area. A prediction usually counts as correct if IoU ≥ 0.5 with a ground-truth box of the same class. Non-overlapping boxes score 0.

NMS: Remove Duplicate Boxes

Example
import numpy as np
boxes = np.array([[50, 50, 150, 150], [55, 48, 152, 155], [60, 60, 170, 160],
                  [300, 80, 380, 200], [305, 85, 385, 190]], float)
scores = np.array([0.92, 0.85, 0.60, 0.88, 0.70])

def nms(boxes, scores, th=0.5):
    order = scores.argsort()[::-1]                 # highest score first
    keep = []
    while len(order):
        i = order[0]
        keep.append(int(i))
        order = np.array([j for j in order[1:] if iou(boxes[i], boxes[j]) < th])
    return keep

print(nms(boxes, scores))
Output
[0, 3]

Explanation: Detectors often predict several overlapping boxes for one object. NMS keeps the highest-scoring box and removes others that overlap it by more than the IoU threshold. Five raw boxes become two objects. (YOLO26 is designed to be NMS-free end-to-end, but NMS is still used by many other detectors.)

Detect with YOLO26

Ultralytics (not run here – downloads weights)
# pip install ultralytics
from ultralytics import YOLO
model = YOLO("yolo26n.pt")                        # nano model pre-trained on COCO (80 classes)
results = model("street.jpg", conf=0.4)
for box in results[0].boxes:
    print(model.names[int(box.cls)], round(float(box.conf), 2), box.xyxy[0].tolist())
results[0].save("street_detected.jpg")            # image with boxes drawn

# webcam / video:  model.predict(source=0, show=True)

Explanation: Each result lists the class name, confidence and box corners. Model sizes run from n (nano, fastest) through s, m, l to x (most accurate). YOLO11 remains a mature alternative; check the Ultralytics docs for the current recommended model.

Train on Your Own Data

Custom training (not run here – use a GPU, e.g. Colab)
# data.yaml
# path: datasets/helmets
# train: images/train
# val: images/val
# names: {0: helmet, 1: no_helmet}

from ultralytics import YOLO
model = YOLO("yolo26n.pt")                       # start from pre-trained weights
model.train(data="data.yaml", epochs=50, imgsz=640, batch=16)
metrics = model.val()
print(metrics.box.map50, metrics.box.map)        # mAP@0.5 and mAP@0.5:0.95
model.export(format="onnx")                      # deploy anywhere

Explanation: Label images with tools like CVAT, Label Studio or Roboflow; YOLO format stores one text line per box: class x_center y_center width height (normalised 0–1). A few hundred well-labelled images per class plus augmentation often give a useful first model.

Evaluation: mAP

Metric Meaning
Precision / recall Computed at an IoU threshold, per class
AP Area under the precision–recall curve for one class
mAP@0.5 Mean AP over classes at IoU 0.5
mAP@0.5:0.95 Average over IoU 0.5–0.95 – stricter, the COCO standard

Detector Families

Family Type Notes
YOLO (Ultralytics) One-stage Fast, easy, real-time
RT-DETR / DETR Transformer End-to-end, strong accuracy
Faster R-CNN Two-stage Accurate, slower
Grounding DINO, YOLO-World/YOLOE Open-vocabulary Detect objects named in text prompts
Note: Ultralytics YOLO is licensed under AGPL-3.0; commercial closed-source use needs an enterprise licence. Check licences of models and datasets before deploying.

Earlier OpenCV projects on this site: vehicle detection in images and in video.

Series

Computer vision series: OpenCV Intro · Image Processing · Image Classification · Data Augmentation · CNN · Transfer Learning · Object Detection (YOLO) · Image Segmentation · OCR · Face Detection

Interview Questions

Q: What is IoU?
Intersection area divided by union area of two boxes; measures localisation quality.

Q: Why is NMS needed?
To remove duplicate overlapping predictions for the same object.

Q: What is mAP@0.5:0.95?
Mean average precision averaged over IoU thresholds from 0.5 to 0.95.

Practice Exercises

  1. Run YOLO26n on five photos of your street and count vehicles by class.
  2. Label 100 images of a custom object and fine-tune for 30 epochs.

Summary

Detectors output boxes, labels and scores. IoU measures box quality, NMS removes duplicates and mAP evaluates models. Ultralytics YOLO makes detection and custom training a few lines of code.

Next: Image Segmentation

About Machine Learning

Check Also

Image Data Augmentation: Why It Works (Tested Python Demo)

Image data augmentation explained with a tested demo where shifting digits drops accuracy to 52% and augmentation restores 99%, plus Keras and Albumentations code.