How to fix modulenotfounderror: no module named cv2 in Python?

In this tutorial, we will learn how to troubleshoot import errors related to the opencv for python module.

In a nutshell, Python import errors occur when calling a specific module that is not yet installed in the Python development environment that you are using (either because you forgot to install them or you are using the wrong environment).

Here’s a screenshot of the No module found cv2 error as seen in Jupyter Notebooks/ Lab. You might have encountered this error in PyCharm, VS Code, Spyder or any other Python development environment.

Why Python shows the modulenotfound error for opencv-python?

Most probably, because opencv-python is not installed on your Python environment. The opencv-python module is not shipped as part of the Python standard library, hence it has to be installed separately before being used. When installing the module, ensure that you are installing it in the right Python (virtual) environment.

How to fix the no module named cv2 error?

For Global / Virtual Environments (Venv)

To install the cv2 module in your environment (global or virtual) you can use the Python Package Installer tool (pip).

  • Save or discard changes to open Python programs and close your Python Editor / IDE.
  • Open your Windows command prompt or Terminal
  • Navigate to the root directory of your environment.
  • Type the following command:
pip install opencv-python

# alternatively for Python3

pip3 install opencv-python

  • Your package will be collected and installed. Once done, you can reopen your Python IDE and continue importing cv2.

For Anaconda / Conda environments

If you are using the Anaconda distribution or just Miniconda, you should proceed a little bit differently:

  • Save or discard changes to your open Python programs.
  • Close your Python Editor / IDE.
  • In Windows, open the conda command prompt. In Linux or macOS open a terminal window.
  • Type the following command:
conda activate <your conda env path name here>
  • Then type:
conda install opencv-python
  • Re-open your Python Editor and import the cv2 module.