Opencv cv2.KalmanFilter 鼠标跟踪

本文通过实例展示了如何使用Python的OpenCV库结合Kalman Filter进行鼠标位置实时跟踪,通过测量更新和预测步骤,提高跟踪精度。通过鼠标点击事件驱动,实时绘制轨迹线,适合初学者理解动态状态估计原理。
摘要由CSDN通过智能技术生成

cv2.KalmanFilter 实现鼠标跟踪

import cv2
import numpy as np


def mousemove(event, x, y, s, p):
    #
    global frame, current_measurement, measurements, last_measurement, current_prediction, last_prediction
    #
    last_measurement = current_measurement
    last_prediction = current_prediction
    current_x = np.float32(x)
    current_y = np.float32(y)
    #
    current_measurement = np.array([[current_x], [current_y]])
    print("current_measurement", current_measurement)
    kalman.correct(current_measurement)
    print("new_current_measurement", current_measurement)
    #
    current_prediction = kalman.predict()
    print("current_prediction", current_prediction)

    #
    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, (int(lmx), int(lmy)), (int(cmx), int(cmy)), (0, 100, 0))
    #
    cv2.line(frame, (int(lpx), int(lpy)), (int(cpx), int(cpy)), (0, 0, 200))


if __name__ == '__main__':

    frame = np.zeros((800, 800, 3), np.uint8)

    last_measurement = current_measurement = np.array((2, 1), np.float32)

    last_predicition = current_prediction = np.zeros((2, 1), np.float32)

    cv2.namedWindow("kalman_maustracker")

    cv2.setMouseCallback("kalman_maustracker", mousemove)

    kalman = cv2.KalmanFilter(4, 2)
#
    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_maustracker", frame)
        if (cv2.waitKey(30) & 0xff) == ord('q'):  # 按 q 键退出
            break

    cv2.destroyAllWindows()
    cv2.waitKey(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值