卡尔曼滤波器简介及代码案例

卡尔曼滤波器可用于,目标跟踪等方面。

卡尔曼滤波器与20世纪50年代提出,在许多领域得到了应用,特别是各种交通工具的导航系统上经常用到。卡尔曼滤波器会对含有噪声的输入数据流如视频输入进行递归操作,并差生底层系统状态在统计意义上的最优估计。卡尔曼滤波器利用这些规律来预测目标在当前视频帧中的位置,当前帧会基于上一帧的信息。

  可以将卡尔曼滤波器分为两个阶段:

     预测:卡尔曼滤波器使用有当前点计算的协方差来估计目标新位置

     更新:卡尔曼滤波器记录目标位置,并未下一次循环计算修正协方差。

鼠标移动案例:两条线,实际运动和预测轨迹

import cv2, numpy as np

measurements = []
predictions = []
frame = np.zeros((800, 800, 3), np.uint8)
last_measurement = current_measurement = np.array((2,1), np.float32) 
last_prediction = current_prediction = np.zeros((2,1), np.float32)

def mousemove(event, x, y, s, p):
    global frame, current_measurement, measurements, last_measurement, current_prediction, last_prediction
    last_prediction = current_prediction
    last_measurement = current_measurement
    current_measurement = np.array([[np.float32(x)],[np.float32(y)]])
    kalman.correct(current_measurement)
    current_prediction = kalman.predict()
    lmx, lmy = last_measurement[0], last_measurement[1]
    cmx, cmy = current_measurement[0], current_measurement[1]
    lpx, lpy = last_prediction[0], last_prediction[1]
    cpx, cpy = current_prediction[0], current_prediction[1]
    cv2.line(frame, (lmx, lmy), (cmx, cmy), (0,100,0))
    cv2.line(frame, (lpx, lpy), (cpx, cpy), (0,0,200))


cv2.namedWindow("kalman_tracker")
cv2.setMouseCallback("kalman_tracker", mousemove);

kalman = cv2.KalmanFilter(4,2,1)
kalman.measurementMatrix = np.array([[1,0,0,0],[0,1,0,0]],np.float32)
kalman.transitionMatrix = np.array([[1,0,1,0],[0,1,0,1],[0,0,1,0],[0,0,0,1]],np.float32)
kalman.processNoiseCov = np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]],np.float32) * 0.03

while True:
    cv2.imshow("kalman_tracker", frame)
    if (cv2.waitKey(30) & 0xFF) == 27:
        break
    if (cv2.waitKey(30) & 0xFF) == ord('q'):
        cv2.imwrite('kalman.jpg', frame)
        break

cv2.destroyAllWindows()

效果图:

卡尔曼滤波器简介及代码案例_第1张图片

你可能感兴趣的:(计算机视觉算法)