archive2023

YOLOv8 on a CPU: export to ONNX and run without PyTorch

Ultralytics released YOLOv8 in January 2023. How to export a YOLOv8 detection model to ONNX and run it with ONNX Runtime and OpenCV, including letterbox resize, output decoding and NMS.

5 min read#computer-vision#yolo#onnx

Ultralytics released YOLOv8 in January 2023. It comes as a pip package, ultralytics, with one Python API and one CLI for training, prediction and export. The detection models are pretrained on COCO, in sizes from n (nano) to x.

I wanted to try it on a camera frame grabber that runs on a small home server. The package is fine for training and quick tests, but on that box I do not want PyTorch and the full package. I want one .onnx file, ONNX Runtime, OpenCV and NumPy. Getting there took me longer than expected, mostly because of the output format, so here are my notes.

This setup makes sense on CPU-only machines where a few frames per second is enough, and when you use a standard detection model. If you need GPU speed, tracking or segmentation helpers, or you change models every week, just stay with the ultralytics package.

Step 1: export on your workstation

python -m venv .venv && . .venv/bin/activate
pip install ultralytics onnx
yolo export model=yolov8n.pt format=onnx imgsz=640

Or in Python:

from ultralytics import YOLO

model = YOLO("yolov8n.pt")       # downloads the weights the first time
model.export(format="onnx", imgsz=640)

The result is yolov8n.onnx. Copy it to the target machine.

Check the input and output:

import onnxruntime as ort
s = ort.InferenceSession("yolov8n.onnx", providers=["CPUExecutionProvider"])
print(s.get_inputs()[0].name, s.get_inputs()[0].shape)    # images [1, 3, 640, 640]
print(s.get_outputs()[0].name, s.get_outputs()[0].shape)  # output0 [1, 84, 8400]

Understanding the output

The output shape is [1, 84, 8400]:

8400 is the number of candidate boxes (from three feature map scales for a 640x640 input). Each box has 84 values: 4 box values (cx, cy, w, h in input pixels), then 80 class scores for COCO.

This is different from YOLOv5, and it is where my first attempt went wrong. YOLOv8 has no separate objectness score. The confidence is the highest class score. Also, the layout is “values first”, so you need a transpose to get one row per box.

Step 2: preprocessing with letterbox

YOLO models are trained with letterbox resize: keep the aspect ratio, and pad the rest with grey. If you just stretch the image to 640x640, detection still works but accuracy drops, especially for wide camera frames.

import cv2
import numpy as np

def letterbox(img, size=640, color=(114, 114, 114)):
    h, w = img.shape[:2]
    scale = min(size / h, size / w)
    nh, nw = round(h * scale), round(w * scale)
    resized = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)
    top = (size - nh) // 2
    left = (size - nw) // 2
    out = np.full((size, size, 3), color, dtype=np.uint8)
    out[top:top + nh, left:left + nw] = resized
    return out, scale, left, top

def preprocess(frame_bgr):
    img, scale, pad_x, pad_y = letterbox(frame_bgr)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    x = img.astype(np.float32) / 255.0
    x = np.transpose(x, (2, 0, 1))[np.newaxis]   # 1x3x640x640
    return np.ascontiguousarray(x), scale, pad_x, pad_y

Note: no mean/std normalization. YOLOv8 only scales to 0..1.

Step 3: decode and NMS

def postprocess(output, scale, pad_x, pad_y, conf_thres=0.4, iou_thres=0.5):
    preds = output[0].T                     # 8400 x 84
    boxes_cxcywh = preds[:, :4]
    scores_all = preds[:, 4:]
    class_ids = scores_all.argmax(axis=1)
    scores = scores_all[np.arange(len(preds)), class_ids]

    keep = scores > conf_thres
    boxes_cxcywh, scores, class_ids = boxes_cxcywh[keep], scores[keep], class_ids[keep]
    if len(scores) == 0:
        return []

    # cx,cy,w,h -> x,y,w,h in letterboxed pixels
    xywh = boxes_cxcywh.copy()
    xywh[:, 0] -= xywh[:, 2] / 2
    xywh[:, 1] -= xywh[:, 3] / 2

    idx = cv2.dnn.NMSBoxes(xywh.tolist(), scores.tolist(), conf_thres, iou_thres)
    results = []
    for i in np.array(idx).flatten():
        x, y, w, h = xywh[i]
        # undo letterbox: remove padding, then scale back
        x = (x - pad_x) / scale
        y = (y - pad_y) / scale
        w /= scale
        h /= scale
        results.append((int(class_ids[i]), float(scores[i]), int(x), int(y), int(w), int(h)))
    return results

cv2.dnn.NMSBoxes does class-agnostic NMS here: a “car” box can suppress an overlapping “truck” box. For most camera use this is what I want. If you need per-class NMS, run it per class, or add class_id * 4096 to the x coordinate before NMS so boxes of different classes never overlap.

Step 4: put it together

import onnxruntime as ort

COCO = ["person", "bicycle", "car"]  # fill in all 80 names, in order

opts = ort.SessionOptions()
opts.intra_op_num_threads = 4
sess = ort.InferenceSession("yolov8n.onnx", opts, providers=["CPUExecutionProvider"])

frame = cv2.imread("frame.jpg")
x, scale, px, py = preprocess(frame)
out = sess.run(None, {"images": x})[0]
for cls, score, x0, y0, w, h in postprocess(out, scale, px, py):
    name = COCO[cls] if cls < len(COCO) else str(cls)
    cv2.rectangle(frame, (x0, y0), (x0 + w, y0 + h), (0, 255, 0), 2)
    cv2.putText(frame, f"{name} {score:.2f}", (x0, y0 - 4),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
cv2.imwrite("out.jpg", frame)

The class names are stored in the model metadata too. You can read them with sess.get_modelmeta().custom_metadata_map["names"] instead of a hand-written list.

Validate against the package

Before you trust your code, compare with the official prediction on the same images:

yolo predict model=yolov8n.pt source=frame.jpg conf=0.4

Boxes and scores should be very close. If they are not, check in this order: BGR/RGB, letterbox padding, the transpose, and the box format.

Speed on small machines

Start with yolov8n. The bigger models are much slower on CPU. After that, a smaller input size is the cheapest speedup: export with imgsz=320 or imgsz=416 and check if small objects are still found. Far-away people are the first thing you lose.

Also, do not run detection on every frame of a 25 fps stream. Two to five frames per second is enough to answer “is someone there”.

I have not measured this on a Raspberry Pi 4 yet. If you try it there, use the 64-bit OS and cool the board. Numbers depend a lot on input size, thread count and cooling, so measure with your own frames.

License

The ultralytics package and the YOLOv8 weights are under AGPL-3.0. If you ship a product that includes them, read what this means for you, or check the commercial license from Ultralytics. I mention it because it is easy to forget when a weekend project slowly turns into something you ship.