OpenCV Python Bindings

4.13.0.92 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

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}")

view raw JSON →