I am trying to run a basic computer vision script to detect edges in images, but I keep getting the ModuleNotFoundError: No module named 'cv2' error. I thought I installed it via the terminal using pip, but the script still fails to recognize the library. Does this have to do with my virtual environment settings or a path issue in VS Code? I really need a step-by-step guide for a Windows setup.
3 answers
The issue usually stems from a mismatch between the environment where you installed the package and the interpreter selected in your IDE. First, ensure you run pip install opencv-python in the correct terminal. If you are using a virtual environment like venv or conda, you must activate it before installing. In VS Code, use Ctrl+Shift+P, type "Python: Select Interpreter," and choose the version that matches your environment. Sometimes, installing opencv-contrib-python provides additional modules that might be missing in the main package. This should clear the pathing error immediately.
Have you checked if you have multiple versions of Python installed on your machine? Sometimes pip installs to Python 3.9 while your project is actually running on 3.11, causing the module to be "missing" despite a successful installation.
Usually, this is just a missing package. Run pip install opencv-python in your command prompt. If you're on Linux, you might also need apt-get install libgl1 to handle the GUI dependencies.
Joshua is right about the Linux dependencies. I had the same error on my Ubuntu server and installing the libgl1-mesa-glx package was the only thing that actually fixed the import error.
You hit the nail on the head, Mark! I checked my path and realized I had a global install and a local one. To fix this, I used python -m pip install opencv-python which ensures the library is attached to the specific executable I'm running. Now the cv2 import works perfectly in my scripts!