'How can I solve No module named 'cv2' issue?

I am unable to import opencv in python. Running import cv2 throws the following error.

ModuleNotFoundError: No module named 'cv2'

I've installed the following packages but they did not work:

pip3 install opencv-contrib-python==4.4.0.46

pip3 install opencv-contrib-python-headless==4.4.0.46

I'm using Windows.



Solution 1:[1]

Have you simultaneously installed the packages you mentioned? If yes, this may be causing the issue. You should not install these packages simultaneously. If you do not have any GUI dependencies, then go for the headless version.

b. Packages for server (headless) environments (such as Docker, cloud environments etc.), no GUI library dependencies

These packages are smaller than the two other packages above because they do not contain any GUI functionality (not compiled with Qt / other GUI components). This means that the packages avoid a heavy dependency chain to X11 libraries and you will have for example smaller Docker images as a result. You should always use these packages if you do not use cv2.imshow et al. or you are using some other package (such as PyQt) than OpenCV to create your GUI.

What you can do now is remove all the installed versions of opencv. Then, install the following:

pip install opencv-python
pip install opencv-contrib-python

If you are unable to decide what packages you want to install, you can read the details here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fam