ModuleNotFoundError: No module named 'cv2'
The import name is cv2 but the pip package is opencv-python — installing "cv2" gets you nothing. Install exactly one OpenCV variant per environment.
Updated
The error
ModuleNotFoundError: No module named 'cv2'
What it means
Python cannot find OpenCV's module in the environment that ran your code. OpenCV has a naming quirk that earns it a page beyond the generic missing-module case: the import name (cv2) and the install name (opencv-python) are different words. pip install cv2 does not exist as the thing you want, and people loop on this error while "installing cv2" repeatedly.
Why it happens
Either OpenCV was never installed under its real name, it was installed into a different environment than the one running (the classic split — see the torch page for the full diagnosis), or the environment holds a broken mix of OpenCV variants.
How to fix it
1. Install the right package name, into the right interpreter.
python -m pip install opencv-pythonIn notebooks:
%pip install opencv-pythonThen restart the kernel and import cv2 again.
2. Know the four official variants — and install exactly one.
| Package | Contents |
|---|---|
| opencv-python | main modules, with GUI support |
| opencv-python-headless | main modules, no GUI — for servers and Docker |
| opencv-contrib-python | main + extra (contrib) modules, with GUI |
| opencv-contrib-python-headless | main + contrib, no GUI |
Two variants installed together shadow each other unpredictably — a frequent cause of "cv2 imports but imshow broke". Clean up to one:
pip uninstall -y opencv-python opencv-python-headless opencv-contrib-python opencv-contrib-python-headless
pip install opencv-pythonPick headless for servers, contrib when you need modules like cv2.aruco.
3. If cv2 imports but errors mention DLLs or libGL, follow the specific pages. ImportError: DLL load failed on Windows and libGL.so.1 on Linux are environment problems with their own fixes — related links below.
4. Environment mismatch symptoms? Diagnose which Python ran.
import sys; print(sys.executable)The full environment-detective procedure lives on the No module named 'torch' page and applies unchanged.
How to prevent it
Remember the pairing "import cv2, install opencv-python" the way you remember "import sklearn, install scikit-learn" and "import PIL, install pillow". Put the correct variant in requirements.txt so servers get headless and workstations get GUI deliberately, not by accident.
Related errors
- ModuleNotFoundError: No module named 'torch' — the general environment diagnosis
- The function is not implemented (OpenCV GUI) — what the headless/GUI mix-up causes
- cv2.error: (-215:Assertion failed)
- ImportError: DLL load failed