OpenCV build in Windows with PyTorch

I built OpenCV from source in Windows 10 to include modules from contrib (namely, cuda optical flow stuff). I’m using OpenCV exclusively from Python 3, and I cannot import PyTorch after OpenCV. E.g.,

import cv2
import torch

gives me

OSError: [WinError 127] The specified procedure could not be found. Error loading "C:\Users\1\decipher-ai\venv\lib\site-packages\torch\lib\cublas64_11.dll" or one of its dependencies.

However, with

import torch
import cv2

Both packages run fine.

This is how I created the build files:

cmake -S ..\sources\opencv-4.5.2\ -G "Visual Studio 16 2019" -D CMAKE_BUILD_TYPE=Release -D OPENCV_EXTRA_MODULES_PATH=../sources/opencv_contrib-4.5.2/modules -D WITH_CUDA=ON -D OPENCV_DNN_CUDA=ON -D CMAKE_INSTALL_PREFIX=../4.5.2 -D BUILD_SHARED_LIBS=OFF

I’m building with Visual Studio 2019.

I thought BUILD_SHARED_LIBS=OFF was going to make a static build which wouldn’t require DLLs being in the path, but it didn’t make any difference.

I mucked with

\Lib\site-packages\cv2\__init__.py

thinking it was an issue of what it was adding to the DLL path or system path, but nothing seems to work. Any ideas?

P.S. - this is with regular Python 3.8, not Anaconda.

[Edit 2021-05-11]: Version details:
Cuda 11.3
OpenCV 4.5.2 - htt ps://github.com/opencv/opencv/releases/tag/4.5.2
OpenCV Contrib 4.5.2 - htt ps://github.com/opencv/opencv_contrib/releases/tag/4.5.2
Python 3.8.10 (from Python.org, not Windows App Store)
PyTorch (stable) installed for Cuda 11.1, as per their website, i.e.

pip3 install torch==1.8.1+cu111 torchvision==0.9.1+cu111 torchaudio===0.8.1 -f https://download.pytorch.org/whl/torch_stable.html

Sorry, had to break up those github URLs due to this two link per post limit…

@cvilio ,
I have the same issue on Win10, Python 3.7, PyTorch 1.8.1+cu111 and OpenCV 4.5.2.
I think, this is a problem of PyTorch as I came across this (as of today) open issue: DataLoader with cv2 and some numpy/cv2 import order causes workers to not work · Issue #45198 · pytorch/pytorch · GitHub.

You could try the workaround, that is proposed there and flip the order of importing numpy and torch.

1 Like