OpenCV Kalman Filter with Python

Implement a Kalman Filter in python using OpenCV for applications like object tracking, motion prediction or sensor fusion across various platforms.

The Kalman Filter is an efficient recursive algorithm used to estimate the state of a system from noisy measurements. In computer vision, it’s commonly used for predicting object positions in tracking systems.

OpenCV provides a built-in KalmanFilter class through cv2.KalmanFilter which simplifies implementation.

Step-by-Step Example: Basic Kalman Filter in Python

Basic example to set up and run a basic Kalman Filter using OpenCV for simple position and velocity tracking in Python.

python
import cv2import numpy as np   # Initialize Kalman Filter with 4 dynamic params (x, y, dx, dy) and 2 measured (x, y) kf = cv2.KalmanFilter(4, 2)   # Define state transition matrix (A) kf.transitionMatrix = np.array([[1, 0, 1, 0],                                 [0, 1, 0, 1],                                 [0, 0, 1, 0],                                 [0, 0, 0, 1]], dtype=np.float32)   # Measurement matrix (H) kf.measurementMatrix = np.array([[1, 0, 0, 0],                                  [0, 1, 0, 0]], dtype=np.float32)   # Process noise covariance (Q) kf.processNoiseCov = np.eye(4, dtype=np.float32) * 0.03   # Initial state estimate kf.statePre = np.array([[0], [0], [0], [0]], dtype=np.float32)   # Predict and correct measured = np.array([[100], [50]], dtype=np.float32) # Example measurement   predicted = kf.predict() print("Predicted:", predicted)   corrected = kf.correct(measured) print("Corrected:", corrected)
Also Read: Boost Efficiency with Leading Python Web Frameworks in 2025

Short Explanation

This example initializes a basic Kalman Filter to track a 2D point with position and velocity. You can expand it for object tracking in video frames by feeding coordinates from detection algorithms.

Tip

To apply this in real-time tracking:
  • Integrate with OpenCV’s object detection.
  • Continuously feed coordinates from detections as measurements.
  • Use predict() to estimate position when detection is missing (occlusion handling).
Related

Printing exceptions in python helps to debug issues by giving clear information about what went wrong and where. You can access the exception message or…

15 Oct, 2025

Python string does not have a built-in .contains() method like some other languages (e.g., Java), but you can easily check if a substring exists using…

10 Oct, 2025

These are the typical reasons why the conda command fails and practical steps to fix them across Windows, macOS and Linux environments. Here are some…

07 Oct, 2025
Request a Quote Schedule a Meeting