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).