Installed opencv but having trouble importing it

Hi all,

I recently downloaded anaconda python in order to work on an opencv personal project.

I installed opencv using pip install opencv-contrib-python, where it installed successfully. Now, when I type import cv2 in my .py file, I get the following error:

ModuleNotFoundError: No module named 'cv2'

I’m a beginner, so I really don’t know what is happening. Here are some things that can maybe help:

where pip

C:\Users\Lildu\anaconda3\Scripts\pip.exe

where python

C:\msys64\ucrt64\bin\python.exe

Any help would be appreciated, thanks!

Hi,

in your command prompt (NOT Python interpreter), type:

pip install cv2

to install this module into your packages folder.

Careful not to mix up the name of a distribution package with the name(s) of the import package(s) it provides. In this case the distribution the OP wants to install is opencv-contrib-python, which provides the import package cv2.

Looks like you have multiple Python installations (MSYS2, anaconda, and possibly more). The first pip and python commands on your path are coming from different installations. Hence when you ran pip install ..., you installed opencv to a different interpreter than the one the the python command corresponds to.

Ordinarily the best way to make sure you install packages to the right interpreter is to use python -m pip instead of pip. That way, you can be sure that you’re invoking pip for the same interpreter you’ll be using to run your code instead of whatever pip happens to come first on your PATH. However, in this case, it looks like python isn’t the Python interpreter that you want to use — that interpreter is coming from MSYS2, not Anaconda. To use your Anaconda interpreter, you’ll likely need to either a) tweak you PATH to put the Anaconda bin directory before the MSYS2 one, or b) spell out the absolute path to the interpreter you want to use (possibly C:\Users\Lildu\anaconda3\Scripts\python.exe, I’m not too familiar with Anaconda on Windows), or c) activate a new conda/virtual environment, which should prepend the interpreter you want to the front of your PATH.

2 Likes

Hi Brian!

Thanks for the help, that was exactly what was happening. I was using the mysys64 python instead of the anaconda3 python (different versions), and the pip installed on the anaconda3 version. I went into VSCode and changed my interpreter accordingly. It works now.

Thanks again for the help, I appreciate it!