How to fix ModuleNotFoundError: No module named 'cv2' error

Endrit Qerreti

Endrit Qerreti

In this tutorial, you will learn how to fix "ModuleNotFoundError: No module named 'cv2'" error.

I was trying to run my python app today, and I got the error "ModuleNotFoundError: No module named 'cv2'" on my terminal.

This error happened because I was importing the opencv module in my python code, without having this module installed on my machine.

So the solution to this error, is by simply installing the missing module before running the python code, in this tutorial, I'll be be showing you how to easily fix this error.

Step 1 - Update package index

Before installing cv2 module on your system, make sure that your machine is up to date.

In this tutorial, we are using Ubuntu 22.04, so to update Ubuntu 22.04, we can easily do so by using the apt package manager.

sudo apt update

Step 2 - Install cv2 module

cv2 module is part of the package python3-opencv, this is the package that is missing that needs to be installed in order to fix this error.

Installing python3-opencv package, is very simple, and it can be done directly from the terminal, as python3-opencv package is available for Ubuntu 22.04 in the Universe repository.

To install python3-opencv, simply run the following.

sudo apt install python3-opencv -y

Step 3 - Verify

Once you install the opencv module, now you need to check that the error is fixed. In my case I was getting the error once I tried to run the python script, so I tried running it after installing the missing module, and the error was gone.

If you are facing other issues even after installing the python3-opencv module, you can run a simple python script that only imports the cv2 module, and see if the error "ModuleNotFoundError: No module named 'cv2' error" is fixed.

For example, when you run the code below, if cv2 module is installed it should print "Yes the cv2 module is working now" , if cv2 module is not successfully installed or broken, then it should not print the message but the error instead.

#!/usr/bin/env python3


import cv2

print("Yes, the cv2 module is working now")

Conclusion

In this tutorial, you learned how to fix ModuleNotFoundError: No module named 'cv2' error that happens when opencv module is not installed.