The error you're encountering, ImportError: DLL load failed while importing cv2: The specified module could not be found, is a common issue on Windows when embedding Python, especially with libraries like OpenCV that rely on additional DLLs.
Missing DLL Dependencies:
The OpenCV Python package (cv2) depends on various DLLs that must be accessible in your environment.
These DLLs are not always loaded automatically when embedding Python in C++.
Use a tool like Dependency Walker or Process Monitor to check which DLLs cv2.pyd depends on and if any are missing.
Add OpenCV DLL Path to System Path:
OpenCV DLLs are usually located in a folder like .../site-packages/cv2/ or in a separate bin directory of OpenCV.
You should add this directory to your process’s DLL search path at runtime before importing cv2.
In your embedded Python code, add:
cpp
PyRun_SimpleString( "import os;" "os.add_dll_directory(r'C:\\Path\\To\\OpenCV\\dlls');" );
Replace "C:\\Path\\To\\OpenCV\\dlls" with the actual path to your OpenCV DLL files.
Visual C++ Redistributable and Media Feature Pack:
Make sure the Microsoft Visual C++ Redistributable (for Visual Studio 2015 or later) is installed on your system because many DLLs depend on it.
For Windows 10/11, also install the Media Feature Pack, which has solved similar problems reported for Python 3.12 and OpenCV.
Architecture Mismatch:
Confirm that the Python interpreter, OpenCV binaries, and your C++ application are all either 64-bit or 32-bit. Mixing these causes DLL load failures.
Your CMake shows Python 3.12 64-bit, so ensure OpenCV is also 64-bit.
Python Path Configuration:
You commented out Py_SetPath. Use Py_SetPath to explicitly set your Python library and site-packages directories if environment variables aren’t set:
cpp
Py_SetPath(L"C:/Users/fxct/AppData/Local/Python/pythoncore-3.12-64/" L"Lib;" L"C:/Users/fxct/AppData/Local/Python/pythoncore-3.12-64/Lib/site-packages;");
This ensures the embedded Python interpreter can locate packages correctly.