OpenCV 4.9.0 with CUDA Build - Python: "No Module Named 'cv2'"

I’ve built OpenCV 4.9.0 from source a bunch of times…
Here’s my latest cmake:

:: Set paths 
set "openCvSource=C:/OpenCV_4.9.0/opencv"
set "openCVExtraModules=C:/OpenCV_4.9.0/opencv_contrib/modules"
set "openCvBuild=C:/OpenCV_4.9.0/build"
set "buildType=Release"
set "generator=Ninja"
set "pathToPython37Dir=C:/Python/Python37"

:: Configure
"C:/Program Files/CMake/bin/cmake.exe" ^
    -H"%openCvSource%" ^
    -DOPENCV_EXTRA_MODULES_PATH="%openCVExtraModules%" ^
    -B"%openCvBuild%" ^
    -G%generator% ^
    -DCMAKE_BUILD_TYPE=%buildType% ^
    -DBUILD_EXAMPLES=OFF ^
    -DBUILD_opencv_world=OFF ^
    -DWITH_CUDA=ON ^
    -DBUILD_opencv_python3=ON ^
    -DPYTHON3_INCLUDE_DIR=%pathToPython37Dir%/include ^
    -DPYTHON3_LIBRARY=%pathToPython37Dir%/libs/python37.lib ^
    -DPYTHON3_EXECUTABLE=%pathToPython37Dir%/python.exe ^
    -DPYTHON3_NUMPY_INCLUDE_DIRS=%pathToPython37Dir%/lib/site-packages/numpy/core/include ^
    -DPYTHON3_PACKAGES_PATH=%pathToPython37Dir%/Lib/site-packages/ ^
    -DBUILD_TESTS=OFF ^
    -DBUILD_PERF_TESTS=OFF ^
    -DBUILD_opencv_apps=OFF ^
    -DWITH_OPENGL=ON ^
    -DOPENCV_DNN_CUDA=ON ^
    -DOPENCV_ENABLE_NONFREE=ON ^
    -DBUILD_opencv_python2=OFF ^
    -DCUDA_ARCH_BIN=9.0 ^
    -DCUDA_ARCH_PTX= ^

which results in:

-- General configuration for OpenCV 4.9.0 =====================================
--   Version control:               4.9.0
--
--   Extra modules:
--     Location (extra):            C:/OpenCV_4.9.0/opencv_contrib/modules
--     Version control (extra):     4.9.0
--
--   Platform:
--     Timestamp:                   2024-12-12T20:43:36Z
--     Host:                        Windows 10.0.19045 AMD64
--     CMake:                       3.28.1
--     CMake generator:             Ninja
--     CMake build tool:            C:/PROGRA~1/MIB055~1/2022/PROFES~1/Common7/IDE/COMMON~1/MICROS~1/CMake/Ninja/ninja.exe
--     MSVC:                        1938
--     Configuration:               Release
--
--   CPU/HW features:
--     Baseline:                    SSE SSE2 SSE3
--       requested:                 SSE3
--     Dispatched code generation:  SSE4_1 SSE4_2 FP16 AVX AVX2 AVX512_SKX
--       requested:                 SSE4_1 SSE4_2 AVX FP16 AVX2 AVX512_SKX
--       SSE4_1 (16 files):         + SSSE3 SSE4_1
--       SSE4_2 (1 files):          + SSSE3 SSE4_1 POPCNT SSE4_2
--       FP16 (0 files):            + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 AVX
--       AVX (8 files):             + SSSE3 SSE4_1 POPCNT SSE4_2 AVX
--       AVX2 (36 files):           + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2
--       AVX512_SKX (5 files):      + SSSE3 SSE4_1 POPCNT SSE4_2 FP16 FMA3 AVX AVX2 AVX_512F AVX512_COMMON AVX512_SKX
--
--   C/C++:
--     Built as dynamic libs?:      YES
--     C++ standard:                11
--     C++ Compiler:                C:/Program Files/Microsoft Visual Studio/2022/Professional/VC/Tools/MSVC/14.38.33130/bin/Hostx64/x64/cl.exe  (ver 19.38.33133.0)
--     C++ flags (Release):         /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise /FS     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819  /O2 /Ob2 /DNDEBUG
--     C++ flags (Debug):           /DWIN32 /D_WINDOWS /W4 /GR  /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE /D _SCL_SECURE_NO_WARNINGS /Gy /bigobj /Oi  /fp:precise /FS     /EHa /wd4127 /wd4251 /wd4324 /wd4275 /wd4512 /wd4589 /wd4819  /Zi /Ob0 /Od /RTC1
--     C Compiler:                  C:/Program Files/Microsoft Visual Studio/2022/Professional/VC/Tools/MSVC/14.38.33130/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:precise /FS       /O2 /Ob2 /DNDEBUG
--     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:precise /FS     /Zi /Ob0 /Od /RTC1
--     Linker flags (Release):      /machine:x64  /INCREMENTAL:NO
--     Linker flags (Debug):        /machine:x64  /debug /INCREMENTAL
--     ccache:                      NO
--     Precompiled headers:         NO
--     Extra dependencies:          cudart_static.lib nppc.lib nppial.lib nppicc.lib nppidei.lib nppif.lib nppig.lib nppim.lib nppist.lib nppisu.lib nppitc.lib npps.lib cublas.lib cudnn.lib cufft.lib -LIBPATH:"C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v12.3/lib/x64"
--     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 stereo stitching structured_light superres surface_matching text tracking video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
--     Disabled:                    world
--     Disabled by dependency:      -
--     Unavailable:                 alphamat cannops cvv freetype hdf java julia matlab ovis python2 sfm ts viz
--     Applications:                -
--     Documentation:               NO
--     Non-free algorithms:         YES
--
--   Windows RT support:            NO
--
--   GUI:                           WIN32UI
--     Win32 UI:                    YES
--     OpenGL support:              YES (opengl32 glu32)
--     VTK support:                 NO
--
--   Media I/O:
--     ZLib:                        build (ver 1.3)
--     JPEG:                        build-libjpeg-turbo (ver 2.1.3-62)
--       SIMD Support Request:      YES
--       SIMD Support:              NO
--     WEBP:                        build (ver encoder: 0x020f)
--     PNG:                         build (ver 1.6.37)
--     TIFF:                        build (ver 42 - 4.2.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:
--     DC1394:                      NO
--     FFMPEG:                      YES (prebuilt binaries)
--       avcodec:                   YES (58.134.100)
--       avformat:                  YES (58.76.100)
--       avutil:                    YES (56.70.100)
--       swscale:                   YES (5.9.100)
--       avresample:                YES (4.0.0)
--     GStreamer:                   YES (1.22.8)
--     DirectShow:                  YES
--     Media Foundation:            YES
--       DXVA:                      YES
--
--   Parallel framework:            Concurrency
--
--   Trace:                         YES (with Intel ITT)
--
--   Other third-party libraries:
--     Intel IPP:                   2021.11.0 [2021.11.0]
--            at:                   C:/OpenCV_4.9.0/build/3rdparty/ippicv/ippicv_win/icv
--     Intel IPP IW:                sources (2021.11.0)
--               at:                C:/OpenCV_4.9.0/build/3rdparty/ippicv/ippicv_win/iw
--     Lapack:                      NO
--     Eigen:                       NO
--     Custom HAL:                  NO
--     Protobuf:                    build (3.19.1)
--     Flatbuffers:                 builtin/3rdparty (23.5.9)
--
--   NVIDIA CUDA:                   YES (ver 12.3, CUFFT CUBLAS NVCUVID NVCUVENC)
--     NVIDIA GPU arch:             90
--     NVIDIA PTX archs:
--
--   cuDNN:                         YES (ver 8.9.7)
--
--   OpenCL:                        YES (NVD3D11)
--     Include path:                C:/OpenCV_4.9.0/opencv/3rdparty/include/opencl/1.2
--     Link libraries:              Dynamic load
--
--   Python 3:
--     Interpreter:                 C:/Python/Python37/python.exe (ver 3.7)
--     Libraries:                   C:/Python/Python37/libs/python37.lib (ver 3.7.0)
--     numpy:                       C:/Python/Python37/Lib/site-packages/numpy/core/include (ver 1.21.6)
--     install path:                C:/Python/Python37/Lib/site-packages//cv2/python-3.7
--
--   Python (for build):            C:/Python/Python37/python.exe
--
--   Java:
--     ant:                         NO
--     Java:                        NO
--     JNI:                         NO
--     Java wrappers:               NO
--     Java tests:                  NO
--
--   Install to:                    C:/OpenCV_4.9.0/build/install
-- -----------------------------------------------------------------
--
-- Configuring done (38.0s)
-- Generating done (2.4s)
-- Build files have been written to: C:/OpenCV_4.9.0/build

The cv2.pyd file is in C:/Python/Python37/Lib/site-packages//cv2/python-3.7 when the build completes. In C:/Python/Python37/Lib/site-packages//cv2 there’s a bunch of folders with OpenCV module names, and __init__.pyi files. Presumably these are Python stubs used for type hints, etc…

My Python project is a simple test project, so far with only:

import cv2

in main.py.

For the life of me I can’t even get past this import statement without some form of, No module name 'cv2', Cannot load DLL, etc… errors.

  • I have copied the full contents of C:/Python/Python37/Lib/site-packages//cv2 into <Python Project Root Folder>/venv/site-packages/cv2.
  • I have tried putting cv2.pyd in every folder: <Python Project Root Folder>/venv/site-packages, <Python Project Root Folder>/venv/site-packages/cv2, <Python Project Root Folder>/venv/site-packages/cv2/python-3.7. Everywhere I put it, it can’t be found.
  • I’ve placed the DLLs from the build folder into all of the same above folders with no luck.

Have been at this for a few days with no successes other than being able to (seemingly) build OpenCV.

I do get type hints in PyCharm when I start typing cv2. - I’ll get a list of modules, functions, etc… I think this is because of all the sub-folders in <Python Project Root Folder>/venv/site-packages/cv2 with those pyi files.

A colleague of mine has done this same process months ago and has it working on his machine with cv2.pyd and all DLL files placed in the <Python Project Root Folder>/venv/site-packages folder.

I’m not even sure what to try next – I must be missing something.

Can anyone out there offer some ideas / pointers?

Thanks in advance,
R

First, when you say /venv/site-packages/cv2 is that correct or is it /venv/Lib/site-packages/cv2? If its the first then depending on your python distro you may have copied things to the wrong directory.

If that’s not the issue then from reading your description. It looks like you:

  1. Built the bindings and set PYTHON3_PACKAGES_PATH=C:/Python/Python37/Lib/site-packages instead of the directory containing your virtual environment (<Python Project Root Folder>/venv/Lib/site-packages).
  2. Tried to import cv2 when in venv but the cv2 directory could not be found as it was installed in the base environment not venv.
  3. Copied not installed everything from the base to your virtual environment and then got some other errors, possibly including
  1. Now you have

and everything is in a bit of a mess.

Does this sound correct?

If so I would start by removing all the files and folders you have manually copied because this could lead to a lot of extra errors.

Then if you successfully remove all of them, try import cv2 from the base environment (where I am assuming you initially installed to from what you have said above) and post the full text of any errors you get. In addition post the contents of your <Python Project Root Folder>/site-packages/cv2\config.py file?

This article has more details regarding the different errors you may encounter.

Hey, thanks for the reply and sorry for my lack of follow-thru, I’ve been working on something else the last few weeks…

Yes, I believe this is the case - I think this was a typo in my post, I’ll have a look to make sure.

Ah, ok… I have to build against the venv? I swear I tried that and it failed.
I’ll give that a go and see what results.

Thanks for your reply!! When I get back to this I’ll update the thread.

Thank you.