YOLO26 Object Detection in Python with Ultralytics: Detect, Count, Track and Export (2026)

Python For Ai Engineers 2026 Nov 26, 2026

Watch on YouTube

Counting people in a shop camera, spotting cars in a parking lot, checking that workers wear helmets, sorting products on a conveyor belt or tagging thousands of photos: all of these are object detection jobs. The model looks at an image and returns every object it knows, with a class name, a confidence score and a bounding box. In 2026 the easiest way to do this in Python is the Ultralytics package and its newest model family, YOLO26, released in January 2026. YOLO26 removes Distribution Focal Loss from the detection head, adds an optional end-to-end head that works without non-maximum suppression (NMS), and is up to 43% faster on CPU than YOLO11 according to Ultralytics. In this tutorial we detect objects in an image, filter and count them, turn the results into plain Python data and a Polars DataFrame, compare YOLO11n, YOLO26n and YOLO26s on speed, track objects across a video, run segmentation and pose estimation, and export the model to ONNX. Everything ran on a normal CPU with Python 3.14.10, ultralytics 8.4.219 and PyTorch 2.15.0, and every output block below is the real output of the script above it.

Setup

Ultralytics needs PyTorch. On a machine without an NVIDIA GPU, install the CPU build of PyTorch first so pip does not download several gigabytes of CUDA libraries, then install Ultralytics. Python 3.11 to 3.14 all work. We also install the ONNX packages now, because otherwise Ultralytics tries to install them automatically the first time you export.

python3.14 -m venv .venv && source .venv/bin/activate
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
pip install ultralytics onnx onnxruntime onnxslim lap
yolo checks          # prints Ultralytics, Python, torch and hardware info

Model weights such as yolo26n.pt download automatically the first time you load them (the nano detection model is only 5.3 MB). The package also ships two test pictures, bus.jpg and zidane.jpg, in ultralytics/assets; we copied them into an images folder so every script below runs without your own photos. Set the environment variable YOLO_VERBOSE=False if you want to hide the Ultralytics log lines, which is what we did for the clean outputs below.

Step 1: Detect objects in an image

Load a model with YOLO(), call it on an image path, URL, NumPy array or Pillow image, and you get a list of Results, one per image. r.boxes holds the detections: cls is the class index, conf the confidence and xyxy the box corners in pixels. model.names maps the index to one of the 80 COCO class names.

from ultralytics import YOLO

model = YOLO("yolo26n.pt")                 # downloads the 5 MB nano model on first use
results = model("images/bus.jpg", verbose=False)
r = results[0]

print("image size:", r.orig_shape, "| objects found:", len(r.boxes))
for box in r.boxes:
    name = model.names[int(box.cls)]
    x1, y1, x2, y2 = box.xyxy[0].tolist()
    print(f"{name:<8} conf={float(box.conf):.2f}  box=({x1:.0f}, {y1:.0f}, {x2:.0f}, {y2:.0f})")

r.save(filename="output/bus_detected.jpg")   # image with boxes and labels drawn
print("speed (ms):", {k: round(v, 1) for k, v in r.speed.items()})
image size: (1080, 810) | objects found: 5
bus      conf=0.88  box=(0, 230, 803, 751)
person   conf=0.87  box=(49, 398, 240, 902)
person   conf=0.86  box=(223, 405, 345, 861)
person   conf=0.85  box=(670, 394, 810, 879)
person   conf=0.66  box=(0, 553, 60, 871)
speed (ms): {'preprocess': 2.2, 'inference': 37.3, 'postprocess': 1.0}

The nano model found the bus and four people, including the person who is cut off at the left edge (with a lower confidence of 0.66). Inference took about 37 ms on CPU for a 640 pixel input. r.save() writes the picture with coloured boxes and labels, and r.plot() returns the same picture as a NumPy array if you want to show it in a window or a notebook.

Step 2: Filter, count and export the results

Most real projects need only some classes and only confident detections. predict() takes conf (minimum confidence), classes (list of class indexes, 0 is person), iou and imgsz. A larger imgsz such as 960 helps with small objects at the cost of speed. To count objects, a Counter over the class names is all you need.

from collections import Counter
from ultralytics import YOLO

model = YOLO("yolo26n.pt")

# only people, only confident boxes, bigger input size for small objects
r = model.predict("images/bus.jpg", conf=0.5, classes=[0], imgsz=960, verbose=False)[0]
print("people with conf >= 0.5:", len(r.boxes))

# count every class in a picture
r = model("images/zidane.jpg", verbose=False)[0]
counts = Counter(model.names[int(c)] for c in r.boxes.cls)
print("zidane.jpg counts:", dict(counts))

# results as plain Python data (great for APIs, CSV or a database)
rows = r.summary()
print("first row keys:", list(rows[0].keys()))
print("first row:", {k: rows[0][k] for k in ("name", "class", "confidence")},
      "box:", {k: round(v) for k, v in rows[0]["box"].items()})
df = r.to_df()                       # a Polars DataFrame in Ultralytics 8.4
print(type(df).__module__.split(".")[0], df.shape)
print(df.select("name", df["confidence"].round(2)))
people with conf >= 0.5: 4
zidane.jpg counts: {'person': 2, 'tie': 1}
first row keys: ['name', 'class', 'confidence', 'box']
first row: {'name': 'person', 'class': 0, 'confidence': 0.89488} box: {'x1': 742, 'y1': 40, 'x2': 1151, 'y2': 709}
polars (3, 4)
shape: (3, 2)
┌────────┬────────────┐
│ name   ┆ confidence │
│ ---    ┆ ---        │
│ str    ┆ f64        │
╞════════╪════════════╡
│ person ┆ 0.89       │
│ person ┆ 0.85       │
│ tie    ┆ 0.58       │
└────────┴────────────┘

The person on the edge disappeared once we set conf=0.5, so we got four people. r.summary() returns a list of dictionaries that you can send straight back from an API or save as JSON, and r.to_df() now returns a Polars DataFrame in Ultralytics 8.4 (older tutorials show pandas, so methods like .round() on the whole frame no longer work; use Polars expressions). There are also to_json() and to_csv() helpers. If you want to accept photos from users and return these detections, combine this step with our FastAPI file upload tutorial.

Step 3: YOLO11 vs YOLO26 and NMS-free inference

Ultralytics offers each model in five sizes: n (nano), s, m, l and x. Bigger models are more accurate but slower. Here we warm up each model and then time 20 runs on the bus picture on our CPU.

import time
from ultralytics import YOLO

print(f"{'model':<12}{'objects':>8}{'avg ms':>9}")
for name in ("yolo11n.pt", "yolo26n.pt", "yolo26s.pt"):
    model = YOLO(name)
    model("images/bus.jpg", verbose=False)              # warm-up
    t = time.perf_counter()
    for _ in range(20):
        r = model("images/bus.jpg", verbose=False)[0]
    ms = (time.perf_counter() - t) / 20 * 1000
    print(f"{name:<12}{len(r.boxes):>8}{ms:>9.1f}")

# YOLO26 can skip NMS completely (end-to-end head)
r = YOLO("yolo26n.pt")("images/bus.jpg", nms=False, verbose=False)[0]
print("yolo26n end-to-end (nms=False) objects:", len(r.boxes))
model        objects   avg ms
yolo11n.pt         5     21.6
yolo26n.pt         5     21.0
yolo26s.pt         5     38.0
yolo26n end-to-end (nms=False) objects: 5

On this CPU, YOLO26n and YOLO11n ran at the same speed, about 21 ms per image after warm-up (Ultralytics measured YOLO26n faster on CPU ONNX, so test on your own hardware), while YOLO26s needed roughly 38 ms. All three found the same five objects in this easy picture. The official COCO numbers show why you might still pick a bigger model:

ModelCOCO mAP 50-95ParamsCPU ONNX ms (Ultralytics)Use it for
yolo26n40.92.4 M38.9CPU, Raspberry Pi, quick scripts
yolo26s48.69.5 M87.2better accuracy on a laptop
yolo26m53.120.4 M220.0GPU servers, small objects
yolo26l55.024.8 M286.2high accuracy on GPU
yolo26x57.555.7 M525.8best accuracy, offline batches

The last line of the script uses nms=False, the YOLO26 end-to-end mode. The one-to-one head gives one box per object directly, so there is no separate NMS step. That makes deployment simpler (for example on mobile or edge devices) and keeps latency stable when there are many objects. By default Ultralytics still uses the one-to-many head with NMS because it is slightly more accurate (40.9 vs 40.1 mAP for the nano model).

Step 4: Track objects in a video

Detection treats each frame on its own. Tracking gives every object an ID that stays the same from frame to frame, which you need for counting people who enter a door or cars that cross a line. We build a short test video with OpenCV by panning a 640 pixel window across the bus picture, then run model.track() with the ByteTrack tracker. stream=True returns a generator, so long videos do not fill your memory.

import cv2
from ultralytics import YOLO

# build a short test video: the camera pans across bus.jpg
img = cv2.imread("images/bus.jpg")                      # 810 x 1080
out = cv2.VideoWriter("images/pan.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 15, (640, 640))
for i in range(45):
    x, y = i * 3, 200 + i * 2
    out.write(img[y:y + 640, x:x + 640])
out.release()

model = YOLO("yolo26n.pt")
seen = {}
for r in model.track("images/pan.mp4", stream=True, persist=True, tracker="bytetrack.yaml", verbose=False):
    if r.boxes.id is None:
        continue
    for tid, c in zip(r.boxes.id.int().tolist(), r.boxes.cls.int().tolist()):
        seen[tid] = model.names[c]
print("frames processed: 45")
print("unique tracked objects:", len(seen))
print("by class:", {n: list(seen.values()).count(n) for n in sorted(set(seen.values()))})
frames processed: 45
unique tracked objects: 5
by class: {'bus': 1, 'person': 4}

Even though the camera moved in every frame, the tracker kept one ID per object: one bus and four people, so five unique objects instead of 45 times five detections. The same loop works with a webcam (source=0), an RTSP camera URL or a YouTube link. ByteTrack needs the small lap package; we installed it in the setup step, otherwise Ultralytics installs it on the first run and asks you to restart.

Step 5: Segmentation, pose estimation and ONNX export

The same API covers other vision tasks. Add -seg to the model name for pixel masks, -pose for 17 human body keypoints, -cls for classification and -obb for rotated boxes. Finally, export() converts the model to formats such as ONNX, OpenVINO, TensorRT, CoreML or TFLite.

from ultralytics import YOLO

seg = YOLO("yolo26n-seg.pt")("images/zidane.jpg", verbose=False)[0]
print("segmentation masks:", seg.masks.data.shape[0], "| mask size:", tuple(seg.masks.data.shape[1:]))
seg.save(filename="output/zidane_seg.jpg")

pose = YOLO("yolo26n-pose.pt")("images/zidane.jpg", verbose=False)[0]
print("people with keypoints:", pose.keypoints.data.shape[0], "| keypoints each:", pose.keypoints.data.shape[1])
pose.save(filename="output/zidane_pose.jpg")

# export to ONNX and run it without PyTorch-specific code
path = YOLO("yolo26n.pt").export(format="onnx", imgsz=640, verbose=False)
print("exported:", path.split("/")[-1])
onnx = YOLO(path, task="detect")
r = onnx("images/bus.jpg", verbose=False)[0]
print("onnx objects:", len(r.boxes), "| top:", [onnx.names[int(c)] for c in r.boxes.cls[:3]])
segmentation masks: 3 | mask size: (384, 640)
people with keypoints: 2 | keypoints each: 17
exported: yolo26n.onnx
onnx objects: 5 | top: ['bus', 'person', 'person']

The segmentation model returned three masks (two people and the tie) and the pose model found both people with 17 keypoints each. The ONNX file is 9.5 MB and runs with ONNX Runtime, which you can use on servers where you do not want the full PyTorch stack, and it gave the same five detections. Masks are useful when you need the exact shape of an object; for cutting a subject out of a photo with a transparent background, our rembg background removal tutorial is the simpler tool.

Common problems and fixes

  • pip downloads gigabytes of CUDA files: install the CPU build of torch from the PyTorch CPU index before installing Ultralytics.
  • Wrong class names or nothing found: the pretrained models only know the 80 COCO classes (person, car, dog, bottle and so on). For your own objects, train on a custom dataset with model.train(data="data.yaml", epochs=50).
  • Small objects are missed: raise imgsz to 960 or 1280, lower conf, or use a bigger model.
  • Too many duplicate boxes: raise conf or lower iou; with YOLO26 you can also try nms=False.
  • AttributeError on to_df(): the result is a Polars DataFrame in 8.4; call .to_pandas() if your code expects pandas.
  • Licence questions: Ultralytics and its models are AGPL-3.0. That is fine for learning and open-source projects; closed-source commercial products need an Ultralytics Enterprise licence.

Where to use it next

Object detection works well together with classic image processing. Crop every detected box with Image.crop() and resize or watermark it with our Pillow tutorial, or send the crops to a vision language model to describe them, as shown in multimodal AI engineering with vision and text in Python. YOLO answers where the objects are very fast; the language model can then explain what is happening.

Conclusion

With Ultralytics, object detection in Python is three lines: load YOLO("yolo26n.pt"), call it on an image, and read r.boxes. From there, conf and classes filter the results, summary() and to_df() turn them into data, track() follows objects through a video, the -seg and -pose models add masks and keypoints, and export() gives you an ONNX file for deployment. Start with the nano model on CPU, measure, and move to a bigger model only if you need more accuracy.

FAQ

Is YOLO26 better than YOLO11? On COCO, YOLO26n scores 40.9 mAP and adds NMS-free inference. In our CPU test both nano models ran at about 21 ms, so YOLO26 is the better default for new projects.

Does YOLO need a GPU? No. Every example in this tutorial ran on a CPU. A GPU makes training and the large models much faster.

Can YOLO detect my own objects? Yes, after training on labelled images of those objects. The pretrained models detect the 80 COCO classes.

How do I count objects in a video? Use model.track() and count unique track IDs, as in step 4, instead of counting boxes in every frame.

Tested versions: Python 3.14.10, ultralytics 8.4.219, torch 2.15.0+cpu, torchvision 0.29.2+cpu, opencv-python 5.1.0.95, NumPy 2.5.5, Polars 2.2.0, onnx 1.23.2, onnxruntime 1.32.0, lap 0.5.14 on Linux x86_64 (CPU only).

Share:
Last updated: November 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices