Registry / ai-ml / opencv-python

opencv-python

JSON →
library4.13.0.92pypypi✓ verified 52d ago

OpenCV (Open Source Computer Vision Library) is a highly optimized open-source library for computer vision and machine learning tasks. The `opencv-python` package provides official Python bindings, enabling developers to access its extensive functionalities for image and video processing, object detection, and more within Python applications. It is actively maintained with frequent minor releases, often on a monthly cadence, to incorporate new features, bug fixes, and support for the latest Python and NumPy versions.

ai-mldata
pip install opencv-python
Install & Compatibility
Where this runs
tested against v4.13.0.92 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
glibc
py 3.10
✕ build_error
4/5 runs
py 3.11
✕ build_error
4/5 runs
py 3.12
✕ build_error
4/5 runs
py 3.13
✕ build_error
4/5 runs
py 3.9
✕ build_error
4/5 runs
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

cv2
import cv2
import opencv
The Python binding module is named `cv2` for historical reasons, not `opencv` or `cv`.

This quickstart demonstrates how to load, display, and then close an image using `opencv-python`. It includes error handling for failed image loading and ensures proper window closure. A dummy image is created if 'test_image.jpg' does not exist.

import cv2 import os # Create a dummy image file for demonstration # In a real scenario, replace 'test_image.jpg' with your image path. img_placeholder_path = 'test_image.jpg' if not os.path.exists(img_placeholder_path): try: import numpy as np dummy_img = np.zeros((300, 500, 3), dtype=np.uint8) cv2.putText(dummy_img, "Hello OpenCV", (50, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2) cv2.imwrite(img_placeholder_path, dummy_img) print(f"Created dummy image: {img_placeholder_path}") except ImportError: print("NumPy not found. Cannot create dummy image. Please ensure 'test_image.jpg' exists.") # Load an image from file img = cv2.imread(img_placeholder_path, cv2.IMREAD_COLOR) # Check if image loading was successful if img is None: print(f"Error: Could not load image from {img_placeholder_path}. Please ensure the file exists and is accessible.") else: # Display the image in a window cv2.imshow('My Image', img) # Wait indefinitely until a key is pressed cv2.waitKey(0) # Close all OpenCV windows cv2.destroyAllWindows() # Optionally, save the processed image # cv2.imwrite('output_image.jpg', img) # Clean up dummy image if created if os.path.exists(img_placeholder_path) and 'dummy_img' in locals(): os.remove(img_placeholder_path) print(f"Cleaned up dummy image: {img_placeholder_path}")
Debug
Known issues
breakingOpenCV-Python versions compiled with NumPy 1.x are not binary compatible with NumPy 2.x, leading to `ImportError` or runtime crashes.
fix
Upgrade `opencv-python` to version 4.10.0.84 or later (or the latest available version that explicitly supports NumPy 2.x for your Python version). Alternatively, downgrade NumPy to a version less than 2.0 (`pip install "numpy<2.0"`) if upgrading OpenCV is not an option.
affects: <4.10.0.84, <4.12.0.88 for some Python versions
gotchaUsing `opencv-python` (which includes GUI dependencies like Qt/X11) in headless environments (e.g., Docker containers, remote servers without a display) can cause runtime errors such as 'Cannot connect to X server'.
fix
For headless environments, use `pip install opencv-python-headless` instead. This package provides core OpenCV functionality without the GUI components.
affects: All versions of `opencv-python`
gotchaFunctions like `cv2.imread()` or `cv2.VideoCapture().read()` return `None` if the file path is incorrect/inaccessible or if a frame cannot be read, respectively. Subsequent operations on this `None` object will raise `AttributeError: 'NoneType' object has no attribute 'something'` or `cv2.error: (-215:Assertion failed) !_src.empty()`.
fix
Always check if the returned object (e.g., `img` from `cv2.imread()`, `success` from `cap.read()`) is valid (not `None` or `False`) before proceeding with image/frame processing.
affects: All versions
gotchaThere are several `opencv-python` package variants (`opencv-python`, `opencv-contrib-python`, `opencv-python-headless`, `opencv-contrib-python-headless`). Installing the wrong one can lead to missing features (e.g., SIFT, SURF algorithms are in `opencv-contrib-python` due to patent restrictions) or unnecessary GUI dependencies.
fix
Choose the correct package for your needs: `opencv-python` for core modules with GUI, `opencv-contrib-python` for core + extra modules with GUI, `opencv-python-headless` for core modules without GUI, and `opencv-contrib-python-headless` for core + extra modules without GUI. Do not install multiple variants in the same environment.
affects: All versions
gotchaOpenCV by default loads images in BGR (Blue-Green-Red) color order, while many other Python libraries (e.g., Matplotlib, Pillow) expect RGB (Red-Green-Blue). Directly displaying an OpenCV-loaded image with an RGB-expecting library will result in incorrect colors.
fix
Convert the image from BGR to RGB using `cv2.cvtColor(img, cv2.COLOR_BGR2RGB)` before displaying it with RGB-expecting libraries.
affects: All versions
breakingBuilding `opencv-python` from source, especially on `alpine` Linux, often fails due to missing C/C++ compilers and essential build tools (like `cmake`, `ninja`, or `make`). The `scikit-build` system used by `opencv-python` explicitly states it cannot install these dependencies on `alpine`.
fix
Ensure the necessary build tools and C/C++ compilers are installed on the system *before* attempting `pip install opencv-python`. For `alpine` Linux, this typically involves `apk add python3-dev build-base cmake ninja`. Alternatively, use a base image for which pre-built `opencv-python` wheels are available (e.g., Debian/Ubuntu), or consider using `opencv-python-headless` which might have fewer build dependencies.
affects: All versions (when building from source on Alpine)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'cv2'
This error occurs because the `opencv-python` package, which provides the `cv2` module, is either not installed in your current Python environment, or was installed using the incorrect package name `cv2` instead of `opencv-python`.
fix
Ensure you install the correct package in your active Python environment: `pip install opencv-python` or `pip install opencv-contrib-python` for extra modules.
ImportError: DLL load failed while importing cv2
(Windows-specific) This typically indicates that required Dynamic Link Libraries (DLLs) that OpenCV depends on are either missing, incompatible with your Python version, or cannot be found in your system's PATH. This can also be caused by conflicts with other installed libraries or an incomplete installation.
fix
Verify Python and `opencv-python` version compatibility, upgrade `pip` (`python -m pip install --upgrade pip`), consider installing `opencv-python-headless` if GUI components are not needed, or ensure the necessary Visual C++ Redistributables are installed and updated. Sometimes, a complete uninstall and reinstall of `opencv-python` resolves the issue.
AttributeError: module 'cv2' has no attribute 'imread'
This error usually means that the `opencv-python` installation is incomplete, corrupted, or shadowed by a local file named `cv2.py`. If the attribute is for a specialized module (e.g., `face`), it indicates that the `opencv-contrib-python` package (which includes additional modules) is not installed.
fix
First, check if you have a file named `cv2.py` in your project directory and rename it. If the error persists for basic functions, uninstall `opencv-python` and reinstall it. If it's for an advanced module, install `opencv-contrib-python`: `pip install opencv-contrib-python`.
pip install cv2
This is a common mistake where developers attempt to install the package using `cv2`, the module's import name, instead of the correct PyPI package name, `opencv-python`. This command will fail to install the library and subsequently lead to a `ModuleNotFoundError`.
fix
Use the correct package name for installation: `pip install opencv-python` or `pip install opencv-contrib-python` if you need extra modules.
Upgrade
Version history
4.13.0.92latest on PyPI
Audit
Dependencies
numpyrequiredEssential for image and array manipulations, as OpenCV images are represented as NumPy arrays.
Agent activity
13 hits · last 30 days
seranking-bot
4
node
2
Amazon
2
ahrefsbot
2
Meta
1
claudebot
1
Resources