OpenCV Python Bindings
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.
Warnings
- breaking OpenCV-Python versions compiled with NumPy 1.x are not binary compatible with NumPy 2.x, leading to `ImportError` or runtime crashes.
- gotcha Using `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'.
- gotcha Functions 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()`.
- gotcha There 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.
- gotcha OpenCV 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.
Install
-
pip install opencv-python
Imports
- cv2
import cv2
Quickstart
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}")