Contents
  1. Problem Description
  2. Cause
  3. Solution

Problem Description

When using the OpenCV package, you may encounter ImportError: No module named cv2:

Problem Description

Cause

I was certain that I had already installed OpenCV, so why did it still say that the module did not exist? After looking into it, I found that OpenCV is installed for its default Python version, and if the Python version for which OpenCV is installed differs from the system’s default Python version, the module cannot be found.

For example, my computer had both python2.7 and python3.8 installed. Ubuntu used python2.7 to launch programs by default, while OpenCV was installed in the python3.8 environment.

Solution

First, make sure that you really have not installed Python support for OpenCV. You can run the following command to install it:

pip3 install opencv-python

If installing it still does not solve the problem, follow the steps below.

Change the system’s default Python version to the newer version you are using.

You can first use ls /usr/bin/python* to see which Python versions are installed on the system.

Solution

Then remove the symbolic link and change the default Python version.

sudo rm /usr/bin/python
sudo ln -s /usr/bin/python3.8 /usr/bin/python

  Restart the previous program. It now starts normally and no longer shows ImportError: No module named cv2!

Solution (2)