Import "cv2" could not be resolved

I've installed python and opencv by using the correct commands in the cmd, but when I type in 'import cv2' in a python then I get the error in visual studio code and I can't find any solution online how to fix this

Import "cv2" could not be resolved Pylance (reportMissingImports) 

More of the error in the terminal

ModuleNotFoundError: No module named 'cv2' 
14

7 Answers

It just happened to me and I solved it installing both opencv-python and opencv-python-headless with pip and reloading the Visual Studio Code window right after it.

To install the needed packages, just run this command in the terminal:

$ pip install opencv-python opencv-python-headless 

Make sure that its using the correct version of Python; e.g., I installed Python from the windows store, which is working:

this version is working for me

However, if I use another one, it does not work:

enter image description here

I noticed that Visual Studio does not support the latest Python 3.8, so I had to use PyCharm as an IDE.

I had a similar issue so I installed opencv-python-headless (install opencv-python if not earlier) and reloaded the VScode window.

pip install opencv-python-headless 

However, some methods like imshow() kept failing:

cv2.error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvShowImage' 

This was resolved by installing opencv-contrib-python. You can install it by running the following code in your terminal:

pip install opencv-contrib-python 

I just uninstalled the older python version and installed a new one again. That is probably the simplest and the most hassle-free one in my mind. Stick to version 3.8.8, that should do the trick. Also no worries about maintaining multiple versions of python in the system. It is indeed true that the lack of support from VS is causing this issue.

In your terminal (cmd if Windows) run the following (make sure that you're on the current working environment):

pip install opencv-python 

then:

pip install opencv-python-headless 
1

I am on a mac and struggle with this and this is the best way to do it, when ur in your .py file, on the lower left part of your vscode windown u will see the version of python you are using, click that and try different versions until your open cv command works, in my case, 3.8.8 worked for me.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like