[英]opencv kalman filter mouse tracker type error
我正在通過本書學習 opencv 和 python 並使用卡爾曼濾波器進行鼠標跟蹤遇到了這個錯誤:
編碼:
import cv2
import numpy as np
# Create a black image
img = np.zeros((500,500,3), np.uint8)
# Initialize the Kalman filter
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
last_measurement = None
last_prediction = None
def on_mouse_moved(event, x, y, flags, param):
global img, kalman, last_measurement, last_prediction
measurement = np.array([[x], [y]], np.float32)
if last_measurement is None:
# This is the first measurement.
# Update the Kalman filter's state to match the measurement.
kalman.statePre = np.array(
[[x],[y], [0],[0]], np.float32)
kalman.statePost = np.array(
[[x],[y],[0],[0]], np.float32)
prediction = measurement
else:
kalman.correct(measurement)
prediction = kalman.predict() # Gets a reference, not a copy
# Trace the path of the measurement in green.
# print(f"The lm:{last_measurement[0]}, and dtype: {last_measurement[0].dtype}")
# print(f"The cm:{measurement[0]}, and dtype: {measurement[0].dtype}")
cv2.line(img, (last_measurement[0], last_measurement[1]),
(measurement[0], measurement[1]), (0,255,0))
# Trace the path of the prediction in red.
cv2.line(img, (last_prediction[0], last_prediction[1]),
(prediction[0], prediction[1]), (0,0,255))
last_prediction = prediction.copy()
last_measurement = measurement
cv2.namedWindow('kalman_tracker')
cv2.setMouseCallback('kalman_tracker', on_mouse_moved)
while True:
cv2.imshow('kalman_tracker', img)
k = cv2.waitKey(1)
if k == 27: # Escape
cv2.imwrite('kalman.png', img)
break
cv2.destroyAllWindows()
錯誤:
43 cv2.line(img, (last_measurement[0], last_measurement[1]),
---> 44 (measurement[0], measurement[1]), (0,255,0))
45
46 # Trace the path of the prediction in red.
error: OpenCV(4.5.1-dev) :-1: error: (-5:Bad argument) in function 'line'
> Overload resolution failed:
> - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
> - Can't parse 'pt1'. Sequence item with index 0 has a wrong type
我試圖查看問題是否確實出在 x 和 y 位置的數據類型中(您可以在 comments 中看到 print 語句),但似乎類型是相同的。 那我不知道有什么問題。 甚至作者的代碼文件也給出了同樣的錯誤。 如果您有任何想法,將不勝感激您的回復!
@DanMašek 哇:! 你說的對! 我將代碼更改為:
cv2.line(img, (last_measurement[0][0].astype(np.int), last_measurement[1][0].astype(np.int)),
(measurement[0][0].astype(np.int), measurement[1][0].astype(np.int)), (0,255,0))
# Trace the path of the prediction in red.
cv2.line(img, (last_prediction[0][0].astype(np.int), last_prediction[1][0].astype(np.int)),
(prediction[0][0].astype(np.int), prediction[1][0].astype(np.int)), (0,0,255))
它奏效了。 很驚訝這本書沒有提到任何關於它的內容,然后書中的代碼是錯誤的。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.