python-3.x - cv2.KalmanFilter.predict 中的错误
问题描述
我正在尝试使用 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'
解决方案
您需要将正确的类型设置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
类似的方式设置,即使我的变体应该没问题。
推荐阅读
- java - 在另一个 Java 程序中执行程序
- jquery - jQuery slideToggle 不在实时站点上显示动画,而是在 jsfiddle 上
- matplotlib - 在 matplotlib 中创建条形图
- javascript - 一个人选中 3 个复选框后,如何使按钮解锁?
- javascript - Javascript 正则表达式:无法删除多行字符串中的前瞻组中的前导空格
- c# - 使用 c# 是否可以检测任务栏何时更改状态?
- c++ - c ++在移动<< 32次后打印出不正确的二进制文件
- objective-c - 实现不区分大小写的 NSMutableDictionary
- python - Python中的哈希性和不变性疑问
- c - 为什么 '\0' 没有被压入堆栈以指示字符串的结尾?