Skip to content

Lesson 8 of 9 · 27m

OpenCV DNN and Model Integration

Load ONNX and framework-exported models with cv2.dnn, build correct input blobs, interpret outputs, and keep preprocessing aligned with training.

The easiest neural network integration bug to create is a model that runs. It accepts input, returns tensors, and produces boxes or masks — all while silently using the wrong color order, normalization, letterbox geometry, or class mapping. In vision, model integration is mostly preprocessing and output interpretation. The matrix multiplication is the easy part.

Prefer deployment artifacts over training frameworks

OpenCV DNN commonly consumes ONNX:

net = cv2.dnn.readNetFromONNX("detector.onnx")
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

This avoids dragging a training framework into production just to run inference. Export the model once, pin the artifact, record the preprocessing contract beside it, and verify output against a reference implementation.

blobFromImage is the contract in code

blob = cv2.dnn.blobFromImage(
    image,
    scalefactor=1 / 255.0,
    size=(640, 640),
    mean=(0, 0, 0),
    swapRB=True,
    crop=False,
)
net.setInput(blob)
out = net.forward()

Every parameter matters. swapRB=True only fixes color order if the input image is BGR and the model expects RGB. scalefactor and mean must match training normalization. crop=True is rarely what detection pipelines want because it can discard geometry. If the trainer normalized with ImageNet mean and standard deviation, blobFromImage alone is often insufficient for per-channel scaling; implement preprocessing explicitly and validate numerically.

Model outputs are framework-shaped, not user-shaped

Object detectors may return rows like:

center_x center_y width height objectness class0 class1 ...

or boxes plus class scores, or batched tensors with transposed dimensions. Print shapes before writing parsing logic:

print(type(out), getattr(out, "shape", None))

Then test with known images and compare against the framework's reference postprocessor. Do not infer semantics from a tensor that happens to be rectangular.

Non-maximum suppression is part of the model behavior

Multiple overlapping boxes are normal. NMS chooses survivors:

indices = cv2.dnn.NMSBoxes(
    boxes, confidences,
    score_threshold=0.25,
    nms_threshold=0.45,
)

NMS thresholds affect duplicates and missed overlapping objects. A high NMS threshold keeps duplicates; a low one deletes nearby objects. Class-agnostic NMS may suppress different classes occupying the same region, which may or may not be acceptable.

Validation needs golden tensors

Keep a small set of input images and expected outputs in CI. Record preprocessing operations exactly, including scale, padding, dtype, color order, and input shape. When upgrading OpenCV, ONNX exports, or model weights, compare outputs within tolerance. Vision models rarely fail compilation; they drift semantically.

Hardware acceleration is a deployment decision

OpenCV can target CPU, OpenCL, CUDA, or inference backends depending on build and platform. Do not assume acceleration exists because the API exposes a constant. Benchmark end-to-end: decode, preprocess, inference, NMS, tracking, and encode. Moving tensors faster does not help if the pipeline spends its life resizing frames.

Field notes

  • Pin model artifact hashes and class-label mappings together; a correct tensor with wrong labels is still wrong.
  • Normalize a real sample and compare checksums or statistics against reference preprocessing.
  • Verify output tensor dimensions per model version. Export tooling changes shapes surprisingly often.
  • Do not run inference directly on compressed or display-resized frames unless that was the training distribution.
  • A low-confidence box may still be a pipeline bug. Inspect preprocessing before tuning thresholds downward.

Was this lesson helpful?

Sign in to rate