code: import cv2 import numpy as np import pandas as pd from filterpy.kalman import…
- User
code: import cv2 import numpy as np import pandas as pd from filterpy.kalman import UnscentedKalmanFilter, MerweScaledSigmaPoints from ultralytics import YOLO
model = YOLO('/Users/surabhi/Documents/kalman/best.pt') def fx(x, dt):
This function predicts the state of the system at time t+1
based on the state at time t and the time step dt.
The state vector x has 10 elements: [pos_x, pos_y, vel_x, vel_y, acc_x, acc_y, jerk_x, jerk_y, snap_x, snap_y]
F = np.array([[1, 0, dt, 0, 0.5*dt**2, 0, (1/6)*dt**3, 0, (1/24)*dt**4, 0], [0, 1, 0, dt, 0, 0.5*dt**2, 0, (1/6)*dt**3, 0, (1/24)*dt**4], [0, 0, 1, 0, dt, 0, 0.5*dt**2, 0, (1/6)*dt**3, 0], [0, 0, 0, 1, 0, dt, 0, 0.5*dt**3, 0, (1/6)*dt**4], [0, 0, 0, 0, 1, 0, dt, 0, 0.5*dt**2, 0], [0, 0, 0, 0, 0, 1, 0, dt, 0, 0.5*dt**3], [0, 0, 0, 0, 0, 0, 1, 0, dt, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, dt], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]) B = np.array([[0.5*dt**2, 0, (1/6)*dt**3, 0], [0, 0.5*dt**2, 0, (1/6)*dt**3], [dt, 0, 0.5*dt**2, 0], [0, dt, 0, 0.5*dt**2], [0, 0, dt, 0], [0, 0, 0, dt], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) return np.dot(F, x)+ np.dot(B, u)def compute_process_sigmas(self, dt, fx, **fx_args): # implementation for i, s in enumerate(sigmas): self.sigmas_f[i] = fx(s, dt, u) dt = 1.0 kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1)) kf.x = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # initial state estimate kf.P = np.eye(10) * 1000 # initial error covariance matrix kf.R = np.diag([0.1, 0.1]) # measurement noise covariance matrix
kf.Q = lambda dt, v: np.diag([dt4/4, dt4/4, dt2/2, dt2/2, dt, dt, 0.1dt**4/4, 0.1dt4/4, 0.1*dt2/2, 0.1*dt**2/2]) kf.sigma_points = MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1)
u = np.zeros((4, 1))
cap = cv2.VideoCapture("1_1.mp4") frame_num = 0 predicted_points = [] bounce_detected = False last_bounce_frame = -10 test_df = pd.DataFrame(columns=['frame', 'x', 'y', 'vx', 'vy', 'ax', 'ay', 'V'])
while True: ret, frame = cap.read() if ret is False: break bbox = model(frame, show=True) frame_num += 1 for boxes_1 in bbox: result = boxes_1.boxes.xyxy if len(result) == 0: print("not detected") else: cx = int((result[0][0] + result[0][2]) / 2) cy = int((result[0][1] + result[0][3]) / 2) centroid = np.array([cx, cy]) kf.predict(dt=dt, control_input=u) kf.update(centroid) next_point = (kf.x).tolist() predicted_points.append((int(next_point[0]), int(next_point[1]))) if len(predicted_points) > 10: predicted_points.pop(0) print("next_point", next_point) print("frame_number", frame_num) if next_point[2] > 0: vx = "positive" else: vx = "negative" if next_point[3] > 0: vy = "positive" else: vy = "negative" test_df = test_df.append({ 'frame': frame_num, 'x': next_point[0], 'y': next_point[1], 'vx': next_point[2], 'vy': next_point[3], 'ax': next_point[4], 'ay': next_point[5], 'V': np.sqrt(kf.x[2]**2 + kf.x[3]**2) }, ignore_index=True) cv2.putText(frame, f'Frame: {frame_num}', (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) cv2.circle(frame, (cx, cy), 5, (0,0,255), 5) cv2.circle(frame, (int(next_point[0]), int(next_point[1])), 5, (255, 0, 0), 10) for i, p in enumerate(predicted_points): color = (255,255,255) cv2.circle(frame, p, 5, color, 2) print(kf.x[2]) if not bounce_detected and frame_num - last_bounce_frame > 50: if abs(next_point[2]) < 1 and test_df.shape[0] > 1 and test_df.shape[1] > 3 and np.sign(test_df.iloc[-2, 3]) == np.sign(kf.x[2]) and np.sqrt(kf.x[2]**2 + kf.x[3]**2) < 5: bounce_detected = True last_bounce_frame = frame_num print("Bounce detected")
- Assistant
The error message indicates that the function
fx()expects 2 arguments, but 3 were provided when calling it in the linekf.predict(dt=dt, control_input=u).To fix the error, either remove the
control_inputargument from thekf.predict()method if it is not needed, or modify thefx()function to accept 3 arguments if thecontrol_inputis necessary. - User
change in code
- Assistant
If you need to use the
control_inputin thefx()function, you can modify the function signature as follows:def fx(x, dt, u):Then, you can pass the
control_inputargument to thekf.predict()method like this:kf.predict(dt=dt, u=u)This will ensure that the
control_inputargument is passed to thefx()function correctly. - User
Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/kalman_t.py", line 69, in kf.predict(dt=dt, u=u) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/filterpy/kalman/UKF.py", line 388, in predict self.compute_process_sigmas(dt, fx, **fx_args) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/filterpy/kalman/UKF.py", line 503, in compute_process_sigmas self.sigmas_f[i] = fx(s, dt, **fx_args) ^^^^^^^^^^^^^^^^^^^^ TypeError: fx() got an unexpected keyword argument 'u'
- Assistant
It seems like the
compute_process_sigmas()method is using keyword arguments to pass thefx()function and its arguments, which might be causing the issue.To fix this error, you can modify the
compute_process_sigmas()method to pass theuargument to thefx()function directly, like this:def compute_process_sigmas(self, dt, fx, u=0.): # implementation for i, s in enumerate(self.sigmas_f): self.sigmas_f[i] = fx(s, dt, u)This will ensure that the
uargument is passed correctly to thefx()function, and should resolve the error. - User
Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/kalman_t.py", line 69, in kf.predict(dt=dt, u=u) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/filterpy/kalman/UKF.py", line 388, in predict self.compute_process_sigmas(dt, fx, **fx_args) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/filterpy/kalman/UKF.py", line 503, in compute_process_sigmas self.sigmas_f[i] = fx(s, dt, **fx_args) ^^^^^^^^^^^^^^^^^^^^ TypeError: fx() got an unexpected keyword argument 'u'
- Assistant
The error message indicates that the
fx()function is still receiving an unexpected keyword argumentu, which means that the change made to thecompute_process_sigmas()method did not solve the issue.To fix this error, try updating the
UnscentedKalmanFilterinitialization to include theuargument as well, like this:kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1), x_mean_fn=None, z_mean_fn=None, residual_x=None, residual_z=None, use_log=False, subtract=residual_x, sqrt_fn=None, inv_sqrt_fn=None, reorder_by_residual=True, u=u)This should ensure that the
uargument is passed correctly to thefx()function in thepredict()method. - User
Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/kalman_t.py", line 38, in kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1),x_mean_fn=None, z_mean_fn=None, residual_x=None, residual_z=None, use_log=False,subtract=residual_x, sqrt_fn=None, inv_sqrt_fn=None, reorder_by_residual=True, u=u) ^^^^^^^^^^ NameError: name 'residual_x' is not defined
- Assistant
It appears that there is an undefined variable
residual_xin the initialization of theUnscentedKalmanFilter, which is causing theNameError.To fix this error, you can remove the
subtractargument and theresidual_xargument from theUnscentedKalmanFilterinitialization since they were not defined, like this:kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1), x_mean_fn=None, z_mean_fn=None, residual_z=None, use_log=False, sqrt_fn=None, inv_sqrt_fn=None, reorder_by_residual=True, u=u)This should fix the
NameErrorissue and ensure that theuargument is passed correctly to thefx()function in thepredict()method. - User
surabhi@surabhis-MacBook-Air kalman % /usr/local/bin/python3 /Users/surabhi/Documents/kalman/kalman_t.py Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/kalman_t.py", line 38, in kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1),x_mean_fn=None, z_mean_fn=None, residual_z=None, use_log=False, sqrt_fn=None, inv_sqrt_fn=None, reorder_by_residual=True, u=u) ^ NameError: name 'u' is not defined
- Assistant
The error message suggests that the
uvariable is not defined or not in the scope of the code.To fix this error, make sure that the
uvariable is defined and assigned a value before it is used to initialize theUnscentedKalmanFilter. You can defineuas a zero matrix like this:u = np.zeros((4,1))Make sure that this line is placed before the
UnscentedKalmanFilterinitialization, and that theuvariable is passed as an argument to theUnscentedKalmanFilterconstructor. - User
surabhi@surabhis-MacBook-Air kalman % /usr/local/bin/python3 /Users/surabhi/Documents/kalman/kalman_t.py Traceback (most recent call last): File "/Users/surabhi/Documents/kalman/kalman_t.py", line 39, in kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1),x_mean_fn=None, z_mean_fn=None, residual_z=None, use_log=False, sqrt_fn=None, inv_sqrt_fn=None, reorder_by_residual=True, u=u) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: UnscentedKalmanFilter.init() got an unexpected keyword argument 'use_log'
- Assistant
The error message indicates that the
UnscentedKalmanFilterinitialization has an unexpected keyword argumentuse_log.To fix this error, you can remove the
use_logargument since it is not a valid argument for theUnscentedKalmanFilterconstructor in thefilterpylibrary.kf = UnscentedKalmanFilter(dim_x=10, dim_z=2, dt=dt, hx=None, fx=fx, points=MerweScaledSigmaPoints(n=10, alpha=0.1, beta=2., kappa=-1), x_mean_fn=None, z_mean_fn=None, residual_z=None, sqrt_fn=None, inv_sqrt_fn=None, reorder_by_residual=True, u=u)After making this change, the
UnscentedKalmanFilterinitialization should work without any issues.