import cv2 import numpy as np # Define the true position of the object x = y = 0 dx = dy = 5 # Initialize the Kalman filter state = np.array([x, y, dx, dy], dtype=np.float32) observation = np.array([x, y], dtype=np.float32) H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], dtype=np.float32) dt = 1.0/30.0 F = np.array([[1, 0, dt, 0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=np.float32) measurement_noise = 10.0 process_noise = 0.1 kalman = cv2.KalmanFilter(4, 2) kalman.transitionMatrix = F kalman.measurementMatrix = H kalman.processNoiseCov = np.eye(4, dtype=np.float32)*process_noise kalman.measurementNoiseCov = np.eye(2, dtype=np.float32)*measurement_noise kalman.errorCovPost = np.eye(4, dtype=np.float32) kalman.statePost = state # Simulate the motion of the object for i in range(300): true_position = np.array([x, y], dtype=np.float32) observation = true_position + np.random.randn(2)*measurement_noise kalman.correct(observation) kalman.predict() state = kalman.statePost x, y, dx, dy = state cv2.circle(img, (int(x), int(y)), 5, (0, 255, 0), -1) cv2.imshow("Kalman Filter Example", img) cv2.waitKey(1) cv2.destroyAllWindows()
In this code, we first define the true position of the object and initialize the Kalman filter. We then simulate the motion of the object by adding some noise to the true position and updating the Kalman filter using the new observation.
We predict the next state of the system using the current state and the process model. We then update the position of the object on the image using the estimated position from the Kalman filter.
Conclusion
In conclusion, the Kalman filter algorithm is a powerful tool for estimating the state of a system based on noisy observations. It is widely used in various fields such as engineering, physics, and computer science.