This error typically arises from naming conflicts or circular imports when using OpenCV’s Python bindings. The interpreter inadvertently loads your own module instead of the official cv2 package. Follow these steps to diagnose and fix the issue.
1. Check Your Script and Module Names
If your script or any file in the same directory is named cv2.py or cv2.pyc, Python will import it instead of OpenCV’s package.
# WRONG: this shadows the real cv2
project/
├─ cv2.py
└─ main.py
Rename your file and remove stale bytecode:
mv cv2.py my_cv_utils.py
find . -name "cv2*.pyc" -delete
2. Inspect Circular Imports
Circular imports occur when module A imports B and B imports A. In OpenCV usage, ensure that you import cv2 only at top and don’t have interdependent imports involving img attributes.
# BAD: circular import
# utils.py
from img_processing import process_image
# img_processing.py
import utils
import cv2
Refactor to remove the cycle:
# utils.py
# only helper functions, no imports of img_processing
# img_processing.py
import cv2
from utils import helper_function
3. Clear Residual Bytecode and Cache
Python may load stale .pyc files. Remove __pycache__ directories:
find . -type d -name "__pycache__" -exec rm -r {} +
4. Verify OpenCV Installation
Ensure you have the official package installed and no conflicting versions:
pip uninstall opencv-python opencv-contrib-python
pip install --upgrade opencv-python
5. Test in a Clean Environment
Create and activate a virtual environment to isolate dependencies:
python3 -m venv venv
source venv/bin/activate
pip install opencv-python
python -c "import cv2; print(cv2.__version__)"
6. Summary Checklist
- Rename any
cv2.pyor conflicting filenames in your project. - Remove stale
.pycfiles and__pycache__directories. - Refactor imports to eliminate circular dependencies.
- Reinstall the official
opencv-pythonpackage. - Test import in a clean virtual environment.
