OpenCV is no longer just a library of filters and edge detectors. It is the glue that turns raw pixels into tensors a neural network can eat, and turns the network’s raw output back into boxes, masks, and decisions a product can use. With the OpenCV DNN module, the same library can also run the model in between.

When deep learning took over computer vision around 2012, many people predicted that hand-crafted image processing would become obsolete. That did not happen. The classical computer vision vs deep learning debate ended in a merger instead. Most production vision systems today are a hybrid computer vision pipeline, where classical operations surround a learned model.

OpenCV sits exactly at that junction. It has more than two decades of battle-tested classical algorithms, and with the release of OpenCV 5 in June 2026 it also ships a rewritten deep learning inference engine. This post walks through both halves, shows how to run ONNX models with OpenCV, and, more importantly, looks at the seam where they meet. The last section covers where OpenCV ONNX inference is enough on its own and where a dedicated runtime does the job better.

The classical toolbox is deterministic, cheap and explainable

Classical image processing treats an image as a 2D signal and applies explicit mathematical operations to it. Every step is deterministic, needs no training data and can be reasoned about line by line. OpenCV’s core modules cover the whole range:

Family Typical functions What it is good for
Color and intensity
cvtColor, equalizeHist, createCLAHE
Normalising lighting, switching color spaces (BGR, HSV, Lab)
Filtering
GaussianBlur, medianBlur, bilateralFilter
GaussianBlur, medianBlur, bilateralFilter
Edges and gradients
Canny, Sobel, Laplacian
Finding boundaries and texture
Morphology
erode, dilate, morphologyEx
Cleaning binary masks, closing gaps, removing specks
Segmentation
threshold, adaptiveThreshold, watershed, findContours
Separating objects from background
Features
findHomography, warpPerspective, solvePnP, calibrateCamera
Undistortion, perspective correction, 3D pose
Video
calcOpticalFlowPyrLK, background subtractors
Motion and change detection

The weakness of this toolbox is semantics. A Canny detector finds edges, but it cannot tell you that a set of edges is a pedestrian. Thresholds tuned for one factory line break under a new light source. That gap, between where the pixels change and what the pixels mean, is what machine learning filled.

Classical computer vision vs deep learning and what actually changed

Deep learning replaced the feature extraction step, not the whole pipeline. Convolutional networks, and later vision transformers, learn their own filters from data instead of relying on hand-designed ones like SIFT or HOG. Error rates on benchmarks such as ImageNet fell several-fold within a few years.

That is why image preprocessing for deep learning never went away. A trained model still expects a very specific input: a fixed resolution, a particular channel order, normalized values, often a batch dimension in NCHW layout. And it still returns raw tensors: logits, anchor offsets, heatmaps, embeddings. Someone has to bridge the camera and the tensor on one side, and the tensor and the business logic on the other.

That someone is very often OpenCV. Even teams that train exclusively in PyTorch load frames with cv2.VideoCapture, resize them with cv2.resize, draw results with cv2.rectangle, and run non-maximum suppression with cv2.dnn.NMSBoxes. The classical library became the I/O and geometry layer of the AI stack.

The OpenCV DNN module runs trained models without a framework

The OpenCV DNN module lets you run a model trained elsewhere without installing PyTorch or TensorFlow at inference time. To run ONNX models with OpenCV, you export the model to ONNX, load it, and run it with the same library that already handles your images.

The OpenCV 5 DNN engine made this far more practical. It was rewritten from scratch, and ONNX operator coverage rose from about 22% in the 4.x line to over 80%. readNet() and readNetFromONNX() now take an engine parameter, auto-selecting the new engine and falling back to the classic one when needed. The new engine even includes tokenizers and KV-caching, so some vision-language models run end-to-end inside OpenCV.

A minimal example to run ONNX models with OpenCV

The core workflow has not changed and works in both 4.x and 5.x:

				
					import cv2
import numpy as np

net = cv2.dnn.readNetFromONNX("resnet50.onnx")

img = cv2.imread("cat.jpg")

# blobFromImage = resize + mean subtraction + scaling + BGR->RGB + HWC->NCHW
blob = cv2.dnn.blobFromImage(
    img,
    scalefactor=1 / 255.0,
    size=(224, 224),
    mean=(0.485 * 255, 0.456 * 255, 0.406 * 255),
    swapRB=True,
    crop=False,
)

# blobFromImage takes one scale factor for all channels,
# so the per-channel ImageNet std is applied separately
blob /= np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 3, 1, 1)

net.setInput(blob)
logits = net.forward()            # shape: (1, 1000)
class_id = int(np.argmax(logits))
print("Predicted class:", class_id)
				
			
OpenCV blobFromlmage: WizzDev

Notice that OpenCV blobFromImage is itself a small classical pipeline: resize, color swap, normalization, and a layout change. It is the clearest example of OpenCV acting as the bridge, in one function call.

One caveat as of this writing: the new OpenCV 5 engine is CPU-only at launch. For GPU inference, you still use the classic engine’s CUDA backend or an external runtime.

Where a hybrid computer vision pipeline earns its keep

The most robust systems use a neural network only for the step that needs semantics, and classical operations for everything else. Classical code is cheaper, deterministic, and easy to debug; the network is expensive and opaque, so you give it the smallest, cleanest job possible.

A typical split has three stages:

  1. Before the model: contrast normalization (CLAHE), denoising, undistortion with camera calibration, cropping a region of interest, letterbox resizing.

  2. The model: detection, segmentation, or classification, where learned features beat any hand-tuned rule.

  3. After the model: non-maximum suppression, mask cleanup with morphology, contour analysis, perspective correction, measurement in real-world units, tracking between frames.

Hybrid computer vision pipeline in which classical OpenCV preprocessing and postprocessing surround an ONNX model run by the OpenCV DNN module: WizzDev

The WizzDev OCR water meter reader applies this split on an ESP32-CAM. A compressed digit-recognition model runs on the device, while everything around it stays simple: configured regions of interest select the digits, a pulsed LED with tuned timing lights dim basements, and readings are validated locally before any cellular data is spent.

Tracking is where the split also saves compute. As we noted in the WizzDev OpenCV tracking tutorial, correlation trackers such as CSRT drift over time, so the practical pattern is to run the detector every few frames and re-sync the tracker in between.

A license plate detector with classical rectification

Here is a compact example: a single-class license plate detector exported to ONNX (YOLO-style output of [cx, cy, w, h, score] per candidate), followed by classical rectification so a downstream OCR step sees a flat, frontal plate.

				
					import cv2
import numpy as np

net = cv2.dnn.readNetFromONNX("plate_detector.onnx")
INPUT = 640

def preprocess(frame):
    # Classical: equalise lighting on the L channel only
    lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
    l, a, b = cv2.split(lab)
    l = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(l)
    return cv2.cvtColor(cv2.merge((l, a, b)), cv2.COLOR_LAB2BGR)

def detect(frame, conf_thr=0.4, nms_thr=0.5):
    h, w = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (INPUT, INPUT), swapRB=True)
    net.setInput(blob)
    out = net.forward()[0].T                 # (N, 5)
    boxes, scores = [], []
    sx, sy = w / INPUT, h / INPUT
    for cx, cy, bw, bh, score in out:
        if score < conf_thr:
            continue
        boxes.append([int((cx - bw / 2) * sx), int((cy - bh / 2) * sy),
                      int(bw * sx), int(bh * sy)])
        scores.append(float(score))
    keep = cv2.dnn.NMSBoxes(boxes, scores, conf_thr, nms_thr)
    return [boxes[i] for i in np.array(keep).flatten()]

def rectify(frame, box):
    # Classical: find the plate's real outline inside the box and unwarp it
    x, y, bw, bh = box
    roi = frame[max(y, 0):y + bh, max(x, 0):x + bw]
    gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(cv2.GaussianBlur(gray, (5, 5), 0), 50, 150)
    edges = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return roi
    rect = cv2.minAreaRect(max(contours, key=cv2.contourArea))
    pts = cv2.boxPoints(rect)
    # Order corners explicitly: top-left, top-right, bottom-right, bottom-left
    s, d = pts.sum(axis=1), np.diff(pts, axis=1).ravel()
    src = np.float32([pts[np.argmin(s)], pts[np.argmin(d)],
                      pts[np.argmax(s)], pts[np.argmax(d)]])
    W, H = 240, 60
    dst = np.float32([[0, 0], [W, 0], [W, H], [0, H]])
    M = cv2.getPerspectiveTransform(src, dst)
    return cv2.warpPerspective(roi, M, (W, H))

frame = cv2.imread("car.jpg")
for box in detect(preprocess(frame)):
    plate = rectify(frame, box)
    cv2.imwrite(f"plate_{box[0]}_{box[1]}.png", plate)
				
			

For brevity the example stretches the frame to 640×640; use letterboxing if the detector was trained that way.

The network answers one question: where is a plate? Everything else (lighting correction, duplicate removal, finding the exact outline, unwarping) is classical. Swap the detector for a better model next year and the rest of the computer vision pipeline stays untouched.

When OpenCV ONNX inference is enough in production

OpenCV’s biggest practical advantage is the dependency footprint. One C++ library (with Python, Java and JavaScript bindings) covers capture, preprocessing, inference and visualization. On an embedded board or in a small container, dropping a full deep learning framework can save hundreds of megabytes and a lot of build pain.

We used the same split in a Smart City Monitoring device we built at WizzDev for municipal vehicles. Instead of streaming video to a server around the clock, the device analyzes footage on board and sends the city’s central system only an alert with a photo and GPS coordinates, which drastically reduced network usage and cost.

When to use OpenCV DNN and when a dedicated runtime

For OpenCV ONNX inference on CPU, the OpenCV team reports that the new 5.x engine matches or beats ONNX Runtime for some tested models. In its own comparison of OpenCV DNN vs ONNX Runtime on an Intel Core i9-14900KS, the new engine was 4.4% to 36.6% faster across seven models, from RF-DETR to OWLv2. The release also adds new core types such as bfloat16 and 64-bit integers that matter for modern networks. Treat vendor benchmarks as a starting point and measure on your own hardware and model.

Situation Reasonable choice
CPU or embedded Linux deployment, standard ONNX model
OpenCV DNN alone
Need GPU throughput today
OpenCV for pre/post-processing; ONNX Runtime, TensorRT or OpenVINO for the model
Training, fine-tuning, research
PyTorch or JAX; OpenCV only for data loading and augmentation
Exotic operators or custom layers
Dedicated runtime; check OpenCV’s ONNX coverage first
No semantic understanding needed (measurement, alignment, QA on fixed setups)
Classical OpenCV, no model at all

A few habits make hybrid pipelines reliable:

  • Reproduce the training image preprocessing exactly: same resize interpolation, channel order, and normalization. Most “the model works in Python but not in production” bugs live here.

  • Budget for retraining. In the WizzDev cost estimate for an OCR water meter, dataset collection and model retraining is a separate risk item of 80–240 hours, because accuracy on real meters may fall short of production standards.

  • Keep pre- and post-processing in plain functions with unit tests on fixed images; they are deterministic, so they are easy to test.

  • Log intermediate images (after CLAHE, after the mask cleanup). Classical steps are inspectable, which is half their value.

  • Upgrading to OpenCV 5 means C++17, no Python 2, a deprecated legacy C API, and the classic ml module moved to opencv_contrib. Plan the migration rather than bumping the version blindly.

Not old versus new, but both

The real skill in modern computer vision is knowing which problem needs a learned model and which needs twenty lines of geometry. OpenCV is the one library fluent in both languages: it speaks pixels, contours, and homographies on one side, and tensors, ONNX graphs, and embeddings on the other.

If you take one thing away: let the network do the part only a network can do, and let OpenCV do the rest. Your pipeline will be faster, cheaper, easier to debug, and ready to swap in tomorrow’s model without rewriting today’s code.

Key takeaways

  • The OpenCV DNN module runs ONNX models without PyTorch or TensorFlow installed, so one library handles the whole path from camera frame to result.

  • OpenCV 5 raised ONNX operator coverage from about 22% in the 4.x line to over 80%, but its new engine is CPU-only at launch.

  • In a hybrid computer vision pipeline, the network handles only the step that needs semantics, and classical code does the work before and after it.

  • Most bugs where a model works in Python but fails in production come from preprocessing that differs from training.

  • Classical computer vision vs deep learning is not an either-or choice, because measurement and alignment on fixed setups often need no model at all.