opencv: Another "ImportError: DLL load failed while importing cv2: The specified module could not be found."

I have looked at other posts in regards “ImportError: DLL load failed while importing cv2: The specified module could not be found” and they were to no avail.

Information about my attempted installation Python: 3.8.9 (tags/v3.8.9:a743f81, Apr 6 2021, 14:02:34) [MSC v.1928 64 bit (AMD64)] on win32 MSVC: Microsoft Visual Studio 2019, Version 16.8.4 OS: Win 7 CMake gui: 3.20.1

Source cv2 files version: 4.5.2 Source files: https://github.com/opencv/opencv with download link https://github.com/opencv/opencv/archive/refs/heads/master.zip https://github.com/opencv/opencv_contrib with download link https://github.com/opencv/opencv_contrib/archive/refs/heads/master.zip

I will describe the steps that appeared to look like everything is OK but when instantiating cv2, the “Import DLL …” error occurred.

Using CMake Setup of files image

Pressing the “Configure” button

During the configure phase received this warning, but don’t know what it means.

CMake Warning at cmake/OpenCVGenSetupVars.cmake:54 (message):
CONFIGURATION IS NOT SUPPORTED: validate setupvars script in install
directory
Call Stack (most recent call first):
CMakeLists.txt:1010 (include)

The configuration obtained this information:

Platform:
Timestamp: 2021-04-24T15:47:32Z
Host: Windows 6.1.7601 AMD64
CMake: 3.20.1
CMake generator: Visual Studio 16 2019
CMake build tool: C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/MSBuild/Current/Bin/MSBuild.exe
MSVC: 1928
Configuration: Debug Release

Last part of the configuration shows installationl Install to: C:/Python38/opencv/build/install

Configuring done

From the CMake output: opencv-contrib

image

GStreamer was installed - here are the locations of the libs and directories which were automatically determined by the correct paths ofthe GStreamer image

Current python installation image

No other packages were checked. That is no BLAS, no LAPACK - no additional checking.

Pressing CMake’s “Generate” button General output

General configuration for OpenCV 4.5.2-dev =====================================
Version control: unknown

Extra modules:
Location (extra): C:/Python38/opencv/opencv_contrib-master/modules

Version control (extra): unknown

Platform: Timestamp: 2021-04-24T15:47:32Z Host: Windows 6.1.7601 AMD64 CMake: 3.20.1 CMake generator: Visual Studio 16 2019 CMake build tool: C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/MSBuild/Current/Bin/MSBuild.exe MSVC: 1928 Configuration: Debug Release

Other information from generation

Python 3:
Interpreter: C:/Python38/python.exe (ver 3.8.9)
Libraries: optimized C:/Python38/libs/python38.lib debug C:/Python38/libs/python38_d.lib (ver 3.8.9)
numpy: c:/python38/lib/site-packages/numpy/core/include (ver 1.20.2)
install path: C:/Python38/Lib/site-packages/cv2/python-3.8

Python (for build): C:/Python38/python.exe

Java: 
ant: NO
JNI: C:/Program Files/Java/jdk1.8.0_121/include C:/Program Files/Java/jdk1.8.0_121/include/win32 C:/Program Files/Java/jdk1.8.0_121/include
Java wrappers: NO
Java tests: NO

Install to: C:/Python38/opencv/build/install
-----------------------------------------------------------------

Configuring done
Generating done

From the above, there appears nothing of concern.

Using the MS Visual Studio 2019 First we get the OpenCV.sln file located in C:\Python38\opencv\build

Opening OpenCV.sln with MS Visual Studio 2019. In the “Solution Explorer”, first build by right clicking on “ALL_BUILD” No error messages from the build of “ALL_BUILD” In the “Solution Explorer”, build the “INSTALL” by right clicking on “INSTALL” No errors from the build of “INSTALL” image

Now in Python’s IDLE, do the following

Python 3.8.9 (tags/v3.8.9:a743f81, Apr  6 2021, 14:02:34) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import cv2
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import cv2
ImportError: DLL load failed while importing cv2: The specified module could not be found.
>>> 

Other questions:

  • What is the DLL file that failed to load?
  • Is there anything else I could do

Thank you, Anthony of Sydney

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 34 (9 by maintainers)

Most upvoted comments

I modified init.py in cv2 repository to use my own python binding (build_shared=ON)

'''
OpenCV Python binary extension loader
'''
import os
import sys

__all__ = []
#NEWLINE for my OWN CONFIGURATION
os.add_dll_directory(r'G:\Lib\install\opencv\x64\vc15\bin')
os.add_dll_directory(r'G:\Lib\install\vtk\bin')
os.add_dll_directory(r'G:\Lib\install\ceres-solver\bin')
os.add_dll_directory(r'G:\Lib\install\glog\bin')
os.add_dll_directory(r'F:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2\bin')
os.add_dll_directory(r'F:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2')
#that's all
try:
    import numpy
    import numpy.core.multiarray
except ImportError:
    print('OpenCV bindings requires "numpy" package.')
    print('Install it via command:')
    print('    pip install numpy')
    raise


py_code_loader = None
if sys.version_info[:2] >= (3, 0):
    try:
        from . import _extra_py_code as py_code_loader
    except:
        pass

# TODO
# is_x64 = sys.maxsize > 2**32

def bootstrap():
    import sys

    import copy
    save_sys_path = copy.copy(sys.path)

    if hasattr(sys, 'OpenCV_LOADER'):
        print(sys.path)
        raise ImportError('ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.')
    sys.OpenCV_LOADER = True

    DEBUG = False
    if hasattr(sys, 'OpenCV_LOADER_DEBUG'):
        DEBUG = True

    import platform
    if DEBUG: print('OpenCV loader: os.name="{}"  platform.system()="{}"'.format(os.name, str(platform.system())))

    LOADER_DIR = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))

    PYTHON_EXTENSIONS_PATHS = []
    BINARIES_PATHS = []

    g_vars = globals()
    l_vars = locals()

    if sys.version_info[:2] < (3, 0):
        from . load_config_py2 import exec_file_wrapper
    else:
        from . load_config_py3 import exec_file_wrapper

    def load_first_config(fnames, required=True):
        for fname in fnames:
            fpath = os.path.join(LOADER_DIR, fname)
            if not os.path.exists(fpath):
                if DEBUG: print('OpenCV loader: config not found, skip: {}'.format(fpath))
                continue
            if DEBUG: print('OpenCV loader: loading config: {}'.format(fpath))
            exec_file_wrapper(fpath, g_vars, l_vars)
            return True
        if required:
            raise ImportError('OpenCV loader: missing configuration file: {}. Check OpenCV installation.'.format(fnames))

    load_first_config(['config.py'], True)
    load_first_config([
        'config-{}.{}.py'.format(sys.version_info[0], sys.version_info[1]),
        'config-{}.py'.format(sys.version_info[0])
    ], True)

    if DEBUG: print('OpenCV loader: PYTHON_EXTENSIONS_PATHS={}'.format(str(l_vars['PYTHON_EXTENSIONS_PATHS'])))
    if DEBUG: print('OpenCV loader: BINARIES_PATHS={}'.format(str(l_vars['BINARIES_PATHS'])))

    for p in reversed(l_vars['PYTHON_EXTENSIONS_PATHS']):
        sys.path.insert(1, p)

    if os.name == 'nt':
        if sys.version_info[:2] >= (3, 8):  # https://github.com/python/cpython/pull/12302
            for p in l_vars['BINARIES_PATHS']:
                try:
                    os.add_dll_directory(p)
                except Exception as e:
                    if DEBUG: print('Failed os.add_dll_directory(): '+ str(e))
                    pass
        os.environ['PATH'] = ';'.join(l_vars['BINARIES_PATHS']) + ';' + os.environ.get('PATH', '')
        if DEBUG: print('OpenCV loader: PATH={}'.format(str(os.environ['PATH'])))
    else:
        # amending of LD_LIBRARY_PATH works for sub-processes only
        os.environ['LD_LIBRARY_PATH'] = ':'.join(l_vars['BINARIES_PATHS']) + ':' + os.environ.get('LD_LIBRARY_PATH', '')

    if DEBUG: print('OpenCV loader: replacing cv2 module')
    del sys.modules['cv2']
    import cv2

    sys.path = save_sys_path  # multiprocessing should start from bootstrap code (https://github.com/opencv/opencv/issues/18502)

    try:
        import sys
        del sys.OpenCV_LOADER
    except:
        pass

    if DEBUG: print('OpenCV loader: binary extension... OK')

    if py_code_loader:
        py_code_loader.init('cv2')

    if DEBUG: print('OpenCV loader: DONE')

bootstrap()

Hey @AnthonyTheKoala !! Greetings!

I Solved my problem… I had been done all you mentioned about build your own opencv from source with cuda support and use it from inside python, but with no success… Then I saw a lot of people showing they had solved their problems… Problems identical the one of this issue you opened. Everybody solved in a simple way. I had installed my python 3.8.3 from windows store… then I thought… why everyone says they had the problem solved in a simple way… Dependency walker showed that the files api-ms-win-xxx.dll have not been found and I thought that this is not the problem because I have been programing windows shared libraries since 2000’s and dependency walker never found the windows related dependent libraries. Its normal from my C/C++ developer point of view… And the api-ms-win-xxx files are already into my computers folder c:\windows\winsxs\x86_microsoft_windows-mxxxxx…

image

The only solution remained in my mind was… If the majority of the people that related success on directly build OpenCV with CUDA support, from sources and with no issues got ‘import cv2’ working said they built OpenCV with Anaconda’s python. Then I installed Anaconda3 and rebuilt OpenCV with Anaconda’s python and, voilá!!

I perceived after this try that anaconda’s folder have all api-ms-win-xxxx.dll inside… the only one difference. But I intend to try install python3.9 from windows store (as before), check the dll files inside python3.9’s folder and use an old build of opencv that I stored here. If the problem of “ImportError: DLL load faliled while importing cv2: The specific module could not be found” persist, I’ll copy the api-ms-win-xxx.dll files from anaconda’s python folder to the python3.9 folder and try to run ‘import cv2’ and see what will happen.

image

FYI: image

Thank you very much about every help you gived me! Obrigado! Claudio Marques

It’s been giving me headaches for a while. Does anyone have a solution?

I tried for a while and got it to work last week, I made a repo to document it (see the issue mentioned just above ☝) because it was not so fun to understand all the problems/solutions discussed here. So maybe go have a look and tell us if it helps? Here you can always detail where you are stuck, what you already tried, how you are trying to install OpenCV, etc, more information is always good!

In short what made it work for me was adding every possible DLL folder I could find with os.add_dll_directory() before using import cv2 because apparently Python didn’t check the paths in the environment variables.

In reply to: https://github.com/opencv/opencv/issues/19972#issuecomment-853981765

ing Toolkit\CUDA\v11.2\bin')
os.add_dll_directory(r'F:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.2')
#that's all
try:
    import numpy
    import numpy.core.multiarray
except ImportError:
    print('OpenCV bindings requires "numpy" package.')
    print('Install it via command:')
    print('    pip install numpy')
    raise


py_code_loader = None
if sys.version_info[:2] >= (3, 0):
    try:
        from . import _extra_py_code as py_code_loader
    except:
        pass

# TODO
# is_x64 = sys.maxsize > 2**32

def bootstrap():
    import sys

    import copy
    save_sys_path = copy.copy(sys.path)

    if hasattr(sys, 'OpenCV_LOADER'):
        print(sys.path)
        raise ImportError('ERROR: recursion is detected during loading of "cv2" binary extensions. Check OpenCV installation.')
    sys.OpenCV_LOADER = True

    DEBUG = False
    if hasattr(sys, 'OpenCV_LOADER_DEBUG'):
        DEBUG = True

    import platform
    if DEBUG: print('OpenCV loader: os.name="{}"  platform.system()="{}"'.format(os.name, str(platform.system())))

    LOADER_DIR = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))

    PYTHON_EXTENSIONS_PATHS = []
    BINARIES_PATHS = []

    g_vars = globals()
    l_vars = locals()

    if sys.version_info[:2] < (3, 0):
        from . load_config_py2 import exec_file_wrapper
    else:
        from . load_config_py3 import exec_file_wrapper

    def load_first_config(fnames, required=True):
        for fname in fnames:
            fpath = os.path.join(LOADER_DIR, fname)
            if not os.path.exists(fpath):
                if DEBUG: print('OpenCV loader: config not found, skip: {}'.format(fpath))
                continue
            if DEBUG: print('OpenCV loader: loading config: {}'.format(fpath))
            exec_file_wrapper(fpath, g_vars, l_vars)
            return True
        if required:
            raise ImportError('OpenCV loader: missing configuration file: {}. Check OpenCV installation.'.format(fnames))

    load_first_config(['config.py'], True)
    load_first_config([
        'config-{}.{}.py'.format(sys.version_info[0], sys.version_info[1]),
        'config-{}.py'.format(sys.version_info[0])
    ], True)

    if DEBUG: print('OpenCV loader: PYTHON_EXTENSIONS_PATHS={}'.format(str(l_vars['PYTHON_EXTENSIONS_PATHS'])))
    if DEBUG: print('OpenCV loader: BINARIES_PATHS={}'.format(str(l_vars['BINARIES_PATHS'])))

    for p in reversed(l_vars['PYTHON_EXTENSIONS_PATHS']):
        sys.path.insert(1, p)

    if os.name == 'nt':
        if sys.version_info[:2] >= (3, 8):  # https://github.com/python/cpython/pull/12302
            for p in l_vars['BINARIES_PATHS']:
                try:
                    os.add_dll_directory(p)
                except Exception as e:
                    if DEBUG: print('Failed os.add_dll_directory(): '+ str(e))
                    pass
        os.environ['PATH'] = ';'.join(l_vars['BINARIES_PATHS']) + ';' + os.environ.get('PATH', '')
        if DEBUG: print('OpenCV loader: PATH={}'.format(str(os.environ['PATH'])))
    else:
        # amending of LD_LIBRARY_PATH works for sub-processes only
        os.environ['LD_LIBRARY_PATH'] = ':'.join(l_vars['BINARIES_PATHS']) + ':' + os.environ.get('LD_LIBRARY_PATH', '')

    if DEBUG: print('OpenCV loader: replacing cv2 module')
    del sys.modules['cv2']
    import cv2

    sys.path = save_sys_path  # multiprocessing should start from bootstrap code (https://github.com/opencv/opencv/issues/18502)

    try:
        import sys
        del sys.OpenCV_LOADER
    except:
        pass

    if DEBUG: print('OpenCV loader: binary extension... OK')

    if py_code_loader:
        py_code_loader.init('cv2')

    if DEBUG: print('OpenCV loader: DONE')

bootstrap()

Yes, including an explicit include set of declarations in init.py works perfectly:

Windows 10 & 11 professional. opencv 4.6

New explicit include lines start

os.add_dll_directory(r’D:\TOOLS\opencv-build-vc\install\x64\vc16\bin’) os.add_dll_directory(r’C:\ProgramData\Anaconda3\Library\bin’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\bin’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDNN\v8.8.0\bin’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDNN\v8.8.0’)

New explicit include lines over

image

And, it works without anaconda dll directory refernce also:

New explicit include lines start

os.add_dll_directory(r’D:\TOOLS\opencv-build-vc\install\x64\vc16\bin’)

os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8\bin’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.8’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDNN\v8.8.0\bin’) os.add_dll_directory(r’C:\Program Files\NVIDIA GPU Computing Toolkit\CUDNN\v8.8.0’)

New explicit include lines over

sorry for the confusion, you were NOT to do cmake -D BUILD_SHARED_LIBS=OFF like that, but either add BUILD_SHARED_LIBS=OFF to an (existing) cmake cmdline, or, unchecking the BUILD_SHARED_LIBS box in cmake-gui

also, make sure you run the INSTALL project, and check the timestamp of your cv2.pyd

then, AVOID all fancy ide’s / editors / notebooks, until you have a successful install.