Skip to content

OpenCV-Python

AI & Machine LearningML/AIPython

What it is

OpenCV-Python is a Python wrapper for the OpenCV C++ library, providing tools for computer vision, image processing, and video analysis. It allows rapid prototyping and deployment of vision applications in Python.

OpenCV-Python provides functions for image I/O, color space conversions, filtering, transformations, object detection, and machine learning integration. It supports reading and writing images and videos, as well as performing operations on arrays representing images.

Installation

pip install opencv-python

Getting started

The smallest useful thing you can do with it, and what each part means.

Read and display an image
import cv2
img = cv2.imread('image.jpg')
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Reads an image from file and displays it in a window until any key is pressed.
Convert image to grayscale
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Gray', gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
Converts a color image to grayscale using OpenCV’s color conversion function.

Advanced usage

Where the library earns its place over a simpler alternative.

Edge detection using Canny
import cv2
img = cv2.imread('image.jpg', 0)
edges = cv2.Canny(img, 100, 200)
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
Detects edges in a grayscale image using the Canny algorithm.
Video capture from webcam
import cv2
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    cv2.imshow('Webcam', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
Captures video from the default webcam and displays it in real-time.
Drawing shapes
import cv2
import numpy as np
img = np.zeros((512,512,3), np.uint8)
cv2.line(img, (0,0), (511,511), (255,0,0), 5)
cv2.rectangle(img, (100,100), (300,300), (0,255,0), 3)
cv2.circle(img, (256,256), 50, (0,0,255), -1)
cv2.imshow('Shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Draws lines, rectangles, and circles on an empty image using OpenCV drawing functions.
Face detection using Haar cascades
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('group.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow('Faces', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Detects faces in an image using pre-trained Haar cascade classifiers.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

cv2.error: OpenCV(…): error: (-215:Assertion failed)
Check that image paths are correct and files exist before reading.
AttributeError: module 'cv2' has no attribute '…'
Ensure that the correct OpenCV version is installed; some functions may require opencv-contrib-python.

Best practices

  • Use NumPy arrays for image processing to leverage vectorized operations.
  • Release video capture objects and destroy windows to avoid resource leaks.
  • Use proper color conversion codes when changing image color spaces.
  • Profile and optimize processing pipelines for real-time applications.
  • Keep pre-trained classifiers and models organized for reuse.

Background

Why it exists, and what it was reacting to.

OpenCV (Open Source Computer Vision Library) was initially developed by Intel in 1999. OpenCV-Python provides bindings to access the full power of OpenCV in Python, making it popular for real-time image and video processing, machine learning, and robotics applications.