OpenCV 5 Migration: What Breaks and How to Fix It

OpenCV 5 Migration feature image with OpenCV logo, Python code on a laptop and AI Vision Insights branding

OpenCV 5 migration sounds like a big job. The official migration guide says something calmer: most existing code needs only small changes. For a Python script that calls cv2.imread, cv2.resize and cv2.dnn.readNet, that is often true. The trouble hides in a few places. A removed model loader. A module that moved. A test that compares pixels and now fails by one value.

This guide goes through those places in the order you should check them. You get a risk table, working snippets, a simple before-and-after test, and a rule for deciding whether to upgrade now or wait. The facts come from the OpenCV project’s own pages, linked as we go.

OpenCV 5 migration at a glance

OpenCV 5.0 came out in June 2026 and follows the long 4.x line. The project says it keeps the most used parts of 4.x, adds new features, removes obsolete code and changes a small number of APIs. The 4.x branch is still maintained next to it, so nobody is forced to move on a deadline.

The biggest change is the DNN module, which runs neural networks. It has a new engine. Around it sit a cleanup of old code, some modules that moved, and a few small changes in numbers and defaults. The table below sorts them by who gets hit, so you can see how big your own OpenCV 5 migration will be.

What changed Who is affected What to do
New DNN engine, CPU only Anyone loading ONNX models, especially with CUDA or OpenVINO targets Test your model; pin an engine if needed
Caffe and Darknet loaders removed Users of readNetFromCaffe or readNetFromDarknet Convert the models to ONNX
ml and G-API moved to opencv_contrib Users of cv2.ml or G-API Build with contrib, or use scikit-learn for ML
Haar and HOG detectors moved to contrib Users of CascadeClassifier or HOGDescriptor Build with contrib, or try a DNN detector
Old C API removed Code using CvMat or IplImage Move to the C++ API
C++17 required, Python 3.6 or later Build systems and old environments Update the toolchain
Resize, warp and text output differ slightly Tests that compare pixels Regenerate the baselines
VideoCapture.get() returns -1 for unsupported properties Code that checks for 0 Check for a value below 0
A vector wrapped in a Mat is now 1D C++ code that reads rows or columns Use total()

If none of the middle column describes your project, your upgrade is probably quick. If a row does, jump to the step that covers it.

Step 1: Check how your model loads (the new DNN engine)

OpenCV 5 model loading illustration showing a neural network workflow
Check how your ONNX models load with the new OpenCV 5 DNN engine.

In 4.x, the DNN module read only part of the ONNX operator list. It also struggled with models whose input shapes change at run time. OpenCV 5 replaces that with a graph-based engine. The release overview says ONNX operator coverage went from about 22% to over 80%. A later revision of the project wiki quotes 64% against 13%. The pages quote different figures, so treat the exact percentage as a rough guide. The direction is clear: more modern models load.

What the default does

For most ONNX models your loading code does not change. cv2.dnn.readNet("model.onnx") still works. In the 5.0.0 release the default mode is automatic: OpenCV tries the new engine first and falls back to the classic engine if the model does not load.

You can force a choice with an engine argument. You can also do it without code changes through the OPENCV_FORCE_DNN_ENGINE environment variable. In 5.0.0 the values are 1 for classic, 2 for new (an error if the model cannot load), 3 for automatic and 4 for ONNX Runtime. One more rule: you cannot switch engines after a model is loaded, because the two engines use different internal formats.

Engine names changed, so use names and not numbers

The OpenCV DNN tutorial checked the newest 5.x development code in September 2026 and found a different API from the 5.0.0 release. In 5.0.0, ENGINE_NEW picks the rewritten engine. In the newer code, ENGINE_AUTO resolves to ENGINE_OPENCV, the built-in CPU-only engine, and ENGINE_ORT picks ONNX Runtime. ENGINE_NEW and ENGINE_CLASSIC are no longer exposed there, and the numeric values changed too.

So code that runs on 5.0.0 can fail on a newer build. A safe pattern is to ask which name exists:

import cv2

# Use whichever name this build provides.
if hasattr(cv2.dnn, "ENGINE_OPENCV"):
    engine = cv2.dnn.ENGINE_OPENCV   # newer 5.x development API
elif hasattr(cv2.dnn, "ENGINE_NEW"):
    engine = cv2.dnn.ENGINE_NEW      # released 5.0.0
else:
    raise RuntimeError("OpenCV 5 built-in DNN engine not found")

net = cv2.dnn.readNetFromONNX("model.onnx", engine)

The tutorial’s own scripts also stop if OPENCV_FORCE_DNN_ENGINE is set, because an old number could select a different engine than you expect. It is worth adding the same check to your test scripts.

GPU users: read this before you upgrade

The new engine runs on the CPU only. Setting a CUDA target does not move it to the GPU. The 5.0.0 migration guide gives two routes: force the classic engine, or build OpenCV with ONNX Runtime and the NVIDIA execution providers (-DWITH_ONNXRUNTIME=ON -DDOWNLOAD_ONNXRUNTIME_GPU=ON).

Installing the onnxruntime Python package alone does not add this to an existing OpenCV wheel. It has to be built in. The classic route also depends on your build, since the newer development API no longer lists ENGINE_CLASSIC. Check the exact build you plan to ship. The release overview lists native GPU support in the new engine as planned work for the 5.x series.

Read the speed numbers with care

The project publishes CPU timings against ONNX Runtime 1.25.1. Here are its YOLO26 Nano results in milliseconds, where lower is better. If you are still choosing a model, our YOLO26 vs YOLO11 comparison covers that side.

Hardware label OpenCV 5 DNN (ms) ONNX Runtime 1.25.1 (ms) Faster
Intel i9 9.9 9.6 ONNX Runtime
Intel i7 24.9 19.0 ONNX Runtime
Apple M1 55.6 63.4 OpenCV 5
Apple M5 22.7 21.6 ONNX Runtime
AMD 13.6 30.7 OpenCV 5

OpenCV is ahead on two of the five machines. ONNX Runtime is ahead on three. There are two warnings. First, these numbers compare two runtimes with each other. They do not show how much faster version 5 is than 4.x. Second, the tutorial itself says the tables do not give enough detail to reproduce every number: model exports, input shapes, exact CPUs, threading and timing method are missing. Use them to decide what to test, then time your own model, as Step 4 shows.

Step 2: Find what was removed or moved

OpenCV 5 migration illustration showing removed and relocated modules
Identify the OpenCV modules and functions that have been removed or moved to opencv_contrib.

Removed features fail loudly. You get an import error or a missing function. That is good news, because loud failures are easy to find. Search your code for the names below.

Model loaders

readNetFromCaffe() and readNetFromDarknet() are gone. The project’s reasoning is that most models now exist in ONNX. The migration guide points to the Ultralytics export tool for Darknet YOLO weights and to caffe-onnx for Caffe models. After converting, load the file with readNetFromONNX(). TFLite models still load through the classic engine, and moving them to the new engine is planned.

Modules now in opencv_contrib

These left the main repository and now live in opencv_contrib:

  • The ml module: SVM, KNearest, decision trees and similar classes.
  • The G-API module, gapi.
  • Haar cascades (CascadeClassifier) and HOG (HOGDescriptor), now in xobjdetect.
  • Older feature detectors such as SURF, BRIEF, FREAK, LUCID and DAISY, now in xfeatures2d.

SIFT, ORB, FAST, GoodFeaturesToTrack and MSER stay in the main repository. In Python, cv2.ml, cv2.CascadeClassifier and cv2.HOGDescriptor are missing unless your OpenCV build includes contrib. For classic machine learning, the guide suggests scikit-learn. For faces, it points to a detector in the main objdetect module and calls it faster and more accurate than Haar cascades:

detector = cv2.FaceDetectorYN.create("face_detection_yunet.onnx", "", (320, 320))
_, faces = detector.detect(image)

You need a face detection ONNX file for this, such as the YuNet model named in the guide. If you use Haar cascades only for a quick prototype, switching now may save you a contrib build later.

The old C API and build tools

The OpenCV 1.x C API is fully removed: CvMat, IplImage, cvCreateMat(), cvFindContours() and friends. Macros such as CV_8U stay. The guide says little production code written in the last decade uses the C API directly, so most projects are not hit.

The build needs C++17. The guide lists GCC 8, Clang 9 or MSVC 2017 (19.14) as the minimum compilers. Python 2 support is gone, so use Python 3.6 or later.

Module splits are mostly invisible. The big calib3d module is now geometry, calib, stereo and ptcloud, but in C++ the old opencv2/calib3d.hpp header still works. In Python every function is still called as cv2.name(). The renames that do need edits are features2d, now features (update the C++ include), and the Java imports.

Step 3: Watch for silent behavior changes

OpenCV 4 and OpenCV 5 comparison illustrating subtle image processing changes
Understand subtle changes in resizing, image warping, text rendering and other OpenCV functions.

These changes do not crash anything. They change numbers, which is why they are easy to miss.

  • Nearest-neighbor resize. It now follows the Pillow algorithm, and INTER_NEAREST and INTER_NEAREST_EXACT are now the same. If you compare OpenCV output with Pillow, the two now agree. If you store 4.x baselines, boundary pixels may differ.
  • Warping. warpAffine, warpPerspective and remap no longer use table-based approximations in bilinear and bicubic modes. Results are closer to the exact math and differ slightly from 4.x. The project wiki reports speed gains from 10% to over 300%, depending on platform, image size, type and flags.
  • Text drawing. Old FONT_HERSHEY_* calls still run, but they now use a TrueType engine with the embedded Rubik font. Text size and look change. A new FontFace API adds UTF-8 text and custom fonts.
  • VideoCapture.get(). An unsupported property now returns -1 instead of 0. Zero is a valid value for many properties, so the old result was ambiguous. Test for < 0.
  • Vector-backed Mat. In C++, a std::vector wrapped in a Mat is now a true 1D array, so rows and columns change meaning. Use total() to count elements. In Python, a NumPy array passed as input now maps to a 1D Mat, so code that assumed a column vector may need a fix.
  • New element types. CV_16BF, CV_32U, CV_64U, CV_64S and CV_Bool are new. If you switch on mat.depth(), add cases, or at least a default branch that raises an error.

Resize changes matter most when resizing already drives your results. Tiny-object work is the clearest case, and our guide to small object detection with YOLO tiling shows why. If that is you, compare outputs closely.

Step 4: Run a before-and-after test

OpenCV 4 and OpenCV 5 before-and-after testing comparison
Compare outputs from OpenCV 4.x and 5.x using the same test images and inputs.

A script that runs without errors is not a script that gives the same answers. Before you take your OpenCV 5 migration to production, compare old and new on the same inputs. This plan needs no special tools.

  1. Freeze a test set. Pick a small set of images or short clips, say 20 to 50. Include normal cases and the hard ones your system struggles with. A labeled set is better than none. If you need images labeled, a data annotation service such as Annotationera is one option.
  2. Save the 4.x output. Store the detections (boxes, scores, class IDs) and any processed images, using your current OpenCV 4.x setup.
  3. Install OpenCV 5 in a fresh environment. Do not upgrade in place.
  4. Run the same inputs and compare. For images, check the pixel difference. For detections, match boxes by overlap and compare scores. Decide before you look what difference is acceptable, for example a box shift of a few pixels.
  5. Time it. Warm up, then average many runs. Time loading, preprocessing, the network and postprocessing separately.
  6. Write down what ran. Record the OpenCV version, the model file, the export settings and the test images. The OpenCV tutorial gives the same advice, so future upgrades can be checked against a known reference.

Here is a minimal image comparison:

import cv2

old = cv2.imread("out_opencv4.png")
new = cv2.imread("out_opencv5.png")

diff = cv2.absdiff(old, new)
print("largest pixel difference:", int(diff.max()))
print("average difference:", round(float(diff.mean()), 3))

And a timing loop for the network call:

import time

net.setInput(blob)
net.forward()                      # warm-up run

start = time.perf_counter()
for _ in range(50):
    net.setInput(blob)
    net.forward()
elapsed = (time.perf_counter() - start) / 50
print(f"{elapsed * 1000:.1f} ms per frame")

This loop times only the network. Measure preprocessing and postprocessing on their own, so you can see where any change comes from.

Common mistake: two OpenCV wheels in one environment

The Python packages opencv-python and opencv-python-headless both install the cv2 module. They share the same name, so installing both in one environment can leave you with the wrong one. The fix is a fresh virtual environment per version, with only one variant installed.

The OpenCV tutorial tested its examples with opencv-python-headless==5.0.0.93 and NumPy 2.3.5. Choose opencv-python instead if you need GUI windows. Keep model export tools such as PyTorch in a separate environment, so they cannot replace your OpenCV install.

Should you upgrade now? A simple decision rule

This is our reading of the official notes, not a project recommendation. Match your project to the two lists.

Upgrade soon if

  • Your code is Python, CPU-only, and uses ordinary image functions and ONNX loading.
  • You hit unsupported-operator errors when loading modern ONNX models on 4.x.
  • You want one fewer dependency for CPU inference.

Wait, or plan extra time, if

  • You use the DNN module on CUDA or OpenVINO targets and cannot yet build with ONNX Runtime.
  • You depend on Haar cascades, HOG or cv2.ml and have no time to rework them.
  • Your tests compare pixels exactly and you cannot regenerate the baselines yet.
  • You still load Caffe or Darknet models that have not been converted.

Our take

Treat OpenCV 5 as a branch, not a switch. The project keeps 4.x alive, so you can take your time. Run Steps 1 to 4 on a copy of your project. If the first list fits you, move early and enjoy the wider ONNX support. If the second list fits you, stay on 4.x until the blocking item is fixed. The one order we would avoid is upgrading production first and testing later.

Practical tip: log your versions at startup

Print cv2.__version__ and the engine you selected when your app starts, and save both with your results. When a number changes after a deploy, you will know in seconds which OpenCV and which engine produced it.

FAQ

Will my Python code run on OpenCV 5 without changes?

Often, yes, for ordinary image functions. The module splits are invisible in Python, because every function is still called as cv2.name(). Code that touches removed loaders, contrib modules or the behavior changes in Step 3 needs attention.

Is OpenCV 5 faster than OpenCV 4?

In some areas the project reports gains. The warping functions are faster by 10% to over 300% depending on the case, and findContours() now uses a new algorithm that the wiki calls several times faster. The published DNN tables compare OpenCV 5 with ONNX Runtime, not with 4.x. So there is no single number. Time your own pipeline.

Can I still run YOLO models with OpenCV 5?

Yes, through ONNX. The OpenCV tutorial ran YOLO26 Nano exported at 640 by 640 with an end-to-end output, so its inference code needed no separate non-maximum suppression step. The old Darknet loader is removed, so convert Darknet weights to ONNX first.

Does OpenCV 5 run on my GPU?

The new built-in engine is CPU-only for now. For a GPU, use ONNX Runtime built into OpenCV with NVIDIA providers, or, in 5.0.0, the classic engine. Native GPU support in the new engine is on the project’s plan for the 5.x series.

Do I need opencv_contrib now?

Only if you use the ml module, G-API, Haar cascades, HOG, or older detectors such as SURF. Otherwise the main package is enough.

Where is the official OpenCV 5 migration guide?

It is a page on the OpenCV project wiki, called OpenCV 4 to 5 migration. It has before-and-after code for each area.

Final thoughts

For a CPU-only Python project, the OpenCV 5 migration is smaller than the headlines suggest. For GPU users of the DNN module, projects built on Haar or HOG, and test suites that compare pixels, it is bigger. Check the engine names, hunt for removed loaders and moved modules, list the silent changes, then compare outputs on a fixed test set.

Bookmark the official pages: the migration guide, the release overview and the DNN tutorial. Details may change as 5.x moves on, so check them against the build you deploy. For more practical guides, browse our Computer Vision category.

Leave a Reply

Your email address will not be published. Required fields are marked *