SystemError: <class 'cv2.VideoCapture'> returned a result with an exception set

I am building a custom Opencv library for my mini project and I am using dynamic loading. I am not close to being an expert at this, I am trying to run cv2.videocapture but each time I get this error :

cv2.error: Unknown C++ exception from OpenCV code

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File “C:\Users\CompHub\Documents\Trace-master\Trace-master\Comparison.py”, line 19, in
cap = cv2.VideoCapture(video_path) # Force FFmpeg backend
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SystemError: <class ‘cv2.VideoCapture’> returned a result with an exception set

I have upgraded my ffmpeg not to use the prebuilt binaries anymore but that didn’t make a difference. I have been at this for a week and this is my hail mary to get a response that could help me progress at least a step forward.

this is my build information:
General configuration for OpenCV 4.10.0-dev =====================================
Version control: unknown

Extra modules:
Location (extra): C:/Users/CompHub/Documents/Trace-master/Trace-master/opencv_contrib/modules
Version control (extra): unknown

Platform:
Timestamp: 2025-02-06T10:55:57Z
Host: Windows 10.0.19045 AMD64
CMake: 3.30.4
CMake generator: Visual Studio 17 2022
CMake build tool: C:/Program Files/Microsoft Visual Studio/2022/Community/MSBuild/Current/Bin/amd64/MSBuild.exe
MSVC: 1942
Configuration: Release
Algorithm Hint: ALGO_HINT_ACCURATE

CPU/HW features:
Baseline: SSE SSE2 SSE3
requested: SSE3
required: SSE
disabled: NEON
Dispatched code generation:
requested: SSE2

C/C++:
Built as dynamic libs?: YES
C++ standard: 11
C++ Compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.42.34433/bin/Hostx64/x64/cl.exe (ver 19.42.34435.0)
C++ flags (Release): /DWIN32 /D_WINDOWS /W4 /GR -D_CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:fast /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819 /MP /O2 /Ob2 /DNDEBUG /MD /Zi
C++ flags (Debug): /DWIN32 /D_WINDOWS /W4 /GR -D_CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:fast /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819 /MP /Zi /Ob0 /Od /RTC1 /MDd
C Compiler: C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.42.34433/bin/Hostx64/x64/cl.exe
C flags (Release): /DWIN32 /D_WINDOWS /W3 /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:fast /MP /O2 /Ob2 /DNDEBUG /Zi
C flags (Debug): /DWIN32 /D_WINDOWS /W3 /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi /fp:fast /MP /Zi /Ob0 /Od /RTC1
Linker flags (Release): /machine:x64 /INCREMENTAL:NO /debug
Linker flags (Debug): /machine:x64 /debug /INCREMENTAL
ccache: NO
Precompiled headers: NO
Extra dependencies: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/cudart_static.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppial.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppc.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppitc.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppig.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppist.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppidei.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/cublas.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/cublasLt.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/cufft.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppif.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppim.lib C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6/lib/x64/nppicc.lib
3rdparty dependencies:

OpenCV modules:
To be built: aruco bgsegm bioinspired calib3d ccalib core cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev datasets dnn dnn_objdetect dnn_superres dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency shape signal stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab wechat_qrcode world xfeatures2d ximgproc xobjdetect xphoto
Disabled: -
Disabled by dependency: -
Unavailable: alphamat cannops cvv freetype hdf java js julia matlab ovis python2 python2 sfm viz
Applications: tests perf_tests apps
Documentation: js
Non-free algorithms: YES

Windows RT support: NO

GUI:
Win32 UI: YES
VTK support: NO

Media I/O:
ZLib-Ng: build (zlib ver 1.3.1.zlib-ng, zlib-ng ver 2.2.1)
JPEG: build-libjpeg-turbo (ver 3.0.3-70)
SIMD Support Request: YES
SIMD Support: NO
WEBP: build (ver encoder: 0x020f)
AVIF: NO
PNG: build (ver 1.6.43)
SIMD Support Request: YES
SIMD Support: YES (Intel SSE)
TIFF: build (ver 42 - 4.6.0)
JPEG 2000: build (ver 2.5.0)
OpenEXR: build (ver 2.3.0)
HDR: YES
SUNRASTER: YES
PXM: YES
PFM: YES

Video I/O:
FFMPEG: YES (find_package)
avcodec: YES (61.32.101)
avformat: YES (61.9.106)
avutil: YES (59.56.100)
swscale: YES (8.13.100)
avresample: NO
avdevice: YES (61.4.100)
GStreamer: NO
DirectShow: YES
Media Foundation: YES
DXVA: YES

Parallel framework: Concurrency

Trace: YES (with Intel ITT)

Other third-party libraries:
Intel IPP: 2021.12.0 [2021.12.0]
at: C:/Users/CompHub/Documents/Trace-master/Trace-master/opencv/build/3rdparty/ippicv/ippicv_win/icv
Intel IPP IW: sources (2021.12.0)
at: C:/Users/CompHub/Documents/Trace-master/Trace-master/opencv/build/3rdparty/ippicv/ippicv_win/iw
Lapack: NO
Eigen: NO
OpenVX: NO
Custom HAL: NO
Protobuf: build (3.19.1)
Flatbuffers: builtin/3rdparty (23.5.9)

NVIDIA CUDA: YES (ver 12.6.68, CUFFT CUBLAS FAST_MATH)
NVIDIA GPU arch: 86
NVIDIA PTX archs: 86

cuDNN: YES (ver 9.4.0)

Vulkan: YES
Include path: C:/Users/CompHub/Documents/Trace-master/Trace-master/opencv/3rdparty/include/
Link libraries: Dynamic load

OpenCL: YES (NVD3D11)
Include path: C:/Users/CompHub/Documents/Trace-master/Trace-master/opencv/3rdparty/include/opencl/1.2
Link libraries: Dynamic load

CANN: NO

Python 3:
Interpreter: C:/Users/CompHub/AppData/Local/Programs/Python/Python312/python.exe (ver 3.12.6)
Libraries: C:/Users/CompHub/AppData/Local/Programs/Python/Python312/libs/python312.lib (ver 3.12.6)
Limited API: NO
numpy: C:/Users/CompHub/AppData/Local/Programs/Python/Python312/Lib/site-packages/numpy/core/include (ver 1.26.2)
install path: C:/Users/CompHub/AppData/Local/Programs/Python/Python312/Lib/site-packages/cv2/python-3.12

Python (for build): C:/Users/CompHub/AppData/Local/Programs/Python/Python312/python.exe

Java:
ant: NO
Java: NO
JNI: NO
Java wrappers: NO
Java tests: NO

Thank you for your help!
@crackwitz any ideas

IDK what to make of this. the “Unknown C++ exception” being unknown is a problem. It could be a complex issue involving the compilation/linking of the program or the finding of DLLs.

or it could be that the video file isn’t where it is expected to be.

you might wanna check the values of os.path.exists(video_path) as well as os.getcwd()

if that’s not it, I don’t know how to help.

So Narrowing it down, there are a couple of boxes I have checked.

so I have checked if the video file is present in the path specified and I have opened the video file myself.

I am also using Process Monitor to check if all .dll is loading properly and all seem to be loading properly.

I would guess that it is a complex issue as said before, I feel like if I can locate the file that prints the system error then I can work backwards and locate the root cause of the problem.

Thank you for the reply anyways!

since you built OpenCV yourself, you’d have all the usual artefacts required for using the library from C++ code (as opposed to only having stuff relevant for Python). perhaps try the same logic but in C++, and see what it’ll do then. there at least you can catch any C++ exceptions and inspect them (e.what())

One thing to always do in debugging at least, is use full path for a file, in case the current directory changes, or a function tries to load it from somewhere else, for some reason

1 Like

Ok, @crackwitz I think it may be an opencv linking problem because I am trying to run video capture in a simple main.cpp file, I get an error of undefined reference to cv:videoCapture and from my understanding that normally comes up from incorrect linking of said class. I will keep debugging the error and let you know how I get on. Thank you!

@matti.vuori I agree and that will be taken into account next time :slight_smile:

This is because the compiler can’t find the OpenCV include directories and has nothing to do with your python issue.

The fact that import cv2 works means that the required dll’s have been located.

I guess my first question is how did you build/install OpenCV yourself (did you manually copy the bindings or let build install take care of it) and why? I’m asking because the installer should have added the dll’s for you inside site-packages/cv2/config.py, e.g.

import os

BINARIES_PATHS = [
    os.path.join('D:/build/opencv/cuda_12_8/install', 'x64/vc17/bin'),
    os.path.join(os.getenv('CUDA_PATH', 'C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.8'), 'bin')
] + BINARIES_PATHS

Additionally before building yourself did you try the pre-built python bindings to see if they were suitable? If not I would uninstall your build (delete the cv2 directory) install the pre-build binaries (pip install opencv-python) and confirm that you get VideoCapture to work with your video file.

Thank you so much @cudawarped . I must apologise for the late reply. I installed OpenCV by downloading the OpenCV folder and the opencv-contrib folder from github because the pre-built OpenCV library does not support Cuda and Cudnn for Gpu acceleration. This is the main reason for using a customised opencv Build/Install.

Moreover, inside my Config.py file, I have this import os

BINARIES_PATHS = [
os.path.join(‘C:/Users/CompHub/Documents/Trace-master/Trace-master/OpenCV/build/install’, ‘x64/vc17/bin’),
os.path.join(os.getenv(‘CUDA_PATH’, ‘C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6’), ‘bin’)
] + BINARIES_PATHS
and it says BINARIES_PATHS is not defined and from research the code is meant to do that?

Now, you previously said CV: video capture doesn’t relate to my Python problem, what would be the best next step, in your opinion?

Do you have any other copies of OpenCV installed, check pip list.

If not delete the cv2 folder as I suggested above and check that the standard python install can read your video.

Yh i have the Opencv installed , Here is what pip list prints ,

Package Version


absl-py 1.4.0
aiofiles 22.1.0
asgiref 3.7.2
attrs 22.1.0
backcall 0.2.0
blinker 1.6.2
cachetools 4.2.4
certifi 2022.12.7
cffi 1.17.1
charset-normalizer 3.0.1
click 8.1.7
colorama 0.4.6
colormath 3.0.0
cupy-cuda12x 13.3.0
debugpy 1.6.4
decorator 4.4.2
defusedxml 0.7.1
dill 0.2.5
distlib 0.3.6
dnspython 2.3.0
entrypoints 0.4
executing 1.2.0
fastjsonschema 2.16.2
fastrlock 0.8.2
filelock 3.12.2
Flask 2.3.0
Flask-Login 0.6.3
Flask-Script 2.0.6
Flask-SQLAlchemy 3.1.1
fqdn 1.5.1
future 0.16.0
gevent 23.9.1
google-api-core 2.14.0
google-api-python-client 2.147.0
google-auth 2.23.4
google-auth-httplib2 0.2.0
google-auth-oauthlib 1.2.1
google-cloud-core 2.3.3
google-cloud-storage 2.13.0
google-crc32c 1.5.0
google-resumable-media 2.6.0
googleapis-common-protos 1.61.0
greenlet 3.0.1
gunicorn 20.1.0
h11 0.14.0
httplib2 0.22.0
idna 3.4
imageio 2.35.1
imageio-ffmpeg 0.5.1
imutils 0.5.4
ipython-genutils 0.2.0
itsdangerous 2.1.2
jeepney 0.8.0
Jinja2 3.1.2
jsonpointer 2.3
jupyterlab-pygments 0.2.2
jupyterlab-widgets 3.0.4
lazy-object-proxy 1.9.0
login 0.0.6
MarkupSafe 2.1.3
mccabe 0.6.1
mistune 2.0.4
moviepy 1.0.3
mypy-extensions 1.0.0
nest-asyncio 1.5.6
networkx 3.2.1
numpy 1.26.2
oauthlib 3.2.2
opencv 4.10.0
packaging 22.0
pandocfilters 1.5.0
parso 0.8.3
pickleshare 0.7.5
pillow 10.4.0
pip 25.0.1
platformdirs 4.0.0
pluggy 1.2.0
ply 3.8
proglog 0.1.10
prometheus-client 0.15.0
prompt-toolkit 3.0.36
protobuf 3.19.6
psutil 5.9.4
psycopg2 2.9.9
ptyprocess 0.7.0
pure-eval 0.2.2
pyasn1 0.5.0
pyasn1-modules 0.3.0
pycodestyle 2.6.0
pycparser 2.21
pydantic 1.10.4
pydocstyle 6.3.0
pyflakes 2.2.0
Pygments 2.13.0
pymongo 4.4.0
pyparsing 3.1.0
pyreadline 2.1
pyrsistent 0.19.2
python-dateutil 2.8.2
python-json-logger 2.0.4
python-jsonrpc-server 0.4.0
pytoolconfig 1.2.5
pytz 2023.3
pywinpty 2.0.13
QtPy 2.3.0
requests 2.28.2
requests-oauthlib 2.0.0
rfc3339-validator 0.1.4
rfc3986-validator 0.1.1
rsa 4.9
scipy 1.11.4
Send2Trash 1.8.0
setuptools 75.1.0
six 1.16.0
sniffio 1.3.0
snowballstemmer 2.2.0
soupsieve 2.3.2.post1
SQLAlchemy 2.0.35
sqlparse 0.4.4
supervisor 4.2.2
tensorboard-data-server 0.7.1
tensorflow-estimator 2.12.0
termcolor 2.3.0
terminado 0.17.1
tinycss2 1.2.1
toml 0.10.2
tomli 2.0.1
tomlkit 0.11.8
tornado 6.2
tqdm 4.66.5
traitlets 5.7.1
typing_extensions 4.12.2
tzdata 2023.3
ujson 5.8.0
uri-template 1.2.0
uritemplate 4.1.1
urllib3 1.26.14
wcwidth 0.2.5
webcolors 1.12
webencodings 0.5.1
websocket-client 1.4.2
Werkzeug 2.3.0
widgetsnbextension 4.0.4
wrapt 1.14.1
zipp 3.15.0
zope.event 5.0
zope.interface 6.1

I also need to add that when i perform another process like cve.imread, it works fine so i think this problem is strictly happening for cv2.videocapture. I think this might help narrowdown the problem.

You have installed an OpenCV wheel in addintion to your manual install

opencv 4.10.0

Additionally you are adding the paths to two build directories before importing OpenCV both of which could be causing the wrong version of the opencv_videoio_ffmpeg.dll to be loaded at runtime.

ok, @cudawarped I kinda understand what you mean, but could you please let me know the next best step? do you want me uninstall opencv or delete the folder in my Site-packages folder? Thank you

  1. Uninstall the OpenCV wheel pip uninstall opencv
  2. Delete the cv2 directory
  3. Install the official OpenCV wheel pip install opencv-python
  4. Check if you can read your video file with VideoCapture
  5. If so uninstall the wheel pip uninstall opencv-python
  6. Build install OpenCV Release.
  7. import cv2 withoutthe redundant calls to os.add_dll_directory because these are all contained inside config.py
  8. Check if VideoCapture still works.

Ok,

@cudawarped I have done that and video capture work but I still want GPU acceleration to be enabled but I can’t do that with the prebuilt Opencv library as expected so what should I do now? I was trying to make The video capture class work for my custom Opencv built and not just use it with the prebuilt library online.

Do you understand? I think there might have been some miss communication?

Also I need to add that my config.py file looks different now , it only has the path to my custom opencv folder bin, import os

BINARIES_PATHS = [
‘C:/Users/CompHub/Documents/Trace-master/Trace-master/opencv/build/bin/Release’
] + BINARIES_PATHS
as opposed to what I had before which I pasted above. thank you

Did you build/install OpenCV again with CUDA? I just tested this on the latest version of OpenCV, if I delete the cv2 and build/install again nothing is built and the cv2 directory is recreated again with the BINARIES_PATHS created correctly.

If this does not work with your version of OpenCV then you can manually add the entries you had before to the config.py file, e.g.

BINARIES_PATHS = [
os.path.join(‘C:/Users/CompHub/Documents/Trace-master/Trace-master/OpenCV/build/install’, ‘x64/vc17/bin’),
os.path.join(os.getenv(‘CUDA_PATH’, ‘C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6’), ‘bin’)
] + BINARIES_PATHS

Hi @cudawarped, I just deleted the cv2 folder and installed the prebuilt library, The first thing I did was modify the config.py file like shown:

import os

BINARIES_PATHS = [
os.path.join(os.path.join(os.getenv(‘LOADER_DIR’, ‘’), ‘…/…/’), ‘x64/vc14/bin’),
os.path.join(‘C:/Users/CompHub/Documents/Trace-master/Trace-master/OpenCV/build/install’, ‘x64/vc17/bin’),
os.path.join(os.getenv(‘CUDA_PATH’, ‘C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.6’), ‘bin’)
]

if ‘BINARIES_PATHS’ in globals():
BINARIES_PATHS += globals()[‘BINARIES_PATHS’]

and videocapture was working but it didn’t seem to identify my Cuda GPU which is understandable as it is the opencv prebuilt library installed.

Then I proceeded to build and install my custom Opencv using this command (cmake --build . --config Release --target INSTALL ), then the video capture class stopped working and I was met with the same error.

My conclusion would be that there is an internal error somewhere in my custom build but I have no idea how to find it. Could it have something to do with the cv2.cp312-win_amd64.pyd file or my ffmpeg dll. I have no clue and don’t even know how to check. Thank you for all your help so far

Ok so I think I have some good news, I got it working but my solution is pretty weird because I think it might be temporary. So it turns out that the error was from the opencv_world.dll but my solution was to copy an old opencv_world.dll file and place that in my python-3.12 folder which is located in the cv2 folder.

Is there a way I could find out what caused the problem now that I have a working file?

Thoughts @cudawarped?

This is not what I meant. I meant that if you built and installed your own bindings and the paths inside config.py were different to the first time you did it (because the version of OpenCV you are using behaves differently to the latest one I am using) you could manually update the file with the same entries again because nothing else has changed. This is not necessary when you pip install.

cv2.cp312-win_amd64.pyd is just a wrapper around the OpenCV shared library stored in C:/Users/CompHub/Documents/Trace-master/Trace-master/OpenCV/build/install/x64/vc17/bin so this is unlikely. Are you using the prebuilt ffmpeg binaries now

--     FFMPEG:                      YES (prebuilt binaries)

or still providing your own? If your own how are you adding the path so that the OpenCV python bindings can locate them?

If this is the case it implies that the bindings were loading a different opencv_world.dll to the one you copied (again you can verify this with Process Monitor) are you still manually adding several build directories with the os.add_dll_directory command before import cv2? To clarify the version of opencv_world.dll and opencv_videoio_ffmpeg4xxx_64.dll you are using should be inside the C:/Users/CompHub/Documents/Trace-master/Trace-master/OpenCV/build/install/x64/vc17/bin directory and you should not be adding any other paths containing other versions of those files.