cv2.KalmanFilter.predict中的错误

时间:2018-08-14 03:48:28

标签: python-3.x kalman-filter opencv3.3

我正在尝试使用opencv-python实现鼠标跟踪程序。我在cv2.Kalman中使用卡尔曼滤波器来预测鼠标的位置,但是函数cv2.KalmanFilter.predict()给我带来了错误。我的代码有什么问题,以及如何解决。谢谢。

这是我的代码:

import numpy as np
import cv2

class MouseInfo():
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __eq__(self, mouse_info):
        return (self.x == mouse_info.x) and (self.y == mouse_info.y)



def getMousePos(event, x, y, flag, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        mouse_info.x = x
        mouse_info.y = y

# def trackMouse():
#     measured = (mouse_info.x, mouse_info.y)
#     kf.update(mouse_info.x, mouse_info.y)
#     estimated = [int(c) for c in kf.getEstimate()]
#     return estimated

state_num = 4
measure_num = 2

kf = cv2.KalmanFilter(state_num, measure_num, 0)
state = np.zeros(state_num, np.float32)
process_noise = np.zeros(state_num, np.float32)
measurement = np.zeros(measure_num, np.float32)

cv2.randn(state, 0, 0.1)
kf.transitionMatrix = np.array([[1, 0, 1, 0],
                                [0, 1, 0, 1],
                                [0, 0, 1, 0],
                                [0, 0, 0, 1]])
cv2.setIdentity(kf.measurementMatrix)
cv2.setIdentity(kf.processNoiseCov, 1e-5)
cv2.setIdentity(kf.measurementNoiseCov, 1e-1)
cv2.setIdentity(kf.errorCovPost, 1)

cv2.randn(kf.statePost, 0, 0.1)

mouse_info = MouseInfo()
old_mouse_info = MouseInfo()
background = np.zeros([800, 600, 3])

cv2.namedWindow('Mouse Track', cv2.WINDOW_AUTOSIZE)
cv2.setMouseCallback('Mouse Track', getMousePos)

while cv2.waitKey(1)&0xff != 27:
    statePt = MouseInfo(kf.statePost[0], kf.statePost[1])
    prediction = kf.predict()
    predictPt = MouseInfo(prediction[0], prediction[1])
    measurement[0] = mouse_info.x
    measurement[1] = mouse_info.y
    kf.correct(measurement)
    cv2.circle(background, (mouse_info.x, mouse_info.y), 5, (0, 255, 0), 1)
    cv2.circle(background, (predictPt.x, predictPt.y), 5, (0, 0, 255), 1)
    cv2.imshow('Mouse Track', background)

我的OpenCV版本是3.4.2,错误信息是:

prediction = kf.predict()
    cv2.error: OpenCV(3.4.2) C:\projects\opencv- 
    python\opencv\modules\core\src\matmul.cpp:1558: error: (-215:Assertion 
    failed) type == B.type(), (type == (((5) & ((1 << 3) - 1)) + (((1)-1) << 
    3)) || type == (((6) & ((1 << 3) - 1)) + (((1)-1) << 3)) || type == 
    (((5) & ((1 << 3) - 1)) + (((2)-1) << 3)) || type == (((6) & ((1 << 3) - 
    1)) + (((2)-1) << 3))) in function 'cv::gemm'

1 个答案:

答案 0 :(得分:0)

您需要为np.float32设置正确的类型transitionMatrix才能消除错误

kf.transitionMatrix = np.array([[1, 0, 1, 0],
                                [0, 1, 0, 1],
                                [0, 0, 1, 0],
                                [0, 0, 0, 1]],np.float32)
kf.measurementMatrix = np.array([[1,0,0,0],
                                 [0,1,0,0]],np.float32)
#cv2.setIdentity(kf.measurementMatrix)

由于某种原因,即使您的变体应该可以,我也必须以类似的方式设置measurementMatrix

相关问题