Upload folder using huggingface_hub (part 3)
Browse files- trackers/ocsort/kalmanfilter.py +1581 -0
- trackers/ocsort/ocsort.py +351 -0
- trackers/sort/__pycache__/sort.cpython-37.pyc +0 -0
- trackers/sort/__pycache__/sort.cpython-38.pyc +0 -0
- trackers/sort/sort.py +256 -0
- tracking_utils/__pycache__/evaluation.cpython-38.pyc +0 -0
- tracking_utils/__pycache__/io.cpython-38.pyc +0 -0
- tracking_utils/__pycache__/log.cpython-38.pyc +0 -0
- tracking_utils/evaluation.py +113 -0
- tracking_utils/io.py +119 -0
- tracking_utils/log.py +18 -0
trackers/ocsort/kalmanfilter.py
ADDED
|
@@ -0,0 +1,1581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# pylint: disable=invalid-name, too-many-arguments, too-many-branches,
|
| 3 |
+
# pylint: disable=too-many-locals, too-many-instance-attributes, too-many-lines
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
This module implements the linear Kalman filter in both an object
|
| 7 |
+
oriented and procedural form. The KalmanFilter class implements
|
| 8 |
+
the filter by storing the various matrices in instance variables,
|
| 9 |
+
minimizing the amount of bookkeeping you have to do.
|
| 10 |
+
All Kalman filters operate with a predict->update cycle. The
|
| 11 |
+
predict step, implemented with the method or function predict(),
|
| 12 |
+
uses the state transition matrix F to predict the state in the next
|
| 13 |
+
time period (epoch). The state is stored as a gaussian (x, P), where
|
| 14 |
+
x is the state (column) vector, and P is its covariance. Covariance
|
| 15 |
+
matrix Q specifies the process covariance. In Bayesian terms, this
|
| 16 |
+
prediction is called the *prior*, which you can think of colloquially
|
| 17 |
+
as the estimate prior to incorporating the measurement.
|
| 18 |
+
The update step, implemented with the method or function `update()`,
|
| 19 |
+
incorporates the measurement z with covariance R, into the state
|
| 20 |
+
estimate (x, P). The class stores the system uncertainty in S,
|
| 21 |
+
the innovation (residual between prediction and measurement in
|
| 22 |
+
measurement space) in y, and the Kalman gain in k. The procedural
|
| 23 |
+
form returns these variables to you. In Bayesian terms this computes
|
| 24 |
+
the *posterior* - the estimate after the information from the
|
| 25 |
+
measurement is incorporated.
|
| 26 |
+
Whether you use the OO form or procedural form is up to you. If
|
| 27 |
+
matrices such as H, R, and F are changing each epoch, you'll probably
|
| 28 |
+
opt to use the procedural form. If they are unchanging, the OO
|
| 29 |
+
form is perhaps easier to use since you won't need to keep track
|
| 30 |
+
of these matrices. This is especially useful if you are implementing
|
| 31 |
+
banks of filters or comparing various KF designs for performance;
|
| 32 |
+
a trivial coding bug could lead to using the wrong sets of matrices.
|
| 33 |
+
This module also offers an implementation of the RTS smoother, and
|
| 34 |
+
other helper functions, such as log likelihood computations.
|
| 35 |
+
The Saver class allows you to easily save the state of the
|
| 36 |
+
KalmanFilter class after every update
|
| 37 |
+
This module expects NumPy arrays for all values that expect
|
| 38 |
+
arrays, although in a few cases, particularly method parameters,
|
| 39 |
+
it will accept types that convert to NumPy arrays, such as lists
|
| 40 |
+
of lists. These exceptions are documented in the method or function.
|
| 41 |
+
Examples
|
| 42 |
+
--------
|
| 43 |
+
The following example constructs a constant velocity kinematic
|
| 44 |
+
filter, filters noisy data, and plots the results. It also demonstrates
|
| 45 |
+
using the Saver class to save the state of the filter at each epoch.
|
| 46 |
+
.. code-block:: Python
|
| 47 |
+
import matplotlib.pyplot as plt
|
| 48 |
+
import numpy as np
|
| 49 |
+
from filterpy.kalman import KalmanFilter
|
| 50 |
+
from filterpy.common import Q_discrete_white_noise, Saver
|
| 51 |
+
r_std, q_std = 2., 0.003
|
| 52 |
+
cv = KalmanFilter(dim_x=2, dim_z=1)
|
| 53 |
+
cv.x = np.array([[0., 1.]]) # position, velocity
|
| 54 |
+
cv.F = np.array([[1, dt],[ [0, 1]])
|
| 55 |
+
cv.R = np.array([[r_std^^2]])
|
| 56 |
+
f.H = np.array([[1., 0.]])
|
| 57 |
+
f.P = np.diag([.1^^2, .03^^2)
|
| 58 |
+
f.Q = Q_discrete_white_noise(2, dt, q_std**2)
|
| 59 |
+
saver = Saver(cv)
|
| 60 |
+
for z in range(100):
|
| 61 |
+
cv.predict()
|
| 62 |
+
cv.update([z + randn() * r_std])
|
| 63 |
+
saver.save() # save the filter's state
|
| 64 |
+
saver.to_array()
|
| 65 |
+
plt.plot(saver.x[:, 0])
|
| 66 |
+
# plot all of the priors
|
| 67 |
+
plt.plot(saver.x_prior[:, 0])
|
| 68 |
+
# plot mahalanobis distance
|
| 69 |
+
plt.figure()
|
| 70 |
+
plt.plot(saver.mahalanobis)
|
| 71 |
+
This code implements the same filter using the procedural form
|
| 72 |
+
x = np.array([[0., 1.]]) # position, velocity
|
| 73 |
+
F = np.array([[1, dt],[ [0, 1]])
|
| 74 |
+
R = np.array([[r_std^^2]])
|
| 75 |
+
H = np.array([[1., 0.]])
|
| 76 |
+
P = np.diag([.1^^2, .03^^2)
|
| 77 |
+
Q = Q_discrete_white_noise(2, dt, q_std**2)
|
| 78 |
+
for z in range(100):
|
| 79 |
+
x, P = predict(x, P, F=F, Q=Q)
|
| 80 |
+
x, P = update(x, P, z=[z + randn() * r_std], R=R, H=H)
|
| 81 |
+
xs.append(x[0, 0])
|
| 82 |
+
plt.plot(xs)
|
| 83 |
+
For more examples see the test subdirectory, or refer to the
|
| 84 |
+
book cited below. In it I both teach Kalman filtering from basic
|
| 85 |
+
principles, and teach the use of this library in great detail.
|
| 86 |
+
FilterPy library.
|
| 87 |
+
http://github.com/rlabbe/filterpy
|
| 88 |
+
Documentation at:
|
| 89 |
+
https://filterpy.readthedocs.org
|
| 90 |
+
Supporting book at:
|
| 91 |
+
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
|
| 92 |
+
This is licensed under an MIT license. See the readme.MD file
|
| 93 |
+
for more information.
|
| 94 |
+
Copyright 2014-2018 Roger R Labbe Jr.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
from __future__ import absolute_import, division
|
| 98 |
+
|
| 99 |
+
from copy import deepcopy
|
| 100 |
+
from math import log, exp, sqrt
|
| 101 |
+
import sys
|
| 102 |
+
import numpy as np
|
| 103 |
+
from numpy import dot, zeros, eye, isscalar, shape
|
| 104 |
+
import numpy.linalg as linalg
|
| 105 |
+
from filterpy.stats import logpdf
|
| 106 |
+
from filterpy.common import pretty_str, reshape_z
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class KalmanFilterNew(object):
|
| 110 |
+
""" Implements a Kalman filter. You are responsible for setting the
|
| 111 |
+
various state variables to reasonable values; the defaults will
|
| 112 |
+
not give you a functional filter.
|
| 113 |
+
For now the best documentation is my free book Kalman and Bayesian
|
| 114 |
+
Filters in Python [2]_. The test files in this directory also give you a
|
| 115 |
+
basic idea of use, albeit without much description.
|
| 116 |
+
In brief, you will first construct this object, specifying the size of
|
| 117 |
+
the state vector with dim_x and the size of the measurement vector that
|
| 118 |
+
you will be using with dim_z. These are mostly used to perform size checks
|
| 119 |
+
when you assign values to the various matrices. For example, if you
|
| 120 |
+
specified dim_z=2 and then try to assign a 3x3 matrix to R (the
|
| 121 |
+
measurement noise matrix you will get an assert exception because R
|
| 122 |
+
should be 2x2. (If for whatever reason you need to alter the size of
|
| 123 |
+
things midstream just use the underscore version of the matrices to
|
| 124 |
+
assign directly: your_filter._R = a_3x3_matrix.)
|
| 125 |
+
After construction the filter will have default matrices created for you,
|
| 126 |
+
but you must specify the values for each. It’s usually easiest to just
|
| 127 |
+
overwrite them rather than assign to each element yourself. This will be
|
| 128 |
+
clearer in the example below. All are of type numpy.array.
|
| 129 |
+
Examples
|
| 130 |
+
--------
|
| 131 |
+
Here is a filter that tracks position and velocity using a sensor that only
|
| 132 |
+
reads position.
|
| 133 |
+
First construct the object with the required dimensionality. Here the state
|
| 134 |
+
(`dim_x`) has 2 coefficients (position and velocity), and the measurement
|
| 135 |
+
(`dim_z`) has one. In FilterPy `x` is the state, `z` is the measurement.
|
| 136 |
+
.. code::
|
| 137 |
+
from filterpy.kalman import KalmanFilter
|
| 138 |
+
f = KalmanFilter (dim_x=2, dim_z=1)
|
| 139 |
+
Assign the initial value for the state (position and velocity). You can do this
|
| 140 |
+
with a two dimensional array like so:
|
| 141 |
+
.. code::
|
| 142 |
+
f.x = np.array([[2.], # position
|
| 143 |
+
[0.]]) # velocity
|
| 144 |
+
or just use a one dimensional array, which I prefer doing.
|
| 145 |
+
.. code::
|
| 146 |
+
f.x = np.array([2., 0.])
|
| 147 |
+
Define the state transition matrix:
|
| 148 |
+
.. code::
|
| 149 |
+
f.F = np.array([[1.,1.],
|
| 150 |
+
[0.,1.]])
|
| 151 |
+
Define the measurement function. Here we need to convert a position-velocity
|
| 152 |
+
vector into just a position vector, so we use:
|
| 153 |
+
.. code::
|
| 154 |
+
f.H = np.array([[1., 0.]])
|
| 155 |
+
Define the state's covariance matrix P.
|
| 156 |
+
.. code::
|
| 157 |
+
f.P = np.array([[1000., 0.],
|
| 158 |
+
[ 0., 1000.] ])
|
| 159 |
+
Now assign the measurement noise. Here the dimension is 1x1, so I can
|
| 160 |
+
use a scalar
|
| 161 |
+
.. code::
|
| 162 |
+
f.R = 5
|
| 163 |
+
I could have done this instead:
|
| 164 |
+
.. code::
|
| 165 |
+
f.R = np.array([[5.]])
|
| 166 |
+
Note that this must be a 2 dimensional array.
|
| 167 |
+
Finally, I will assign the process noise. Here I will take advantage of
|
| 168 |
+
another FilterPy library function:
|
| 169 |
+
.. code::
|
| 170 |
+
from filterpy.common import Q_discrete_white_noise
|
| 171 |
+
f.Q = Q_discrete_white_noise(dim=2, dt=0.1, var=0.13)
|
| 172 |
+
Now just perform the standard predict/update loop:
|
| 173 |
+
.. code::
|
| 174 |
+
while some_condition_is_true:
|
| 175 |
+
z = get_sensor_reading()
|
| 176 |
+
f.predict()
|
| 177 |
+
f.update(z)
|
| 178 |
+
do_something_with_estimate (f.x)
|
| 179 |
+
**Procedural Form**
|
| 180 |
+
This module also contains stand alone functions to perform Kalman filtering.
|
| 181 |
+
Use these if you are not a fan of objects.
|
| 182 |
+
**Example**
|
| 183 |
+
.. code::
|
| 184 |
+
while True:
|
| 185 |
+
z, R = read_sensor()
|
| 186 |
+
x, P = predict(x, P, F, Q)
|
| 187 |
+
x, P = update(x, P, z, R, H)
|
| 188 |
+
See my book Kalman and Bayesian Filters in Python [2]_.
|
| 189 |
+
You will have to set the following attributes after constructing this
|
| 190 |
+
object for the filter to perform properly. Please note that there are
|
| 191 |
+
various checks in place to ensure that you have made everything the
|
| 192 |
+
'correct' size. However, it is possible to provide incorrectly sized
|
| 193 |
+
arrays such that the linear algebra can not perform an operation.
|
| 194 |
+
It can also fail silently - you can end up with matrices of a size that
|
| 195 |
+
allows the linear algebra to work, but are the wrong shape for the problem
|
| 196 |
+
you are trying to solve.
|
| 197 |
+
Parameters
|
| 198 |
+
----------
|
| 199 |
+
dim_x : int
|
| 200 |
+
Number of state variables for the Kalman filter. For example, if
|
| 201 |
+
you are tracking the position and velocity of an object in two
|
| 202 |
+
dimensions, dim_x would be 4.
|
| 203 |
+
This is used to set the default size of P, Q, and u
|
| 204 |
+
dim_z : int
|
| 205 |
+
Number of of measurement inputs. For example, if the sensor
|
| 206 |
+
provides you with position in (x,y), dim_z would be 2.
|
| 207 |
+
dim_u : int (optional)
|
| 208 |
+
size of the control input, if it is being used.
|
| 209 |
+
Default value of 0 indicates it is not used.
|
| 210 |
+
compute_log_likelihood : bool (default = True)
|
| 211 |
+
Computes log likelihood by default, but this can be a slow
|
| 212 |
+
computation, so if you never use it you can turn this computation
|
| 213 |
+
off.
|
| 214 |
+
Attributes
|
| 215 |
+
----------
|
| 216 |
+
x : numpy.array(dim_x, 1)
|
| 217 |
+
Current state estimate. Any call to update() or predict() updates
|
| 218 |
+
this variable.
|
| 219 |
+
P : numpy.array(dim_x, dim_x)
|
| 220 |
+
Current state covariance matrix. Any call to update() or predict()
|
| 221 |
+
updates this variable.
|
| 222 |
+
x_prior : numpy.array(dim_x, 1)
|
| 223 |
+
Prior (predicted) state estimate. The *_prior and *_post attributes
|
| 224 |
+
are for convenience; they store the prior and posterior of the
|
| 225 |
+
current epoch. Read Only.
|
| 226 |
+
P_prior : numpy.array(dim_x, dim_x)
|
| 227 |
+
Prior (predicted) state covariance matrix. Read Only.
|
| 228 |
+
x_post : numpy.array(dim_x, 1)
|
| 229 |
+
Posterior (updated) state estimate. Read Only.
|
| 230 |
+
P_post : numpy.array(dim_x, dim_x)
|
| 231 |
+
Posterior (updated) state covariance matrix. Read Only.
|
| 232 |
+
z : numpy.array
|
| 233 |
+
Last measurement used in update(). Read only.
|
| 234 |
+
R : numpy.array(dim_z, dim_z)
|
| 235 |
+
Measurement noise covariance matrix. Also known as the
|
| 236 |
+
observation covariance.
|
| 237 |
+
Q : numpy.array(dim_x, dim_x)
|
| 238 |
+
Process noise covariance matrix. Also known as the transition
|
| 239 |
+
covariance.
|
| 240 |
+
F : numpy.array()
|
| 241 |
+
State Transition matrix. Also known as `A` in some formulation.
|
| 242 |
+
H : numpy.array(dim_z, dim_x)
|
| 243 |
+
Measurement function. Also known as the observation matrix, or as `C`.
|
| 244 |
+
y : numpy.array
|
| 245 |
+
Residual of the update step. Read only.
|
| 246 |
+
K : numpy.array(dim_x, dim_z)
|
| 247 |
+
Kalman gain of the update step. Read only.
|
| 248 |
+
S : numpy.array
|
| 249 |
+
System uncertainty (P projected to measurement space). Read only.
|
| 250 |
+
SI : numpy.array
|
| 251 |
+
Inverse system uncertainty. Read only.
|
| 252 |
+
log_likelihood : float
|
| 253 |
+
log-likelihood of the last measurement. Read only.
|
| 254 |
+
likelihood : float
|
| 255 |
+
likelihood of last measurement. Read only.
|
| 256 |
+
Computed from the log-likelihood. The log-likelihood can be very
|
| 257 |
+
small, meaning a large negative value such as -28000. Taking the
|
| 258 |
+
exp() of that results in 0.0, which can break typical algorithms
|
| 259 |
+
which multiply by this value, so by default we always return a
|
| 260 |
+
number >= sys.float_info.min.
|
| 261 |
+
mahalanobis : float
|
| 262 |
+
mahalanobis distance of the innovation. Read only.
|
| 263 |
+
inv : function, default numpy.linalg.inv
|
| 264 |
+
If you prefer another inverse function, such as the Moore-Penrose
|
| 265 |
+
pseudo inverse, set it to that instead: kf.inv = np.linalg.pinv
|
| 266 |
+
This is only used to invert self.S. If you know it is diagonal, you
|
| 267 |
+
might choose to set it to filterpy.common.inv_diagonal, which is
|
| 268 |
+
several times faster than numpy.linalg.inv for diagonal matrices.
|
| 269 |
+
alpha : float
|
| 270 |
+
Fading memory setting. 1.0 gives the normal Kalman filter, and
|
| 271 |
+
values slightly larger than 1.0 (such as 1.02) give a fading
|
| 272 |
+
memory effect - previous measurements have less influence on the
|
| 273 |
+
filter's estimates. This formulation of the Fading memory filter
|
| 274 |
+
(there are many) is due to Dan Simon [1]_.
|
| 275 |
+
References
|
| 276 |
+
----------
|
| 277 |
+
.. [1] Dan Simon. "Optimal State Estimation." John Wiley & Sons.
|
| 278 |
+
p. 208-212. (2006)
|
| 279 |
+
.. [2] Roger Labbe. "Kalman and Bayesian Filters in Python"
|
| 280 |
+
https://github.com/rlabbe/Kalman-and-Bayesian-Filters-in-Python
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
def __init__(self, dim_x, dim_z, dim_u=0):
|
| 284 |
+
if dim_x < 1:
|
| 285 |
+
raise ValueError('dim_x must be 1 or greater')
|
| 286 |
+
if dim_z < 1:
|
| 287 |
+
raise ValueError('dim_z must be 1 or greater')
|
| 288 |
+
if dim_u < 0:
|
| 289 |
+
raise ValueError('dim_u must be 0 or greater')
|
| 290 |
+
|
| 291 |
+
self.dim_x = dim_x
|
| 292 |
+
self.dim_z = dim_z
|
| 293 |
+
self.dim_u = dim_u
|
| 294 |
+
|
| 295 |
+
self.x = zeros((dim_x, 1)) # state
|
| 296 |
+
self.P = eye(dim_x) # uncertainty covariance
|
| 297 |
+
self.Q = eye(dim_x) # process uncertainty
|
| 298 |
+
self.B = None # control transition matrix
|
| 299 |
+
self.F = eye(dim_x) # state transition matrix
|
| 300 |
+
self.H = zeros((dim_z, dim_x)) # measurement function
|
| 301 |
+
self.R = eye(dim_z) # measurement uncertainty
|
| 302 |
+
self._alpha_sq = 1. # fading memory control
|
| 303 |
+
self.M = np.zeros((dim_x, dim_z)) # process-measurement cross correlation
|
| 304 |
+
self.z = np.array([[None]*self.dim_z]).T
|
| 305 |
+
|
| 306 |
+
# gain and residual are computed during the innovation step. We
|
| 307 |
+
# save them so that in case you want to inspect them for various
|
| 308 |
+
# purposes
|
| 309 |
+
self.K = np.zeros((dim_x, dim_z)) # kalman gain
|
| 310 |
+
self.y = zeros((dim_z, 1))
|
| 311 |
+
self.S = np.zeros((dim_z, dim_z)) # system uncertainty
|
| 312 |
+
self.SI = np.zeros((dim_z, dim_z)) # inverse system uncertainty
|
| 313 |
+
|
| 314 |
+
# identity matrix. Do not alter this.
|
| 315 |
+
self._I = np.eye(dim_x)
|
| 316 |
+
|
| 317 |
+
# these will always be a copy of x,P after predict() is called
|
| 318 |
+
self.x_prior = self.x.copy()
|
| 319 |
+
self.P_prior = self.P.copy()
|
| 320 |
+
|
| 321 |
+
# these will always be a copy of x,P after update() is called
|
| 322 |
+
self.x_post = self.x.copy()
|
| 323 |
+
self.P_post = self.P.copy()
|
| 324 |
+
|
| 325 |
+
# Only computed only if requested via property
|
| 326 |
+
self._log_likelihood = log(sys.float_info.min)
|
| 327 |
+
self._likelihood = sys.float_info.min
|
| 328 |
+
self._mahalanobis = None
|
| 329 |
+
|
| 330 |
+
# keep all observations
|
| 331 |
+
self.history_obs = []
|
| 332 |
+
|
| 333 |
+
self.inv = np.linalg.inv
|
| 334 |
+
|
| 335 |
+
self.attr_saved = None
|
| 336 |
+
self.observed = False
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def predict(self, u=None, B=None, F=None, Q=None):
|
| 340 |
+
"""
|
| 341 |
+
Predict next state (prior) using the Kalman filter state propagation
|
| 342 |
+
equations.
|
| 343 |
+
Parameters
|
| 344 |
+
----------
|
| 345 |
+
u : np.array, default 0
|
| 346 |
+
Optional control vector.
|
| 347 |
+
B : np.array(dim_x, dim_u), or None
|
| 348 |
+
Optional control transition matrix; a value of None
|
| 349 |
+
will cause the filter to use `self.B`.
|
| 350 |
+
F : np.array(dim_x, dim_x), or None
|
| 351 |
+
Optional state transition matrix; a value of None
|
| 352 |
+
will cause the filter to use `self.F`.
|
| 353 |
+
Q : np.array(dim_x, dim_x), scalar, or None
|
| 354 |
+
Optional process noise matrix; a value of None will cause the
|
| 355 |
+
filter to use `self.Q`.
|
| 356 |
+
"""
|
| 357 |
+
|
| 358 |
+
if B is None:
|
| 359 |
+
B = self.B
|
| 360 |
+
if F is None:
|
| 361 |
+
F = self.F
|
| 362 |
+
if Q is None:
|
| 363 |
+
Q = self.Q
|
| 364 |
+
elif isscalar(Q):
|
| 365 |
+
Q = eye(self.dim_x) * Q
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
# x = Fx + Bu
|
| 369 |
+
if B is not None and u is not None:
|
| 370 |
+
self.x = dot(F, self.x) + dot(B, u)
|
| 371 |
+
else:
|
| 372 |
+
self.x = dot(F, self.x)
|
| 373 |
+
|
| 374 |
+
# P = FPF' + Q
|
| 375 |
+
self.P = self._alpha_sq * dot(dot(F, self.P), F.T) + Q
|
| 376 |
+
|
| 377 |
+
# save prior
|
| 378 |
+
self.x_prior = self.x.copy()
|
| 379 |
+
self.P_prior = self.P.copy()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def freeze(self):
|
| 384 |
+
"""
|
| 385 |
+
Save the parameters before non-observation forward
|
| 386 |
+
"""
|
| 387 |
+
self.attr_saved = deepcopy(self.__dict__)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def unfreeze(self):
|
| 391 |
+
if self.attr_saved is not None:
|
| 392 |
+
new_history = deepcopy(self.history_obs)
|
| 393 |
+
self.__dict__ = self.attr_saved
|
| 394 |
+
# self.history_obs = new_history
|
| 395 |
+
self.history_obs = self.history_obs[:-1]
|
| 396 |
+
occur = [int(d is None) for d in new_history]
|
| 397 |
+
indices = np.where(np.array(occur)==0)[0]
|
| 398 |
+
index1 = indices[-2]
|
| 399 |
+
index2 = indices[-1]
|
| 400 |
+
box1 = new_history[index1]
|
| 401 |
+
x1, y1, s1, r1 = box1
|
| 402 |
+
w1 = np.sqrt(s1 * r1)
|
| 403 |
+
h1 = np.sqrt(s1 / r1)
|
| 404 |
+
box2 = new_history[index2]
|
| 405 |
+
x2, y2, s2, r2 = box2
|
| 406 |
+
w2 = np.sqrt(s2 * r2)
|
| 407 |
+
h2 = np.sqrt(s2 / r2)
|
| 408 |
+
time_gap = index2 - index1
|
| 409 |
+
dx = (x2-x1)/time_gap
|
| 410 |
+
dy = (y2-y1)/time_gap
|
| 411 |
+
dw = (w2-w1)/time_gap
|
| 412 |
+
dh = (h2-h1)/time_gap
|
| 413 |
+
for i in range(index2 - index1):
|
| 414 |
+
"""
|
| 415 |
+
The default virtual trajectory generation is by linear
|
| 416 |
+
motion (constant speed hypothesis), you could modify this
|
| 417 |
+
part to implement your own.
|
| 418 |
+
"""
|
| 419 |
+
x = x1 + (i+1) * dx
|
| 420 |
+
y = y1 + (i+1) * dy
|
| 421 |
+
w = w1 + (i+1) * dw
|
| 422 |
+
h = h1 + (i+1) * dh
|
| 423 |
+
s = w * h
|
| 424 |
+
r = w / float(h)
|
| 425 |
+
new_box = np.array([x, y, s, r]).reshape((4, 1))
|
| 426 |
+
"""
|
| 427 |
+
I still use predict-update loop here to refresh the parameters,
|
| 428 |
+
but this can be faster by directly modifying the internal parameters
|
| 429 |
+
as suggested in the paper. I keep this naive but slow way for
|
| 430 |
+
easy read and understanding
|
| 431 |
+
"""
|
| 432 |
+
self.update(new_box)
|
| 433 |
+
if not i == (index2-index1-1):
|
| 434 |
+
self.predict()
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def update(self, z, R=None, H=None):
|
| 438 |
+
"""
|
| 439 |
+
Add a new measurement (z) to the Kalman filter.
|
| 440 |
+
If z is None, nothing is computed. However, x_post and P_post are
|
| 441 |
+
updated with the prior (x_prior, P_prior), and self.z is set to None.
|
| 442 |
+
Parameters
|
| 443 |
+
----------
|
| 444 |
+
z : (dim_z, 1): array_like
|
| 445 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 446 |
+
otherwise it must be convertible to a column vector.
|
| 447 |
+
If you pass in a value of H, z must be a column vector the
|
| 448 |
+
of the correct size.
|
| 449 |
+
R : np.array, scalar, or None
|
| 450 |
+
Optionally provide R to override the measurement noise for this
|
| 451 |
+
one call, otherwise self.R will be used.
|
| 452 |
+
H : np.array, or None
|
| 453 |
+
Optionally provide H to override the measurement function for this
|
| 454 |
+
one call, otherwise self.H will be used.
|
| 455 |
+
"""
|
| 456 |
+
|
| 457 |
+
# set to None to force recompute
|
| 458 |
+
self._log_likelihood = None
|
| 459 |
+
self._likelihood = None
|
| 460 |
+
self._mahalanobis = None
|
| 461 |
+
|
| 462 |
+
# append the observation
|
| 463 |
+
self.history_obs.append(z)
|
| 464 |
+
|
| 465 |
+
if z is None:
|
| 466 |
+
if self.observed:
|
| 467 |
+
"""
|
| 468 |
+
Got no observation so freeze the current parameters for future
|
| 469 |
+
potential online smoothing.
|
| 470 |
+
"""
|
| 471 |
+
self.freeze()
|
| 472 |
+
self.observed = False
|
| 473 |
+
self.z = np.array([[None]*self.dim_z]).T
|
| 474 |
+
self.x_post = self.x.copy()
|
| 475 |
+
self.P_post = self.P.copy()
|
| 476 |
+
self.y = zeros((self.dim_z, 1))
|
| 477 |
+
return
|
| 478 |
+
|
| 479 |
+
# self.observed = True
|
| 480 |
+
if not self.observed:
|
| 481 |
+
"""
|
| 482 |
+
Get observation, use online smoothing to re-update parameters
|
| 483 |
+
"""
|
| 484 |
+
self.unfreeze()
|
| 485 |
+
self.observed = True
|
| 486 |
+
|
| 487 |
+
if R is None:
|
| 488 |
+
R = self.R
|
| 489 |
+
elif isscalar(R):
|
| 490 |
+
R = eye(self.dim_z) * R
|
| 491 |
+
|
| 492 |
+
if H is None:
|
| 493 |
+
z = reshape_z(z, self.dim_z, self.x.ndim)
|
| 494 |
+
H = self.H
|
| 495 |
+
|
| 496 |
+
# y = z - Hx
|
| 497 |
+
# error (residual) between measurement and prediction
|
| 498 |
+
self.y = z - dot(H, self.x)
|
| 499 |
+
|
| 500 |
+
# common subexpression for speed
|
| 501 |
+
PHT = dot(self.P, H.T)
|
| 502 |
+
|
| 503 |
+
# S = HPH' + R
|
| 504 |
+
# project system uncertainty into measurement space
|
| 505 |
+
self.S = dot(H, PHT) + R
|
| 506 |
+
self.SI = self.inv(self.S)
|
| 507 |
+
# K = PH'inv(S)
|
| 508 |
+
# map system uncertainty into kalman gain
|
| 509 |
+
self.K = dot(PHT, self.SI)
|
| 510 |
+
|
| 511 |
+
# x = x + Ky
|
| 512 |
+
# predict new x with residual scaled by the kalman gain
|
| 513 |
+
self.x = self.x + dot(self.K, self.y)
|
| 514 |
+
|
| 515 |
+
# P = (I-KH)P(I-KH)' + KRK'
|
| 516 |
+
# This is more numerically stable
|
| 517 |
+
# and works for non-optimal K vs the equation
|
| 518 |
+
# P = (I-KH)P usually seen in the literature.
|
| 519 |
+
|
| 520 |
+
I_KH = self._I - dot(self.K, H)
|
| 521 |
+
self.P = dot(dot(I_KH, self.P), I_KH.T) + dot(dot(self.K, R), self.K.T)
|
| 522 |
+
|
| 523 |
+
# save measurement and posterior state
|
| 524 |
+
self.z = deepcopy(z)
|
| 525 |
+
self.x_post = self.x.copy()
|
| 526 |
+
self.P_post = self.P.copy()
|
| 527 |
+
|
| 528 |
+
def predict_steadystate(self, u=0, B=None):
|
| 529 |
+
"""
|
| 530 |
+
Predict state (prior) using the Kalman filter state propagation
|
| 531 |
+
equations. Only x is updated, P is left unchanged. See
|
| 532 |
+
update_steadstate() for a longer explanation of when to use this
|
| 533 |
+
method.
|
| 534 |
+
Parameters
|
| 535 |
+
----------
|
| 536 |
+
u : np.array
|
| 537 |
+
Optional control vector. If non-zero, it is multiplied by B
|
| 538 |
+
to create the control input into the system.
|
| 539 |
+
B : np.array(dim_x, dim_u), or None
|
| 540 |
+
Optional control transition matrix; a value of None
|
| 541 |
+
will cause the filter to use `self.B`.
|
| 542 |
+
"""
|
| 543 |
+
|
| 544 |
+
if B is None:
|
| 545 |
+
B = self.B
|
| 546 |
+
|
| 547 |
+
# x = Fx + Bu
|
| 548 |
+
if B is not None:
|
| 549 |
+
self.x = dot(self.F, self.x) + dot(B, u)
|
| 550 |
+
else:
|
| 551 |
+
self.x = dot(self.F, self.x)
|
| 552 |
+
|
| 553 |
+
# save prior
|
| 554 |
+
self.x_prior = self.x.copy()
|
| 555 |
+
self.P_prior = self.P.copy()
|
| 556 |
+
|
| 557 |
+
def update_steadystate(self, z):
|
| 558 |
+
"""
|
| 559 |
+
Add a new measurement (z) to the Kalman filter without recomputing
|
| 560 |
+
the Kalman gain K, the state covariance P, or the system
|
| 561 |
+
uncertainty S.
|
| 562 |
+
You can use this for LTI systems since the Kalman gain and covariance
|
| 563 |
+
converge to a fixed value. Precompute these and assign them explicitly,
|
| 564 |
+
or run the Kalman filter using the normal predict()/update(0 cycle
|
| 565 |
+
until they converge.
|
| 566 |
+
The main advantage of this call is speed. We do significantly less
|
| 567 |
+
computation, notably avoiding a costly matrix inversion.
|
| 568 |
+
Use in conjunction with predict_steadystate(), otherwise P will grow
|
| 569 |
+
without bound.
|
| 570 |
+
Parameters
|
| 571 |
+
----------
|
| 572 |
+
z : (dim_z, 1): array_like
|
| 573 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 574 |
+
otherwise it must be convertible to a column vector.
|
| 575 |
+
Examples
|
| 576 |
+
--------
|
| 577 |
+
>>> cv = kinematic_kf(dim=3, order=2) # 3D const velocity filter
|
| 578 |
+
>>> # let filter converge on representative data, then save k and P
|
| 579 |
+
>>> for i in range(100):
|
| 580 |
+
>>> cv.predict()
|
| 581 |
+
>>> cv.update([i, i, i])
|
| 582 |
+
>>> saved_k = np.copy(cv.K)
|
| 583 |
+
>>> saved_P = np.copy(cv.P)
|
| 584 |
+
later on:
|
| 585 |
+
>>> cv = kinematic_kf(dim=3, order=2) # 3D const velocity filter
|
| 586 |
+
>>> cv.K = np.copy(saved_K)
|
| 587 |
+
>>> cv.P = np.copy(saved_P)
|
| 588 |
+
>>> for i in range(100):
|
| 589 |
+
>>> cv.predict_steadystate()
|
| 590 |
+
>>> cv.update_steadystate([i, i, i])
|
| 591 |
+
"""
|
| 592 |
+
|
| 593 |
+
# set to None to force recompute
|
| 594 |
+
self._log_likelihood = None
|
| 595 |
+
self._likelihood = None
|
| 596 |
+
self._mahalanobis = None
|
| 597 |
+
|
| 598 |
+
if z is None:
|
| 599 |
+
self.z = np.array([[None]*self.dim_z]).T
|
| 600 |
+
self.x_post = self.x.copy()
|
| 601 |
+
self.P_post = self.P.copy()
|
| 602 |
+
self.y = zeros((self.dim_z, 1))
|
| 603 |
+
return
|
| 604 |
+
|
| 605 |
+
z = reshape_z(z, self.dim_z, self.x.ndim)
|
| 606 |
+
|
| 607 |
+
# y = z - Hx
|
| 608 |
+
# error (residual) between measurement and prediction
|
| 609 |
+
self.y = z - dot(self.H, self.x)
|
| 610 |
+
|
| 611 |
+
# x = x + Ky
|
| 612 |
+
# predict new x with residual scaled by the kalman gain
|
| 613 |
+
self.x = self.x + dot(self.K, self.y)
|
| 614 |
+
|
| 615 |
+
self.z = deepcopy(z)
|
| 616 |
+
self.x_post = self.x.copy()
|
| 617 |
+
self.P_post = self.P.copy()
|
| 618 |
+
|
| 619 |
+
# set to None to force recompute
|
| 620 |
+
self._log_likelihood = None
|
| 621 |
+
self._likelihood = None
|
| 622 |
+
self._mahalanobis = None
|
| 623 |
+
|
| 624 |
+
def update_correlated(self, z, R=None, H=None):
|
| 625 |
+
""" Add a new measurement (z) to the Kalman filter assuming that
|
| 626 |
+
process noise and measurement noise are correlated as defined in
|
| 627 |
+
the `self.M` matrix.
|
| 628 |
+
A partial derivation can be found in [1]
|
| 629 |
+
If z is None, nothing is changed.
|
| 630 |
+
Parameters
|
| 631 |
+
----------
|
| 632 |
+
z : (dim_z, 1): array_like
|
| 633 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 634 |
+
otherwise it must be convertible to a column vector.
|
| 635 |
+
R : np.array, scalar, or None
|
| 636 |
+
Optionally provide R to override the measurement noise for this
|
| 637 |
+
one call, otherwise self.R will be used.
|
| 638 |
+
H : np.array, or None
|
| 639 |
+
Optionally provide H to override the measurement function for this
|
| 640 |
+
one call, otherwise self.H will be used.
|
| 641 |
+
References
|
| 642 |
+
----------
|
| 643 |
+
.. [1] Bulut, Y. (2011). Applied Kalman filter theory (Doctoral dissertation, Northeastern University).
|
| 644 |
+
http://people.duke.edu/~hpgavin/SystemID/References/Balut-KalmanFilter-PhD-NEU-2011.pdf
|
| 645 |
+
"""
|
| 646 |
+
|
| 647 |
+
# set to None to force recompute
|
| 648 |
+
self._log_likelihood = None
|
| 649 |
+
self._likelihood = None
|
| 650 |
+
self._mahalanobis = None
|
| 651 |
+
|
| 652 |
+
if z is None:
|
| 653 |
+
self.z = np.array([[None]*self.dim_z]).T
|
| 654 |
+
self.x_post = self.x.copy()
|
| 655 |
+
self.P_post = self.P.copy()
|
| 656 |
+
self.y = zeros((self.dim_z, 1))
|
| 657 |
+
return
|
| 658 |
+
|
| 659 |
+
if R is None:
|
| 660 |
+
R = self.R
|
| 661 |
+
elif isscalar(R):
|
| 662 |
+
R = eye(self.dim_z) * R
|
| 663 |
+
|
| 664 |
+
# rename for readability and a tiny extra bit of speed
|
| 665 |
+
if H is None:
|
| 666 |
+
z = reshape_z(z, self.dim_z, self.x.ndim)
|
| 667 |
+
H = self.H
|
| 668 |
+
|
| 669 |
+
# handle special case: if z is in form [[z]] but x is not a column
|
| 670 |
+
# vector dimensions will not match
|
| 671 |
+
if self.x.ndim == 1 and shape(z) == (1, 1):
|
| 672 |
+
z = z[0]
|
| 673 |
+
|
| 674 |
+
if shape(z) == (): # is it scalar, e.g. z=3 or z=np.array(3)
|
| 675 |
+
z = np.asarray([z])
|
| 676 |
+
|
| 677 |
+
# y = z - Hx
|
| 678 |
+
# error (residual) between measurement and prediction
|
| 679 |
+
self.y = z - dot(H, self.x)
|
| 680 |
+
|
| 681 |
+
# common subexpression for speed
|
| 682 |
+
PHT = dot(self.P, H.T)
|
| 683 |
+
|
| 684 |
+
# project system uncertainty into measurement space
|
| 685 |
+
self.S = dot(H, PHT) + dot(H, self.M) + dot(self.M.T, H.T) + R
|
| 686 |
+
self.SI = self.inv(self.S)
|
| 687 |
+
|
| 688 |
+
# K = PH'inv(S)
|
| 689 |
+
# map system uncertainty into kalman gain
|
| 690 |
+
self.K = dot(PHT + self.M, self.SI)
|
| 691 |
+
|
| 692 |
+
# x = x + Ky
|
| 693 |
+
# predict new x with residual scaled by the kalman gain
|
| 694 |
+
self.x = self.x + dot(self.K, self.y)
|
| 695 |
+
self.P = self.P - dot(self.K, dot(H, self.P) + self.M.T)
|
| 696 |
+
|
| 697 |
+
self.z = deepcopy(z)
|
| 698 |
+
self.x_post = self.x.copy()
|
| 699 |
+
self.P_post = self.P.copy()
|
| 700 |
+
|
| 701 |
+
def batch_filter(self, zs, Fs=None, Qs=None, Hs=None,
|
| 702 |
+
Rs=None, Bs=None, us=None, update_first=False,
|
| 703 |
+
saver=None):
|
| 704 |
+
""" Batch processes a sequences of measurements.
|
| 705 |
+
Parameters
|
| 706 |
+
----------
|
| 707 |
+
zs : list-like
|
| 708 |
+
list of measurements at each time step `self.dt`. Missing
|
| 709 |
+
measurements must be represented by `None`.
|
| 710 |
+
Fs : None, list-like, default=None
|
| 711 |
+
optional value or list of values to use for the state transition
|
| 712 |
+
matrix F.
|
| 713 |
+
If Fs is None then self.F is used for all epochs.
|
| 714 |
+
Otherwise it must contain a list-like list of F's, one for
|
| 715 |
+
each epoch. This allows you to have varying F per epoch.
|
| 716 |
+
Qs : None, np.array or list-like, default=None
|
| 717 |
+
optional value or list of values to use for the process error
|
| 718 |
+
covariance Q.
|
| 719 |
+
If Qs is None then self.Q is used for all epochs.
|
| 720 |
+
Otherwise it must contain a list-like list of Q's, one for
|
| 721 |
+
each epoch. This allows you to have varying Q per epoch.
|
| 722 |
+
Hs : None, np.array or list-like, default=None
|
| 723 |
+
optional list of values to use for the measurement matrix H.
|
| 724 |
+
If Hs is None then self.H is used for all epochs.
|
| 725 |
+
If Hs contains a single matrix, then it is used as H for all
|
| 726 |
+
epochs.
|
| 727 |
+
Otherwise it must contain a list-like list of H's, one for
|
| 728 |
+
each epoch. This allows you to have varying H per epoch.
|
| 729 |
+
Rs : None, np.array or list-like, default=None
|
| 730 |
+
optional list of values to use for the measurement error
|
| 731 |
+
covariance R.
|
| 732 |
+
If Rs is None then self.R is used for all epochs.
|
| 733 |
+
Otherwise it must contain a list-like list of R's, one for
|
| 734 |
+
each epoch. This allows you to have varying R per epoch.
|
| 735 |
+
Bs : None, np.array or list-like, default=None
|
| 736 |
+
optional list of values to use for the control transition matrix B.
|
| 737 |
+
If Bs is None then self.B is used for all epochs.
|
| 738 |
+
Otherwise it must contain a list-like list of B's, one for
|
| 739 |
+
each epoch. This allows you to have varying B per epoch.
|
| 740 |
+
us : None, np.array or list-like, default=None
|
| 741 |
+
optional list of values to use for the control input vector;
|
| 742 |
+
If us is None then None is used for all epochs (equivalent to 0,
|
| 743 |
+
or no control input).
|
| 744 |
+
Otherwise it must contain a list-like list of u's, one for
|
| 745 |
+
each epoch.
|
| 746 |
+
update_first : bool, optional, default=False
|
| 747 |
+
controls whether the order of operations is update followed by
|
| 748 |
+
predict, or predict followed by update. Default is predict->update.
|
| 749 |
+
saver : filterpy.common.Saver, optional
|
| 750 |
+
filterpy.common.Saver object. If provided, saver.save() will be
|
| 751 |
+
called after every epoch
|
| 752 |
+
Returns
|
| 753 |
+
-------
|
| 754 |
+
means : np.array((n,dim_x,1))
|
| 755 |
+
array of the state for each time step after the update. Each entry
|
| 756 |
+
is an np.array. In other words `means[k,:]` is the state at step
|
| 757 |
+
`k`.
|
| 758 |
+
covariance : np.array((n,dim_x,dim_x))
|
| 759 |
+
array of the covariances for each time step after the update.
|
| 760 |
+
In other words `covariance[k,:,:]` is the covariance at step `k`.
|
| 761 |
+
means_predictions : np.array((n,dim_x,1))
|
| 762 |
+
array of the state for each time step after the predictions. Each
|
| 763 |
+
entry is an np.array. In other words `means[k,:]` is the state at
|
| 764 |
+
step `k`.
|
| 765 |
+
covariance_predictions : np.array((n,dim_x,dim_x))
|
| 766 |
+
array of the covariances for each time step after the prediction.
|
| 767 |
+
In other words `covariance[k,:,:]` is the covariance at step `k`.
|
| 768 |
+
Examples
|
| 769 |
+
--------
|
| 770 |
+
.. code-block:: Python
|
| 771 |
+
# this example demonstrates tracking a measurement where the time
|
| 772 |
+
# between measurement varies, as stored in dts. This requires
|
| 773 |
+
# that F be recomputed for each epoch. The output is then smoothed
|
| 774 |
+
# with an RTS smoother.
|
| 775 |
+
zs = [t + random.randn()*4 for t in range (40)]
|
| 776 |
+
Fs = [np.array([[1., dt], [0, 1]] for dt in dts]
|
| 777 |
+
(mu, cov, _, _) = kf.batch_filter(zs, Fs=Fs)
|
| 778 |
+
(xs, Ps, Ks, Pps) = kf.rts_smoother(mu, cov, Fs=Fs)
|
| 779 |
+
"""
|
| 780 |
+
|
| 781 |
+
#pylint: disable=too-many-statements
|
| 782 |
+
n = np.size(zs, 0)
|
| 783 |
+
if Fs is None:
|
| 784 |
+
Fs = [self.F] * n
|
| 785 |
+
if Qs is None:
|
| 786 |
+
Qs = [self.Q] * n
|
| 787 |
+
if Hs is None:
|
| 788 |
+
Hs = [self.H] * n
|
| 789 |
+
if Rs is None:
|
| 790 |
+
Rs = [self.R] * n
|
| 791 |
+
if Bs is None:
|
| 792 |
+
Bs = [self.B] * n
|
| 793 |
+
if us is None:
|
| 794 |
+
us = [0] * n
|
| 795 |
+
|
| 796 |
+
# mean estimates from Kalman Filter
|
| 797 |
+
if self.x.ndim == 1:
|
| 798 |
+
means = zeros((n, self.dim_x))
|
| 799 |
+
means_p = zeros((n, self.dim_x))
|
| 800 |
+
else:
|
| 801 |
+
means = zeros((n, self.dim_x, 1))
|
| 802 |
+
means_p = zeros((n, self.dim_x, 1))
|
| 803 |
+
|
| 804 |
+
# state covariances from Kalman Filter
|
| 805 |
+
covariances = zeros((n, self.dim_x, self.dim_x))
|
| 806 |
+
covariances_p = zeros((n, self.dim_x, self.dim_x))
|
| 807 |
+
|
| 808 |
+
if update_first:
|
| 809 |
+
for i, (z, F, Q, H, R, B, u) in enumerate(zip(zs, Fs, Qs, Hs, Rs, Bs, us)):
|
| 810 |
+
|
| 811 |
+
self.update(z, R=R, H=H)
|
| 812 |
+
means[i, :] = self.x
|
| 813 |
+
covariances[i, :, :] = self.P
|
| 814 |
+
|
| 815 |
+
self.predict(u=u, B=B, F=F, Q=Q)
|
| 816 |
+
means_p[i, :] = self.x
|
| 817 |
+
covariances_p[i, :, :] = self.P
|
| 818 |
+
|
| 819 |
+
if saver is not None:
|
| 820 |
+
saver.save()
|
| 821 |
+
else:
|
| 822 |
+
for i, (z, F, Q, H, R, B, u) in enumerate(zip(zs, Fs, Qs, Hs, Rs, Bs, us)):
|
| 823 |
+
|
| 824 |
+
self.predict(u=u, B=B, F=F, Q=Q)
|
| 825 |
+
means_p[i, :] = self.x
|
| 826 |
+
covariances_p[i, :, :] = self.P
|
| 827 |
+
|
| 828 |
+
self.update(z, R=R, H=H)
|
| 829 |
+
means[i, :] = self.x
|
| 830 |
+
covariances[i, :, :] = self.P
|
| 831 |
+
|
| 832 |
+
if saver is not None:
|
| 833 |
+
saver.save()
|
| 834 |
+
|
| 835 |
+
return (means, covariances, means_p, covariances_p)
|
| 836 |
+
|
| 837 |
+
def rts_smoother(self, Xs, Ps, Fs=None, Qs=None, inv=np.linalg.inv):
|
| 838 |
+
"""
|
| 839 |
+
Runs the Rauch-Tung-Striebel Kalman smoother on a set of
|
| 840 |
+
means and covariances computed by a Kalman filter. The usual input
|
| 841 |
+
would come from the output of `KalmanFilter.batch_filter()`.
|
| 842 |
+
Parameters
|
| 843 |
+
----------
|
| 844 |
+
Xs : numpy.array
|
| 845 |
+
array of the means (state variable x) of the output of a Kalman
|
| 846 |
+
filter.
|
| 847 |
+
Ps : numpy.array
|
| 848 |
+
array of the covariances of the output of a kalman filter.
|
| 849 |
+
Fs : list-like collection of numpy.array, optional
|
| 850 |
+
State transition matrix of the Kalman filter at each time step.
|
| 851 |
+
Optional, if not provided the filter's self.F will be used
|
| 852 |
+
Qs : list-like collection of numpy.array, optional
|
| 853 |
+
Process noise of the Kalman filter at each time step. Optional,
|
| 854 |
+
if not provided the filter's self.Q will be used
|
| 855 |
+
inv : function, default numpy.linalg.inv
|
| 856 |
+
If you prefer another inverse function, such as the Moore-Penrose
|
| 857 |
+
pseudo inverse, set it to that instead: kf.inv = np.linalg.pinv
|
| 858 |
+
Returns
|
| 859 |
+
-------
|
| 860 |
+
x : numpy.ndarray
|
| 861 |
+
smoothed means
|
| 862 |
+
P : numpy.ndarray
|
| 863 |
+
smoothed state covariances
|
| 864 |
+
K : numpy.ndarray
|
| 865 |
+
smoother gain at each step
|
| 866 |
+
Pp : numpy.ndarray
|
| 867 |
+
Predicted state covariances
|
| 868 |
+
Examples
|
| 869 |
+
--------
|
| 870 |
+
.. code-block:: Python
|
| 871 |
+
zs = [t + random.randn()*4 for t in range (40)]
|
| 872 |
+
(mu, cov, _, _) = kalman.batch_filter(zs)
|
| 873 |
+
(x, P, K, Pp) = rts_smoother(mu, cov, kf.F, kf.Q)
|
| 874 |
+
"""
|
| 875 |
+
|
| 876 |
+
if len(Xs) != len(Ps):
|
| 877 |
+
raise ValueError('length of Xs and Ps must be the same')
|
| 878 |
+
|
| 879 |
+
n = Xs.shape[0]
|
| 880 |
+
dim_x = Xs.shape[1]
|
| 881 |
+
|
| 882 |
+
if Fs is None:
|
| 883 |
+
Fs = [self.F] * n
|
| 884 |
+
if Qs is None:
|
| 885 |
+
Qs = [self.Q] * n
|
| 886 |
+
|
| 887 |
+
# smoother gain
|
| 888 |
+
K = zeros((n, dim_x, dim_x))
|
| 889 |
+
|
| 890 |
+
x, P, Pp = Xs.copy(), Ps.copy(), Ps.copy()
|
| 891 |
+
for k in range(n-2, -1, -1):
|
| 892 |
+
Pp[k] = dot(dot(Fs[k+1], P[k]), Fs[k+1].T) + Qs[k+1]
|
| 893 |
+
|
| 894 |
+
#pylint: disable=bad-whitespace
|
| 895 |
+
K[k] = dot(dot(P[k], Fs[k+1].T), inv(Pp[k]))
|
| 896 |
+
x[k] += dot(K[k], x[k+1] - dot(Fs[k+1], x[k]))
|
| 897 |
+
P[k] += dot(dot(K[k], P[k+1] - Pp[k]), K[k].T)
|
| 898 |
+
|
| 899 |
+
return (x, P, K, Pp)
|
| 900 |
+
|
| 901 |
+
def get_prediction(self, u=None, B=None, F=None, Q=None):
|
| 902 |
+
"""
|
| 903 |
+
Predict next state (prior) using the Kalman filter state propagation
|
| 904 |
+
equations and returns it without modifying the object.
|
| 905 |
+
Parameters
|
| 906 |
+
----------
|
| 907 |
+
u : np.array, default 0
|
| 908 |
+
Optional control vector.
|
| 909 |
+
B : np.array(dim_x, dim_u), or None
|
| 910 |
+
Optional control transition matrix; a value of None
|
| 911 |
+
will cause the filter to use `self.B`.
|
| 912 |
+
F : np.array(dim_x, dim_x), or None
|
| 913 |
+
Optional state transition matrix; a value of None
|
| 914 |
+
will cause the filter to use `self.F`.
|
| 915 |
+
Q : np.array(dim_x, dim_x), scalar, or None
|
| 916 |
+
Optional process noise matrix; a value of None will cause the
|
| 917 |
+
filter to use `self.Q`.
|
| 918 |
+
Returns
|
| 919 |
+
-------
|
| 920 |
+
(x, P) : tuple
|
| 921 |
+
State vector and covariance array of the prediction.
|
| 922 |
+
"""
|
| 923 |
+
|
| 924 |
+
if B is None:
|
| 925 |
+
B = self.B
|
| 926 |
+
if F is None:
|
| 927 |
+
F = self.F
|
| 928 |
+
if Q is None:
|
| 929 |
+
Q = self.Q
|
| 930 |
+
elif isscalar(Q):
|
| 931 |
+
Q = eye(self.dim_x) * Q
|
| 932 |
+
|
| 933 |
+
# x = Fx + Bu
|
| 934 |
+
if B is not None and u is not None:
|
| 935 |
+
x = dot(F, self.x) + dot(B, u)
|
| 936 |
+
else:
|
| 937 |
+
x = dot(F, self.x)
|
| 938 |
+
|
| 939 |
+
# P = FPF' + Q
|
| 940 |
+
P = self._alpha_sq * dot(dot(F, self.P), F.T) + Q
|
| 941 |
+
|
| 942 |
+
return x, P
|
| 943 |
+
|
| 944 |
+
def get_update(self, z=None):
|
| 945 |
+
"""
|
| 946 |
+
Computes the new estimate based on measurement `z` and returns it
|
| 947 |
+
without altering the state of the filter.
|
| 948 |
+
Parameters
|
| 949 |
+
----------
|
| 950 |
+
z : (dim_z, 1): array_like
|
| 951 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 952 |
+
otherwise it must be convertible to a column vector.
|
| 953 |
+
Returns
|
| 954 |
+
-------
|
| 955 |
+
(x, P) : tuple
|
| 956 |
+
State vector and covariance array of the update.
|
| 957 |
+
"""
|
| 958 |
+
|
| 959 |
+
if z is None:
|
| 960 |
+
return self.x, self.P
|
| 961 |
+
z = reshape_z(z, self.dim_z, self.x.ndim)
|
| 962 |
+
|
| 963 |
+
R = self.R
|
| 964 |
+
H = self.H
|
| 965 |
+
P = self.P
|
| 966 |
+
x = self.x
|
| 967 |
+
|
| 968 |
+
# error (residual) between measurement and prediction
|
| 969 |
+
y = z - dot(H, x)
|
| 970 |
+
|
| 971 |
+
# common subexpression for speed
|
| 972 |
+
PHT = dot(P, H.T)
|
| 973 |
+
|
| 974 |
+
# project system uncertainty into measurement space
|
| 975 |
+
S = dot(H, PHT) + R
|
| 976 |
+
|
| 977 |
+
# map system uncertainty into kalman gain
|
| 978 |
+
K = dot(PHT, self.inv(S))
|
| 979 |
+
|
| 980 |
+
# predict new x with residual scaled by the kalman gain
|
| 981 |
+
x = x + dot(K, y)
|
| 982 |
+
|
| 983 |
+
# P = (I-KH)P(I-KH)' + KRK'
|
| 984 |
+
I_KH = self._I - dot(K, H)
|
| 985 |
+
P = dot(dot(I_KH, P), I_KH.T) + dot(dot(K, R), K.T)
|
| 986 |
+
|
| 987 |
+
return x, P
|
| 988 |
+
|
| 989 |
+
def residual_of(self, z):
|
| 990 |
+
"""
|
| 991 |
+
Returns the residual for the given measurement (z). Does not alter
|
| 992 |
+
the state of the filter.
|
| 993 |
+
"""
|
| 994 |
+
z = reshape_z(z, self.dim_z, self.x.ndim)
|
| 995 |
+
return z - dot(self.H, self.x_prior)
|
| 996 |
+
|
| 997 |
+
def measurement_of_state(self, x):
|
| 998 |
+
"""
|
| 999 |
+
Helper function that converts a state into a measurement.
|
| 1000 |
+
Parameters
|
| 1001 |
+
----------
|
| 1002 |
+
x : np.array
|
| 1003 |
+
kalman state vector
|
| 1004 |
+
Returns
|
| 1005 |
+
-------
|
| 1006 |
+
z : (dim_z, 1): array_like
|
| 1007 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 1008 |
+
otherwise it must be convertible to a column vector.
|
| 1009 |
+
"""
|
| 1010 |
+
|
| 1011 |
+
return dot(self.H, x)
|
| 1012 |
+
|
| 1013 |
+
@property
|
| 1014 |
+
def log_likelihood(self):
|
| 1015 |
+
"""
|
| 1016 |
+
log-likelihood of the last measurement.
|
| 1017 |
+
"""
|
| 1018 |
+
if self._log_likelihood is None:
|
| 1019 |
+
self._log_likelihood = logpdf(x=self.y, cov=self.S)
|
| 1020 |
+
return self._log_likelihood
|
| 1021 |
+
|
| 1022 |
+
@property
|
| 1023 |
+
def likelihood(self):
|
| 1024 |
+
"""
|
| 1025 |
+
Computed from the log-likelihood. The log-likelihood can be very
|
| 1026 |
+
small, meaning a large negative value such as -28000. Taking the
|
| 1027 |
+
exp() of that results in 0.0, which can break typical algorithms
|
| 1028 |
+
which multiply by this value, so by default we always return a
|
| 1029 |
+
number >= sys.float_info.min.
|
| 1030 |
+
"""
|
| 1031 |
+
if self._likelihood is None:
|
| 1032 |
+
self._likelihood = exp(self.log_likelihood)
|
| 1033 |
+
if self._likelihood == 0:
|
| 1034 |
+
self._likelihood = sys.float_info.min
|
| 1035 |
+
return self._likelihood
|
| 1036 |
+
|
| 1037 |
+
@property
|
| 1038 |
+
def mahalanobis(self):
|
| 1039 |
+
""""
|
| 1040 |
+
Mahalanobis distance of measurement. E.g. 3 means measurement
|
| 1041 |
+
was 3 standard deviations away from the predicted value.
|
| 1042 |
+
Returns
|
| 1043 |
+
-------
|
| 1044 |
+
mahalanobis : float
|
| 1045 |
+
"""
|
| 1046 |
+
if self._mahalanobis is None:
|
| 1047 |
+
self._mahalanobis = sqrt(float(dot(dot(self.y.T, self.SI), self.y)))
|
| 1048 |
+
return self._mahalanobis
|
| 1049 |
+
|
| 1050 |
+
@property
|
| 1051 |
+
def alpha(self):
|
| 1052 |
+
"""
|
| 1053 |
+
Fading memory setting. 1.0 gives the normal Kalman filter, and
|
| 1054 |
+
values slightly larger than 1.0 (such as 1.02) give a fading
|
| 1055 |
+
memory effect - previous measurements have less influence on the
|
| 1056 |
+
filter's estimates. This formulation of the Fading memory filter
|
| 1057 |
+
(there are many) is due to Dan Simon [1]_.
|
| 1058 |
+
"""
|
| 1059 |
+
return self._alpha_sq**.5
|
| 1060 |
+
|
| 1061 |
+
def log_likelihood_of(self, z):
|
| 1062 |
+
"""
|
| 1063 |
+
log likelihood of the measurement `z`. This should only be called
|
| 1064 |
+
after a call to update(). Calling after predict() will yield an
|
| 1065 |
+
incorrect result."""
|
| 1066 |
+
|
| 1067 |
+
if z is None:
|
| 1068 |
+
return log(sys.float_info.min)
|
| 1069 |
+
return logpdf(z, dot(self.H, self.x), self.S)
|
| 1070 |
+
|
| 1071 |
+
@alpha.setter
|
| 1072 |
+
def alpha(self, value):
|
| 1073 |
+
if not np.isscalar(value) or value < 1:
|
| 1074 |
+
raise ValueError('alpha must be a float greater than 1')
|
| 1075 |
+
|
| 1076 |
+
self._alpha_sq = value**2
|
| 1077 |
+
|
| 1078 |
+
def __repr__(self):
|
| 1079 |
+
return '\n'.join([
|
| 1080 |
+
'KalmanFilter object',
|
| 1081 |
+
pretty_str('dim_x', self.dim_x),
|
| 1082 |
+
pretty_str('dim_z', self.dim_z),
|
| 1083 |
+
pretty_str('dim_u', self.dim_u),
|
| 1084 |
+
pretty_str('x', self.x),
|
| 1085 |
+
pretty_str('P', self.P),
|
| 1086 |
+
pretty_str('x_prior', self.x_prior),
|
| 1087 |
+
pretty_str('P_prior', self.P_prior),
|
| 1088 |
+
pretty_str('x_post', self.x_post),
|
| 1089 |
+
pretty_str('P_post', self.P_post),
|
| 1090 |
+
pretty_str('F', self.F),
|
| 1091 |
+
pretty_str('Q', self.Q),
|
| 1092 |
+
pretty_str('R', self.R),
|
| 1093 |
+
pretty_str('H', self.H),
|
| 1094 |
+
pretty_str('K', self.K),
|
| 1095 |
+
pretty_str('y', self.y),
|
| 1096 |
+
pretty_str('S', self.S),
|
| 1097 |
+
pretty_str('SI', self.SI),
|
| 1098 |
+
pretty_str('M', self.M),
|
| 1099 |
+
pretty_str('B', self.B),
|
| 1100 |
+
pretty_str('z', self.z),
|
| 1101 |
+
pretty_str('log-likelihood', self.log_likelihood),
|
| 1102 |
+
pretty_str('likelihood', self.likelihood),
|
| 1103 |
+
pretty_str('mahalanobis', self.mahalanobis),
|
| 1104 |
+
pretty_str('alpha', self.alpha),
|
| 1105 |
+
pretty_str('inv', self.inv)
|
| 1106 |
+
])
|
| 1107 |
+
|
| 1108 |
+
def test_matrix_dimensions(self, z=None, H=None, R=None, F=None, Q=None):
|
| 1109 |
+
"""
|
| 1110 |
+
Performs a series of asserts to check that the size of everything
|
| 1111 |
+
is what it should be. This can help you debug problems in your design.
|
| 1112 |
+
If you pass in H, R, F, Q those will be used instead of this object's
|
| 1113 |
+
value for those matrices.
|
| 1114 |
+
Testing `z` (the measurement) is problamatic. x is a vector, and can be
|
| 1115 |
+
implemented as either a 1D array or as a nx1 column vector. Thus Hx
|
| 1116 |
+
can be of different shapes. Then, if Hx is a single value, it can
|
| 1117 |
+
be either a 1D array or 2D vector. If either is true, z can reasonably
|
| 1118 |
+
be a scalar (either '3' or np.array('3') are scalars under this
|
| 1119 |
+
definition), a 1D, 1 element array, or a 2D, 1 element array. You are
|
| 1120 |
+
allowed to pass in any combination that works.
|
| 1121 |
+
"""
|
| 1122 |
+
|
| 1123 |
+
if H is None:
|
| 1124 |
+
H = self.H
|
| 1125 |
+
if R is None:
|
| 1126 |
+
R = self.R
|
| 1127 |
+
if F is None:
|
| 1128 |
+
F = self.F
|
| 1129 |
+
if Q is None:
|
| 1130 |
+
Q = self.Q
|
| 1131 |
+
x = self.x
|
| 1132 |
+
P = self.P
|
| 1133 |
+
|
| 1134 |
+
assert x.ndim == 1 or x.ndim == 2, \
|
| 1135 |
+
"x must have one or two dimensions, but has {}".format(x.ndim)
|
| 1136 |
+
|
| 1137 |
+
if x.ndim == 1:
|
| 1138 |
+
assert x.shape[0] == self.dim_x, \
|
| 1139 |
+
"Shape of x must be ({},{}), but is {}".format(
|
| 1140 |
+
self.dim_x, 1, x.shape)
|
| 1141 |
+
else:
|
| 1142 |
+
assert x.shape == (self.dim_x, 1), \
|
| 1143 |
+
"Shape of x must be ({},{}), but is {}".format(
|
| 1144 |
+
self.dim_x, 1, x.shape)
|
| 1145 |
+
|
| 1146 |
+
assert P.shape == (self.dim_x, self.dim_x), \
|
| 1147 |
+
"Shape of P must be ({},{}), but is {}".format(
|
| 1148 |
+
self.dim_x, self.dim_x, P.shape)
|
| 1149 |
+
|
| 1150 |
+
assert Q.shape == (self.dim_x, self.dim_x), \
|
| 1151 |
+
"Shape of Q must be ({},{}), but is {}".format(
|
| 1152 |
+
self.dim_x, self.dim_x, P.shape)
|
| 1153 |
+
|
| 1154 |
+
assert F.shape == (self.dim_x, self.dim_x), \
|
| 1155 |
+
"Shape of F must be ({},{}), but is {}".format(
|
| 1156 |
+
self.dim_x, self.dim_x, F.shape)
|
| 1157 |
+
|
| 1158 |
+
assert np.ndim(H) == 2, \
|
| 1159 |
+
"Shape of H must be (dim_z, {}), but is {}".format(
|
| 1160 |
+
P.shape[0], shape(H))
|
| 1161 |
+
|
| 1162 |
+
assert H.shape[1] == P.shape[0], \
|
| 1163 |
+
"Shape of H must be (dim_z, {}), but is {}".format(
|
| 1164 |
+
P.shape[0], H.shape)
|
| 1165 |
+
|
| 1166 |
+
# shape of R must be the same as HPH'
|
| 1167 |
+
hph_shape = (H.shape[0], H.shape[0])
|
| 1168 |
+
r_shape = shape(R)
|
| 1169 |
+
|
| 1170 |
+
if H.shape[0] == 1:
|
| 1171 |
+
# r can be scalar, 1D, or 2D in this case
|
| 1172 |
+
assert r_shape in [(), (1,), (1, 1)], \
|
| 1173 |
+
"R must be scalar or one element array, but is shaped {}".format(
|
| 1174 |
+
r_shape)
|
| 1175 |
+
else:
|
| 1176 |
+
assert r_shape == hph_shape, \
|
| 1177 |
+
"shape of R should be {} but it is {}".format(hph_shape, r_shape)
|
| 1178 |
+
|
| 1179 |
+
|
| 1180 |
+
if z is not None:
|
| 1181 |
+
z_shape = shape(z)
|
| 1182 |
+
else:
|
| 1183 |
+
z_shape = (self.dim_z, 1)
|
| 1184 |
+
|
| 1185 |
+
# H@x must have shape of z
|
| 1186 |
+
Hx = dot(H, x)
|
| 1187 |
+
|
| 1188 |
+
if z_shape == (): # scalar or np.array(scalar)
|
| 1189 |
+
assert Hx.ndim == 1 or shape(Hx) == (1, 1), \
|
| 1190 |
+
"shape of z should be {}, not {} for the given H".format(
|
| 1191 |
+
shape(Hx), z_shape)
|
| 1192 |
+
|
| 1193 |
+
elif shape(Hx) == (1,):
|
| 1194 |
+
assert z_shape[0] == 1, 'Shape of z must be {} for the given H'.format(shape(Hx))
|
| 1195 |
+
|
| 1196 |
+
else:
|
| 1197 |
+
assert (z_shape == shape(Hx) or
|
| 1198 |
+
(len(z_shape) == 1 and shape(Hx) == (z_shape[0], 1))), \
|
| 1199 |
+
"shape of z should be {}, not {} for the given H".format(
|
| 1200 |
+
shape(Hx), z_shape)
|
| 1201 |
+
|
| 1202 |
+
if np.ndim(Hx) > 1 and shape(Hx) != (1, 1):
|
| 1203 |
+
assert shape(Hx) == z_shape, \
|
| 1204 |
+
'shape of z should be {} for the given H, but it is {}'.format(
|
| 1205 |
+
shape(Hx), z_shape)
|
| 1206 |
+
|
| 1207 |
+
|
| 1208 |
+
def update(x, P, z, R, H=None, return_all=False):
|
| 1209 |
+
"""
|
| 1210 |
+
Add a new measurement (z) to the Kalman filter. If z is None, nothing
|
| 1211 |
+
is changed.
|
| 1212 |
+
This can handle either the multidimensional or unidimensional case. If
|
| 1213 |
+
all parameters are floats instead of arrays the filter will still work,
|
| 1214 |
+
and return floats for x, P as the result.
|
| 1215 |
+
update(1, 2, 1, 1, 1) # univariate
|
| 1216 |
+
update(x, P, 1
|
| 1217 |
+
Parameters
|
| 1218 |
+
----------
|
| 1219 |
+
x : numpy.array(dim_x, 1), or float
|
| 1220 |
+
State estimate vector
|
| 1221 |
+
P : numpy.array(dim_x, dim_x), or float
|
| 1222 |
+
Covariance matrix
|
| 1223 |
+
z : (dim_z, 1): array_like
|
| 1224 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 1225 |
+
otherwise it must be convertible to a column vector.
|
| 1226 |
+
R : numpy.array(dim_z, dim_z), or float
|
| 1227 |
+
Measurement noise matrix
|
| 1228 |
+
H : numpy.array(dim_x, dim_x), or float, optional
|
| 1229 |
+
Measurement function. If not provided, a value of 1 is assumed.
|
| 1230 |
+
return_all : bool, default False
|
| 1231 |
+
If true, y, K, S, and log_likelihood are returned, otherwise
|
| 1232 |
+
only x and P are returned.
|
| 1233 |
+
Returns
|
| 1234 |
+
-------
|
| 1235 |
+
x : numpy.array
|
| 1236 |
+
Posterior state estimate vector
|
| 1237 |
+
P : numpy.array
|
| 1238 |
+
Posterior covariance matrix
|
| 1239 |
+
y : numpy.array or scalar
|
| 1240 |
+
Residua. Difference between measurement and state in measurement space
|
| 1241 |
+
K : numpy.array
|
| 1242 |
+
Kalman gain
|
| 1243 |
+
S : numpy.array
|
| 1244 |
+
System uncertainty in measurement space
|
| 1245 |
+
log_likelihood : float
|
| 1246 |
+
log likelihood of the measurement
|
| 1247 |
+
"""
|
| 1248 |
+
|
| 1249 |
+
#pylint: disable=bare-except
|
| 1250 |
+
|
| 1251 |
+
if z is None:
|
| 1252 |
+
if return_all:
|
| 1253 |
+
return x, P, None, None, None, None
|
| 1254 |
+
return x, P
|
| 1255 |
+
|
| 1256 |
+
if H is None:
|
| 1257 |
+
H = np.array([1])
|
| 1258 |
+
|
| 1259 |
+
if np.isscalar(H):
|
| 1260 |
+
H = np.array([H])
|
| 1261 |
+
|
| 1262 |
+
Hx = np.atleast_1d(dot(H, x))
|
| 1263 |
+
z = reshape_z(z, Hx.shape[0], x.ndim)
|
| 1264 |
+
|
| 1265 |
+
# error (residual) between measurement and prediction
|
| 1266 |
+
y = z - Hx
|
| 1267 |
+
|
| 1268 |
+
# project system uncertainty into measurement space
|
| 1269 |
+
S = dot(dot(H, P), H.T) + R
|
| 1270 |
+
|
| 1271 |
+
|
| 1272 |
+
# map system uncertainty into kalman gain
|
| 1273 |
+
try:
|
| 1274 |
+
K = dot(dot(P, H.T), linalg.inv(S))
|
| 1275 |
+
except:
|
| 1276 |
+
# can't invert a 1D array, annoyingly
|
| 1277 |
+
K = dot(dot(P, H.T), 1./S)
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
# predict new x with residual scaled by the kalman gain
|
| 1281 |
+
x = x + dot(K, y)
|
| 1282 |
+
|
| 1283 |
+
# P = (I-KH)P(I-KH)' + KRK'
|
| 1284 |
+
KH = dot(K, H)
|
| 1285 |
+
|
| 1286 |
+
try:
|
| 1287 |
+
I_KH = np.eye(KH.shape[0]) - KH
|
| 1288 |
+
except:
|
| 1289 |
+
I_KH = np.array([1 - KH])
|
| 1290 |
+
P = dot(dot(I_KH, P), I_KH.T) + dot(dot(K, R), K.T)
|
| 1291 |
+
|
| 1292 |
+
|
| 1293 |
+
if return_all:
|
| 1294 |
+
# compute log likelihood
|
| 1295 |
+
log_likelihood = logpdf(z, dot(H, x), S)
|
| 1296 |
+
return x, P, y, K, S, log_likelihood
|
| 1297 |
+
return x, P
|
| 1298 |
+
|
| 1299 |
+
|
| 1300 |
+
def update_steadystate(x, z, K, H=None):
|
| 1301 |
+
"""
|
| 1302 |
+
Add a new measurement (z) to the Kalman filter. If z is None, nothing
|
| 1303 |
+
is changed.
|
| 1304 |
+
Parameters
|
| 1305 |
+
----------
|
| 1306 |
+
x : numpy.array(dim_x, 1), or float
|
| 1307 |
+
State estimate vector
|
| 1308 |
+
z : (dim_z, 1): array_like
|
| 1309 |
+
measurement for this update. z can be a scalar if dim_z is 1,
|
| 1310 |
+
otherwise it must be convertible to a column vector.
|
| 1311 |
+
K : numpy.array, or float
|
| 1312 |
+
Kalman gain matrix
|
| 1313 |
+
H : numpy.array(dim_x, dim_x), or float, optional
|
| 1314 |
+
Measurement function. If not provided, a value of 1 is assumed.
|
| 1315 |
+
Returns
|
| 1316 |
+
-------
|
| 1317 |
+
x : numpy.array
|
| 1318 |
+
Posterior state estimate vector
|
| 1319 |
+
Examples
|
| 1320 |
+
--------
|
| 1321 |
+
This can handle either the multidimensional or unidimensional case. If
|
| 1322 |
+
all parameters are floats instead of arrays the filter will still work,
|
| 1323 |
+
and return floats for x, P as the result.
|
| 1324 |
+
>>> update_steadystate(1, 2, 1) # univariate
|
| 1325 |
+
>>> update_steadystate(x, P, z, H)
|
| 1326 |
+
"""
|
| 1327 |
+
|
| 1328 |
+
|
| 1329 |
+
if z is None:
|
| 1330 |
+
return x
|
| 1331 |
+
|
| 1332 |
+
if H is None:
|
| 1333 |
+
H = np.array([1])
|
| 1334 |
+
|
| 1335 |
+
if np.isscalar(H):
|
| 1336 |
+
H = np.array([H])
|
| 1337 |
+
|
| 1338 |
+
Hx = np.atleast_1d(dot(H, x))
|
| 1339 |
+
z = reshape_z(z, Hx.shape[0], x.ndim)
|
| 1340 |
+
|
| 1341 |
+
# error (residual) between measurement and prediction
|
| 1342 |
+
y = z - Hx
|
| 1343 |
+
|
| 1344 |
+
# estimate new x with residual scaled by the kalman gain
|
| 1345 |
+
return x + dot(K, y)
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.):
|
| 1349 |
+
"""
|
| 1350 |
+
Predict next state (prior) using the Kalman filter state propagation
|
| 1351 |
+
equations.
|
| 1352 |
+
Parameters
|
| 1353 |
+
----------
|
| 1354 |
+
x : numpy.array
|
| 1355 |
+
State estimate vector
|
| 1356 |
+
P : numpy.array
|
| 1357 |
+
Covariance matrix
|
| 1358 |
+
F : numpy.array()
|
| 1359 |
+
State Transition matrix
|
| 1360 |
+
Q : numpy.array, Optional
|
| 1361 |
+
Process noise matrix
|
| 1362 |
+
u : numpy.array, Optional, default 0.
|
| 1363 |
+
Control vector. If non-zero, it is multiplied by B
|
| 1364 |
+
to create the control input into the system.
|
| 1365 |
+
B : numpy.array, optional, default 0.
|
| 1366 |
+
Control transition matrix.
|
| 1367 |
+
alpha : float, Optional, default=1.0
|
| 1368 |
+
Fading memory setting. 1.0 gives the normal Kalman filter, and
|
| 1369 |
+
values slightly larger than 1.0 (such as 1.02) give a fading
|
| 1370 |
+
memory effect - previous measurements have less influence on the
|
| 1371 |
+
filter's estimates. This formulation of the Fading memory filter
|
| 1372 |
+
(there are many) is due to Dan Simon
|
| 1373 |
+
Returns
|
| 1374 |
+
-------
|
| 1375 |
+
x : numpy.array
|
| 1376 |
+
Prior state estimate vector
|
| 1377 |
+
P : numpy.array
|
| 1378 |
+
Prior covariance matrix
|
| 1379 |
+
"""
|
| 1380 |
+
|
| 1381 |
+
if np.isscalar(F):
|
| 1382 |
+
F = np.array(F)
|
| 1383 |
+
x = dot(F, x) + dot(B, u)
|
| 1384 |
+
P = (alpha * alpha) * dot(dot(F, P), F.T) + Q
|
| 1385 |
+
|
| 1386 |
+
return x, P
|
| 1387 |
+
|
| 1388 |
+
|
| 1389 |
+
def predict_steadystate(x, F=1, u=0, B=1):
|
| 1390 |
+
"""
|
| 1391 |
+
Predict next state (prior) using the Kalman filter state propagation
|
| 1392 |
+
equations. This steady state form only computes x, assuming that the
|
| 1393 |
+
covariance is constant.
|
| 1394 |
+
Parameters
|
| 1395 |
+
----------
|
| 1396 |
+
x : numpy.array
|
| 1397 |
+
State estimate vector
|
| 1398 |
+
P : numpy.array
|
| 1399 |
+
Covariance matrix
|
| 1400 |
+
F : numpy.array()
|
| 1401 |
+
State Transition matrix
|
| 1402 |
+
u : numpy.array, Optional, default 0.
|
| 1403 |
+
Control vector. If non-zero, it is multiplied by B
|
| 1404 |
+
to create the control input into the system.
|
| 1405 |
+
B : numpy.array, optional, default 0.
|
| 1406 |
+
Control transition matrix.
|
| 1407 |
+
Returns
|
| 1408 |
+
-------
|
| 1409 |
+
x : numpy.array
|
| 1410 |
+
Prior state estimate vector
|
| 1411 |
+
"""
|
| 1412 |
+
|
| 1413 |
+
if np.isscalar(F):
|
| 1414 |
+
F = np.array(F)
|
| 1415 |
+
x = dot(F, x) + dot(B, u)
|
| 1416 |
+
|
| 1417 |
+
return x
|
| 1418 |
+
|
| 1419 |
+
|
| 1420 |
+
|
| 1421 |
+
def batch_filter(x, P, zs, Fs, Qs, Hs, Rs, Bs=None, us=None,
|
| 1422 |
+
update_first=False, saver=None):
|
| 1423 |
+
"""
|
| 1424 |
+
Batch processes a sequences of measurements.
|
| 1425 |
+
Parameters
|
| 1426 |
+
----------
|
| 1427 |
+
zs : list-like
|
| 1428 |
+
list of measurements at each time step. Missing measurements must be
|
| 1429 |
+
represented by None.
|
| 1430 |
+
Fs : list-like
|
| 1431 |
+
list of values to use for the state transition matrix matrix.
|
| 1432 |
+
Qs : list-like
|
| 1433 |
+
list of values to use for the process error
|
| 1434 |
+
covariance.
|
| 1435 |
+
Hs : list-like
|
| 1436 |
+
list of values to use for the measurement matrix.
|
| 1437 |
+
Rs : list-like
|
| 1438 |
+
list of values to use for the measurement error
|
| 1439 |
+
covariance.
|
| 1440 |
+
Bs : list-like, optional
|
| 1441 |
+
list of values to use for the control transition matrix;
|
| 1442 |
+
a value of None in any position will cause the filter
|
| 1443 |
+
to use `self.B` for that time step.
|
| 1444 |
+
us : list-like, optional
|
| 1445 |
+
list of values to use for the control input vector;
|
| 1446 |
+
a value of None in any position will cause the filter to use
|
| 1447 |
+
0 for that time step.
|
| 1448 |
+
update_first : bool, optional
|
| 1449 |
+
controls whether the order of operations is update followed by
|
| 1450 |
+
predict, or predict followed by update. Default is predict->update.
|
| 1451 |
+
saver : filterpy.common.Saver, optional
|
| 1452 |
+
filterpy.common.Saver object. If provided, saver.save() will be
|
| 1453 |
+
called after every epoch
|
| 1454 |
+
Returns
|
| 1455 |
+
-------
|
| 1456 |
+
means : np.array((n,dim_x,1))
|
| 1457 |
+
array of the state for each time step after the update. Each entry
|
| 1458 |
+
is an np.array. In other words `means[k,:]` is the state at step
|
| 1459 |
+
`k`.
|
| 1460 |
+
covariance : np.array((n,dim_x,dim_x))
|
| 1461 |
+
array of the covariances for each time step after the update.
|
| 1462 |
+
In other words `covariance[k,:,:]` is the covariance at step `k`.
|
| 1463 |
+
means_predictions : np.array((n,dim_x,1))
|
| 1464 |
+
array of the state for each time step after the predictions. Each
|
| 1465 |
+
entry is an np.array. In other words `means[k,:]` is the state at
|
| 1466 |
+
step `k`.
|
| 1467 |
+
covariance_predictions : np.array((n,dim_x,dim_x))
|
| 1468 |
+
array of the covariances for each time step after the prediction.
|
| 1469 |
+
In other words `covariance[k,:,:]` is the covariance at step `k`.
|
| 1470 |
+
Examples
|
| 1471 |
+
--------
|
| 1472 |
+
.. code-block:: Python
|
| 1473 |
+
zs = [t + random.randn()*4 for t in range (40)]
|
| 1474 |
+
Fs = [kf.F for t in range (40)]
|
| 1475 |
+
Hs = [kf.H for t in range (40)]
|
| 1476 |
+
(mu, cov, _, _) = kf.batch_filter(zs, Rs=R_list, Fs=Fs, Hs=Hs, Qs=None,
|
| 1477 |
+
Bs=None, us=None, update_first=False)
|
| 1478 |
+
(xs, Ps, Ks, Pps) = kf.rts_smoother(mu, cov, Fs=Fs, Qs=None)
|
| 1479 |
+
"""
|
| 1480 |
+
|
| 1481 |
+
n = np.size(zs, 0)
|
| 1482 |
+
dim_x = x.shape[0]
|
| 1483 |
+
|
| 1484 |
+
# mean estimates from Kalman Filter
|
| 1485 |
+
if x.ndim == 1:
|
| 1486 |
+
means = zeros((n, dim_x))
|
| 1487 |
+
means_p = zeros((n, dim_x))
|
| 1488 |
+
else:
|
| 1489 |
+
means = zeros((n, dim_x, 1))
|
| 1490 |
+
means_p = zeros((n, dim_x, 1))
|
| 1491 |
+
|
| 1492 |
+
# state covariances from Kalman Filter
|
| 1493 |
+
covariances = zeros((n, dim_x, dim_x))
|
| 1494 |
+
covariances_p = zeros((n, dim_x, dim_x))
|
| 1495 |
+
|
| 1496 |
+
if us is None:
|
| 1497 |
+
us = [0.] * n
|
| 1498 |
+
Bs = [0.] * n
|
| 1499 |
+
|
| 1500 |
+
if update_first:
|
| 1501 |
+
for i, (z, F, Q, H, R, B, u) in enumerate(zip(zs, Fs, Qs, Hs, Rs, Bs, us)):
|
| 1502 |
+
|
| 1503 |
+
x, P = update(x, P, z, R=R, H=H)
|
| 1504 |
+
means[i, :] = x
|
| 1505 |
+
covariances[i, :, :] = P
|
| 1506 |
+
|
| 1507 |
+
x, P = predict(x, P, u=u, B=B, F=F, Q=Q)
|
| 1508 |
+
means_p[i, :] = x
|
| 1509 |
+
covariances_p[i, :, :] = P
|
| 1510 |
+
if saver is not None:
|
| 1511 |
+
saver.save()
|
| 1512 |
+
else:
|
| 1513 |
+
for i, (z, F, Q, H, R, B, u) in enumerate(zip(zs, Fs, Qs, Hs, Rs, Bs, us)):
|
| 1514 |
+
|
| 1515 |
+
x, P = predict(x, P, u=u, B=B, F=F, Q=Q)
|
| 1516 |
+
means_p[i, :] = x
|
| 1517 |
+
covariances_p[i, :, :] = P
|
| 1518 |
+
|
| 1519 |
+
x, P = update(x, P, z, R=R, H=H)
|
| 1520 |
+
means[i, :] = x
|
| 1521 |
+
covariances[i, :, :] = P
|
| 1522 |
+
if saver is not None:
|
| 1523 |
+
saver.save()
|
| 1524 |
+
|
| 1525 |
+
return (means, covariances, means_p, covariances_p)
|
| 1526 |
+
|
| 1527 |
+
|
| 1528 |
+
|
| 1529 |
+
def rts_smoother(Xs, Ps, Fs, Qs):
|
| 1530 |
+
"""
|
| 1531 |
+
Runs the Rauch-Tung-Striebel Kalman smoother on a set of
|
| 1532 |
+
means and covariances computed by a Kalman filter. The usual input
|
| 1533 |
+
would come from the output of `KalmanFilter.batch_filter()`.
|
| 1534 |
+
Parameters
|
| 1535 |
+
----------
|
| 1536 |
+
Xs : numpy.array
|
| 1537 |
+
array of the means (state variable x) of the output of a Kalman
|
| 1538 |
+
filter.
|
| 1539 |
+
Ps : numpy.array
|
| 1540 |
+
array of the covariances of the output of a kalman filter.
|
| 1541 |
+
Fs : list-like collection of numpy.array
|
| 1542 |
+
State transition matrix of the Kalman filter at each time step.
|
| 1543 |
+
Qs : list-like collection of numpy.array, optional
|
| 1544 |
+
Process noise of the Kalman filter at each time step.
|
| 1545 |
+
Returns
|
| 1546 |
+
-------
|
| 1547 |
+
x : numpy.ndarray
|
| 1548 |
+
smoothed means
|
| 1549 |
+
P : numpy.ndarray
|
| 1550 |
+
smoothed state covariances
|
| 1551 |
+
K : numpy.ndarray
|
| 1552 |
+
smoother gain at each step
|
| 1553 |
+
pP : numpy.ndarray
|
| 1554 |
+
predicted state covariances
|
| 1555 |
+
Examples
|
| 1556 |
+
--------
|
| 1557 |
+
.. code-block:: Python
|
| 1558 |
+
zs = [t + random.randn()*4 for t in range (40)]
|
| 1559 |
+
(mu, cov, _, _) = kalman.batch_filter(zs)
|
| 1560 |
+
(x, P, K, pP) = rts_smoother(mu, cov, kf.F, kf.Q)
|
| 1561 |
+
"""
|
| 1562 |
+
|
| 1563 |
+
if len(Xs) != len(Ps):
|
| 1564 |
+
raise ValueError('length of Xs and Ps must be the same')
|
| 1565 |
+
|
| 1566 |
+
n = Xs.shape[0]
|
| 1567 |
+
dim_x = Xs.shape[1]
|
| 1568 |
+
|
| 1569 |
+
# smoother gain
|
| 1570 |
+
K = zeros((n, dim_x, dim_x))
|
| 1571 |
+
x, P, pP = Xs.copy(), Ps.copy(), Ps.copy()
|
| 1572 |
+
|
| 1573 |
+
for k in range(n-2, -1, -1):
|
| 1574 |
+
pP[k] = dot(dot(Fs[k], P[k]), Fs[k].T) + Qs[k]
|
| 1575 |
+
|
| 1576 |
+
#pylint: disable=bad-whitespace
|
| 1577 |
+
K[k] = dot(dot(P[k], Fs[k].T), linalg.inv(pP[k]))
|
| 1578 |
+
x[k] += dot(K[k], x[k+1] - dot(Fs[k], x[k]))
|
| 1579 |
+
P[k] += dot(dot(K[k], P[k+1] - pP[k]), K[k].T)
|
| 1580 |
+
|
| 1581 |
+
return (x, P, K, pP)
|
trackers/ocsort/ocsort.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This script is adopted from the SORT script by Alex Bewley alex@bewley.ai
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from .association import *
|
| 8 |
+
from .cmc import GMC
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def k_previous_obs(observations, cur_age, k):
|
| 12 |
+
if len(observations) == 0:
|
| 13 |
+
return [-1, -1, -1, -1, -1]
|
| 14 |
+
for i in range(k):
|
| 15 |
+
dt = k - i
|
| 16 |
+
if cur_age - dt in observations:
|
| 17 |
+
return observations[cur_age - dt]
|
| 18 |
+
max_age = max(observations.keys())
|
| 19 |
+
return observations[max_age]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def convert_bbox_to_z(bbox):
|
| 23 |
+
"""
|
| 24 |
+
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
|
| 25 |
+
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
|
| 26 |
+
the aspect ratio
|
| 27 |
+
"""
|
| 28 |
+
w = bbox[2] - bbox[0]
|
| 29 |
+
h = bbox[3] - bbox[1]
|
| 30 |
+
x = bbox[0] + w / 2.
|
| 31 |
+
y = bbox[1] + h / 2.
|
| 32 |
+
s = w * h # scale is just area
|
| 33 |
+
r = w / float(h + 1e-6)
|
| 34 |
+
return np.array([x, y, s, r]).reshape((4, 1))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def convert_x_to_bbox(x, score=None):
|
| 38 |
+
"""
|
| 39 |
+
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
|
| 40 |
+
[x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
|
| 41 |
+
"""
|
| 42 |
+
w = np.sqrt(x[2] * x[3])
|
| 43 |
+
h = x[2] / w
|
| 44 |
+
if (score == None):
|
| 45 |
+
return np.array([x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2.]).reshape((1, 4))
|
| 46 |
+
else:
|
| 47 |
+
return np.array([x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2., score]).reshape((1, 5))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def speed_direction(bbox1, bbox2):
|
| 51 |
+
cx1, cy1 = (bbox1[0] + bbox1[2]) / 2.0, (bbox1[1] + bbox1[3]) / 2.0
|
| 52 |
+
cx2, cy2 = (bbox2[0] + bbox2[2]) / 2.0, (bbox2[1] + bbox2[3]) / 2.0
|
| 53 |
+
speed = np.array([cy2 - cy1, cx2 - cx1])
|
| 54 |
+
norm = np.sqrt((cy2 - cy1) ** 2 + (cx2 - cx1) ** 2) + 1e-6
|
| 55 |
+
return speed / norm
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class KalmanBoxTracker(object):
|
| 59 |
+
"""
|
| 60 |
+
This class represents the internal state of individual tracked objects observed as bbox.
|
| 61 |
+
"""
|
| 62 |
+
count = 0
|
| 63 |
+
|
| 64 |
+
def __init__(self, bbox, delta_t=3, orig=False, use_gmc=True):
|
| 65 |
+
"""
|
| 66 |
+
Initialises a tracker using initial bounding box.
|
| 67 |
+
|
| 68 |
+
"""
|
| 69 |
+
# define constant velocity model
|
| 70 |
+
if not orig:
|
| 71 |
+
from .kalmanfilter import KalmanFilterNew as KalmanFilter
|
| 72 |
+
self.kf = KalmanFilter(dim_x=7, dim_z=4)
|
| 73 |
+
else:
|
| 74 |
+
from filterpy.kalman import KalmanFilter
|
| 75 |
+
self.kf = KalmanFilter(dim_x=7, dim_z=4)
|
| 76 |
+
self.kf.F = np.array([[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 1], [
|
| 77 |
+
0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1]])
|
| 78 |
+
self.kf.H = np.array([[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0],
|
| 79 |
+
[0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]])
|
| 80 |
+
|
| 81 |
+
self.kf.R[2:, 2:] *= 10.
|
| 82 |
+
self.kf.P[4:, 4:] *= 1000. # give high uncertainty to the unobservable initial velocities
|
| 83 |
+
self.kf.P *= 10.
|
| 84 |
+
self.kf.Q[-1, -1] *= 0.01
|
| 85 |
+
self.kf.Q[4:, 4:] *= 0.01
|
| 86 |
+
|
| 87 |
+
self.kf.x[:4] = convert_bbox_to_z(bbox)
|
| 88 |
+
self.time_since_update = 0
|
| 89 |
+
self.id = KalmanBoxTracker.count
|
| 90 |
+
KalmanBoxTracker.count += 1
|
| 91 |
+
self.history = []
|
| 92 |
+
self.hits = 0
|
| 93 |
+
self.hit_streak = 0
|
| 94 |
+
self.age = 0
|
| 95 |
+
"""
|
| 96 |
+
NOTE: [-1,-1,-1,-1,-1] is a compromising placeholder for non-observation status, the same for the return of
|
| 97 |
+
function k_previous_obs. It is ugly and I do not like it. But to support generate observation array in a
|
| 98 |
+
fast and unified way, which you would see below k_observations = np.array([k_previous_obs(...]]), let's bear it for now.
|
| 99 |
+
"""
|
| 100 |
+
self.last_observation = np.array([-1, -1, -1, -1, -1]) # placeholder
|
| 101 |
+
self.observations = dict()
|
| 102 |
+
self.history_observations = []
|
| 103 |
+
self.velocity = None
|
| 104 |
+
self.delta_t = delta_t
|
| 105 |
+
self.use_gmc = use_gmc
|
| 106 |
+
|
| 107 |
+
def update(self, bbox):
|
| 108 |
+
"""
|
| 109 |
+
Updates the state vector with observed bbox.
|
| 110 |
+
"""
|
| 111 |
+
if bbox is not None:
|
| 112 |
+
if self.last_observation.sum() >= 0: # no previous observation
|
| 113 |
+
previous_box = None
|
| 114 |
+
for i in range(self.delta_t):
|
| 115 |
+
dt = self.delta_t - i
|
| 116 |
+
if self.age - dt in self.observations:
|
| 117 |
+
previous_box = self.observations[self.age - dt]
|
| 118 |
+
break
|
| 119 |
+
if previous_box is None:
|
| 120 |
+
previous_box = self.last_observation
|
| 121 |
+
"""
|
| 122 |
+
Estimate the track speed direction with observations \Delta t steps away
|
| 123 |
+
"""
|
| 124 |
+
self.velocity = speed_direction(previous_box, bbox)
|
| 125 |
+
|
| 126 |
+
"""
|
| 127 |
+
Insert new observations. This is a ugly way to maintain both self.observations
|
| 128 |
+
and self.history_observations. Bear it for the moment.
|
| 129 |
+
"""
|
| 130 |
+
self.last_observation = bbox
|
| 131 |
+
self.observations[self.age] = bbox
|
| 132 |
+
self.history_observations.append(bbox)
|
| 133 |
+
|
| 134 |
+
self.time_since_update = 0
|
| 135 |
+
self.history = []
|
| 136 |
+
self.hits += 1
|
| 137 |
+
self.hit_streak += 1
|
| 138 |
+
self.kf.update(convert_bbox_to_z(bbox))
|
| 139 |
+
else:
|
| 140 |
+
self.kf.update(bbox)
|
| 141 |
+
|
| 142 |
+
def predict(self, H=np.eye(2, 3)):
|
| 143 |
+
"""
|
| 144 |
+
Advances the state vector and returns the predicted bounding box estimate.
|
| 145 |
+
"""
|
| 146 |
+
if ((self.kf.x[6] + self.kf.x[2]) <= 0):
|
| 147 |
+
self.kf.x[6] *= 0.0
|
| 148 |
+
|
| 149 |
+
self.kf.predict()
|
| 150 |
+
if self.use_gmc:
|
| 151 |
+
##### Apply Camera Motion Compensation
|
| 152 |
+
state_org = self.kf.x
|
| 153 |
+
P = self.kf.P
|
| 154 |
+
a11, a12, tx = H[0]
|
| 155 |
+
a21, a22, ty = H[1]
|
| 156 |
+
# Construct the transformation matrix J (7x7)
|
| 157 |
+
J = np.array([
|
| 158 |
+
[a11, a12, 0, 0, 0, 0, 0], # x
|
| 159 |
+
[a21, a22, 0, 0, 0, 0, 0], # y
|
| 160 |
+
[0, 0, abs(a11 * a22 - a21 * a12), 0, 0, 0, 0], # s
|
| 161 |
+
[0, 0, 0, 1, 0, 0, 0], # r
|
| 162 |
+
[0, 0, 0, 0, a11, a12, 0], # dx
|
| 163 |
+
[0, 0, 0, 0, a21, a22, 0], # dy
|
| 164 |
+
[0, 0, 0, 0, 0, 0, abs(a11 * a22 - a21 * a12)] # ds
|
| 165 |
+
])
|
| 166 |
+
self.kf.x = np.dot(J, state_org) + np.array([[tx], [ty], [0], [0], [0], [0], [0]]) # -state
|
| 167 |
+
self.kf.P = J @ P @ J.T
|
| 168 |
+
#####
|
| 169 |
+
self.age += 1
|
| 170 |
+
if (self.time_since_update > 0):
|
| 171 |
+
self.hit_streak = 0
|
| 172 |
+
self.time_since_update += 1
|
| 173 |
+
self.history.append(convert_x_to_bbox(self.kf.x))
|
| 174 |
+
return self.history[-1]
|
| 175 |
+
|
| 176 |
+
def get_state(self):
|
| 177 |
+
"""
|
| 178 |
+
Returns the current bounding box estimate.
|
| 179 |
+
"""
|
| 180 |
+
return convert_x_to_bbox(self.kf.x)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
"""
|
| 184 |
+
We support multiple ways for association cost calculation, by default
|
| 185 |
+
we use IoU. GIoU may have better performance in some situations. We note
|
| 186 |
+
that we hardly normalize the cost by all methods to (0,1) which may not be
|
| 187 |
+
the best practice.
|
| 188 |
+
"""
|
| 189 |
+
ASSO_FUNCS = {"iou": iou_batch,
|
| 190 |
+
"giou": giou_batch,
|
| 191 |
+
"ciou": ciou_batch,
|
| 192 |
+
"diou": diou_batch,
|
| 193 |
+
"ct_dist": ct_dist}
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class Track:
|
| 197 |
+
def __init__(self, track_id, tlrb, score):
|
| 198 |
+
self.track_id = track_id
|
| 199 |
+
self.tlwh = [tlrb[0], tlrb[1], tlrb[2] - tlrb[0], tlrb[3] - tlrb[1]]
|
| 200 |
+
self.score = score
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class OCSort(object):
|
| 204 |
+
def __init__(self, det_thresh, max_age=30, min_hits=3,
|
| 205 |
+
iou_threshold=0.3, delta_t=3, asso_func="iou", inertia=0.2, use_byte=True, use_gmc=True):
|
| 206 |
+
"""
|
| 207 |
+
Sets key parameters for SORT
|
| 208 |
+
"""
|
| 209 |
+
self.max_age = max_age
|
| 210 |
+
self.min_hits = min_hits
|
| 211 |
+
self.iou_threshold = iou_threshold
|
| 212 |
+
self.trackers = []
|
| 213 |
+
self.frame_count = 0
|
| 214 |
+
self.det_thresh = det_thresh
|
| 215 |
+
self.delta_t = delta_t
|
| 216 |
+
self.asso_func = ASSO_FUNCS[asso_func]
|
| 217 |
+
self.inertia = inertia
|
| 218 |
+
self.use_byte = use_byte
|
| 219 |
+
KalmanBoxTracker.count = 0
|
| 220 |
+
self.gmc = GMC(method="cmc", verbose=None)
|
| 221 |
+
self.use_gmc = use_gmc
|
| 222 |
+
|
| 223 |
+
def update(self, fdets, frame):
|
| 224 |
+
"""
|
| 225 |
+
Params:
|
| 226 |
+
dets - a numpy array of detections in the format [[x1,y1,x2,y2,score],[x1,y1,x2,y2,score],...]
|
| 227 |
+
Requires: this method must be called once for each frame even with empty detections (use np.empty((0, 5)) for frames without detections).
|
| 228 |
+
Returns the a similar array, where the last column is the object ID.
|
| 229 |
+
NOTE: The number of objects returned may differ from the number of detections provided.
|
| 230 |
+
"""
|
| 231 |
+
#####
|
| 232 |
+
bboxes, scores = fdets[:, 0:4], fdets[:, 4]
|
| 233 |
+
dets = np.concatenate((bboxes, np.expand_dims(scores, axis=-1)), axis=1)
|
| 234 |
+
inds_low = scores > 0.1
|
| 235 |
+
if len(scores) > 1:
|
| 236 |
+
det_thresh = scores[np.argmin(np.diff(scores))]
|
| 237 |
+
if det_thresh < self.det_thresh:
|
| 238 |
+
det_thresh = self.det_thresh
|
| 239 |
+
else:
|
| 240 |
+
det_thresh = self.det_thresh
|
| 241 |
+
# det_thresh = 0.3
|
| 242 |
+
H = None
|
| 243 |
+
if self.use_gmc:
|
| 244 |
+
H = self.gmc.applyCMC(frame)
|
| 245 |
+
inds_high = scores <= det_thresh
|
| 246 |
+
inds_second = np.logical_and(inds_low, inds_high) # self.det_thresh > score > 0.1, for second matching
|
| 247 |
+
dets_second = dets[inds_second] # detections for second matching
|
| 248 |
+
remain_inds = scores > det_thresh
|
| 249 |
+
dets = dets[remain_inds]
|
| 250 |
+
|
| 251 |
+
# get predicted locations from existing trackers.
|
| 252 |
+
trks = np.zeros((len(self.trackers), 5))
|
| 253 |
+
to_del = []
|
| 254 |
+
ret = []
|
| 255 |
+
for t, trk in enumerate(trks):
|
| 256 |
+
pos = self.trackers[t].predict(H)[0]
|
| 257 |
+
trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]
|
| 258 |
+
if np.any(np.isnan(pos)):
|
| 259 |
+
to_del.append(t)
|
| 260 |
+
|
| 261 |
+
trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
|
| 262 |
+
for t in reversed(to_del):
|
| 263 |
+
self.trackers.pop(t)
|
| 264 |
+
|
| 265 |
+
velocities = np.array(
|
| 266 |
+
[trk.velocity if trk.velocity is not None else np.array((0, 0)) for trk in self.trackers])
|
| 267 |
+
last_boxes = np.array([trk.last_observation for trk in self.trackers])
|
| 268 |
+
k_observations = np.array(
|
| 269 |
+
[k_previous_obs(trk.observations, trk.age, self.delta_t) for trk in self.trackers])
|
| 270 |
+
|
| 271 |
+
"""
|
| 272 |
+
First round of association
|
| 273 |
+
"""
|
| 274 |
+
matched, unmatched_dets, unmatched_trks = associate(
|
| 275 |
+
self.asso_func, dets, trks, self.iou_threshold, velocities, k_observations, self.inertia)
|
| 276 |
+
for m in matched:
|
| 277 |
+
self.trackers[m[1]].update(dets[m[0], :])
|
| 278 |
+
|
| 279 |
+
"""
|
| 280 |
+
Second round of associaton by OCR
|
| 281 |
+
"""
|
| 282 |
+
# BYTE association
|
| 283 |
+
if self.use_byte and len(dets_second) > 0 and unmatched_trks.shape[0] > 0:
|
| 284 |
+
u_trks = trks[unmatched_trks]
|
| 285 |
+
iou_left = self.asso_func(dets_second, u_trks) # iou between low score detections and unmatched tracks
|
| 286 |
+
iou_left = np.array(iou_left)
|
| 287 |
+
if iou_left.max() > self.iou_threshold:
|
| 288 |
+
"""
|
| 289 |
+
NOTE: by using a lower threshold, e.g., self.iou_threshold - 0.1, you may
|
| 290 |
+
get a higher performance especially on MOT17/MOT20 datasets. But we keep it
|
| 291 |
+
uniform here for simplicity
|
| 292 |
+
"""
|
| 293 |
+
matched_indices = linear_assignment(-iou_left)
|
| 294 |
+
to_remove_trk_indices = []
|
| 295 |
+
for m in matched_indices:
|
| 296 |
+
det_ind, trk_ind = m[0], unmatched_trks[m[1]]
|
| 297 |
+
if iou_left[m[0], m[1]] < self.iou_threshold:
|
| 298 |
+
continue
|
| 299 |
+
self.trackers[trk_ind].update(dets_second[det_ind, :])
|
| 300 |
+
to_remove_trk_indices.append(trk_ind)
|
| 301 |
+
unmatched_trks = np.setdiff1d(unmatched_trks, np.array(to_remove_trk_indices))
|
| 302 |
+
|
| 303 |
+
if unmatched_dets.shape[0] > 0 and unmatched_trks.shape[0] > 0:
|
| 304 |
+
left_dets = dets[unmatched_dets]
|
| 305 |
+
left_trks = last_boxes[unmatched_trks]
|
| 306 |
+
iou_left = self.asso_func(left_dets, left_trks)
|
| 307 |
+
iou_left = np.array(iou_left)
|
| 308 |
+
if iou_left.max() > self.iou_threshold:
|
| 309 |
+
"""
|
| 310 |
+
NOTE: by using a lower threshold, e.g., self.iou_threshold - 0.1, you may
|
| 311 |
+
get a higher performance especially on MOT17/MOT20 datasets. But we keep it
|
| 312 |
+
uniform here for simplicity
|
| 313 |
+
"""
|
| 314 |
+
rematched_indices = linear_assignment(-iou_left)
|
| 315 |
+
to_remove_det_indices = []
|
| 316 |
+
to_remove_trk_indices = []
|
| 317 |
+
for m in rematched_indices:
|
| 318 |
+
det_ind, trk_ind = unmatched_dets[m[0]], unmatched_trks[m[1]]
|
| 319 |
+
if iou_left[m[0], m[1]] < self.iou_threshold:
|
| 320 |
+
continue
|
| 321 |
+
self.trackers[trk_ind].update(dets[det_ind, :])
|
| 322 |
+
to_remove_det_indices.append(det_ind)
|
| 323 |
+
to_remove_trk_indices.append(trk_ind)
|
| 324 |
+
unmatched_dets = np.setdiff1d(unmatched_dets, np.array(to_remove_det_indices))
|
| 325 |
+
unmatched_trks = np.setdiff1d(unmatched_trks, np.array(to_remove_trk_indices))
|
| 326 |
+
|
| 327 |
+
for m in unmatched_trks:
|
| 328 |
+
self.trackers[m].update(None)
|
| 329 |
+
|
| 330 |
+
# create and initialise new trackers for unmatched detections
|
| 331 |
+
for i in unmatched_dets:
|
| 332 |
+
trk = KalmanBoxTracker(dets[i, :], delta_t=self.delta_t, use_gmc=self.use_gmc)
|
| 333 |
+
self.trackers.append(trk)
|
| 334 |
+
i = len(self.trackers)
|
| 335 |
+
for trk in reversed(self.trackers):
|
| 336 |
+
if trk.last_observation.sum() < 0:
|
| 337 |
+
d = trk.get_state()[0]
|
| 338 |
+
else:
|
| 339 |
+
"""
|
| 340 |
+
this is optional to use the recent observation or the kalman filter prediction,
|
| 341 |
+
we didn't notice significant difference here
|
| 342 |
+
"""
|
| 343 |
+
d = trk.last_observation[:4]
|
| 344 |
+
if (trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):
|
| 345 |
+
# +1 as MOT benchmark requires positive
|
| 346 |
+
ret.append(Track(trk.id + 1, d, 1))
|
| 347 |
+
i -= 1
|
| 348 |
+
# remove dead tracklet
|
| 349 |
+
if (trk.time_since_update > self.max_age):
|
| 350 |
+
self.trackers.pop(i)
|
| 351 |
+
return ret
|
trackers/sort/__pycache__/sort.cpython-37.pyc
ADDED
|
Binary file (8.45 kB). View file
|
|
|
trackers/sort/__pycache__/sort.cpython-38.pyc
ADDED
|
Binary file (8.7 kB). View file
|
|
|
trackers/sort/sort.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SORT: A Simple, Online and Realtime Tracker
|
| 3 |
+
Copyright (C) 2016-2020 Alex Bewley alex@bewley.ai
|
| 4 |
+
This program is free software: you can redistribute it and/or modify
|
| 5 |
+
it under the terms of the GNU General Public License as published by
|
| 6 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 7 |
+
(at your option) any later version.
|
| 8 |
+
This program is distributed in the hope that it will be useful,
|
| 9 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 10 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 11 |
+
GNU General Public License for more details.
|
| 12 |
+
You should have received a copy of the GNU General Public License
|
| 13 |
+
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import print_function
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from filterpy.kalman import KalmanFilter
|
| 21 |
+
|
| 22 |
+
np.random.seed(0)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def linear_assignment(cost_matrix):
|
| 26 |
+
try:
|
| 27 |
+
import lap
|
| 28 |
+
_, x, y = lap.lapjv(cost_matrix, extend_cost=True)
|
| 29 |
+
return np.array([[y[i], i] for i in x if i >= 0]) #
|
| 30 |
+
except ImportError:
|
| 31 |
+
from scipy.optimize import linear_sum_assignment
|
| 32 |
+
x, y = linear_sum_assignment(cost_matrix)
|
| 33 |
+
return np.array(list(zip(x, y)))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def iou_batch(bb_test, bb_gt):
|
| 37 |
+
"""
|
| 38 |
+
From SORT: Computes IOU between two bboxes in the form [x1,y1,x2,y2]
|
| 39 |
+
"""
|
| 40 |
+
bb_gt = np.expand_dims(bb_gt, 0)
|
| 41 |
+
bb_test = np.expand_dims(bb_test, 1)
|
| 42 |
+
|
| 43 |
+
xx1 = np.maximum(bb_test[..., 0], bb_gt[..., 0])
|
| 44 |
+
yy1 = np.maximum(bb_test[..., 1], bb_gt[..., 1])
|
| 45 |
+
xx2 = np.minimum(bb_test[..., 2], bb_gt[..., 2])
|
| 46 |
+
yy2 = np.minimum(bb_test[..., 3], bb_gt[..., 3])
|
| 47 |
+
w = np.maximum(0., xx2 - xx1)
|
| 48 |
+
h = np.maximum(0., yy2 - yy1)
|
| 49 |
+
wh = w * h
|
| 50 |
+
o = wh / ((bb_test[..., 2] - bb_test[..., 0]) * (bb_test[..., 3] - bb_test[..., 1])
|
| 51 |
+
+ (bb_gt[..., 2] - bb_gt[..., 0]) * (bb_gt[..., 3] - bb_gt[..., 1]) - wh)
|
| 52 |
+
return (o)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def convert_bbox_to_z(bbox):
|
| 56 |
+
"""
|
| 57 |
+
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
|
| 58 |
+
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
|
| 59 |
+
the aspect ratio
|
| 60 |
+
"""
|
| 61 |
+
w = bbox[2] - bbox[0]
|
| 62 |
+
h = bbox[3] - bbox[1]
|
| 63 |
+
x = bbox[0] + w / 2.
|
| 64 |
+
y = bbox[1] + h / 2.
|
| 65 |
+
s = w * h # scale is just area
|
| 66 |
+
r = w / float(h)
|
| 67 |
+
return np.array([x, y, s, r]).reshape((4, 1))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def convert_x_to_bbox(x, score=None):
|
| 71 |
+
"""
|
| 72 |
+
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
|
| 73 |
+
[x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
|
| 74 |
+
"""
|
| 75 |
+
w = np.sqrt(x[2] * x[3])
|
| 76 |
+
h = x[2] / w
|
| 77 |
+
if (score == None):
|
| 78 |
+
return np.array([x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2.]).reshape((1, 4))
|
| 79 |
+
else:
|
| 80 |
+
return np.array([x[0] - w / 2., x[1] - h / 2., x[0] + w / 2., x[1] + h / 2., score]).reshape((1, 5))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class KalmanBoxTracker(object):
|
| 84 |
+
"""
|
| 85 |
+
This class represents the internal state of individual tracked objects observed as bbox.
|
| 86 |
+
"""
|
| 87 |
+
count = 0
|
| 88 |
+
|
| 89 |
+
def __init__(self, bbox):
|
| 90 |
+
"""
|
| 91 |
+
Initialises a tracker using initial bounding box.
|
| 92 |
+
"""
|
| 93 |
+
# define constant velocity model
|
| 94 |
+
self.kf = KalmanFilter(dim_x=7, dim_z=4)
|
| 95 |
+
self.kf.F = np.array(
|
| 96 |
+
[[1, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0],
|
| 97 |
+
[0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1]])
|
| 98 |
+
self.kf.H = np.array(
|
| 99 |
+
[[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]])
|
| 100 |
+
|
| 101 |
+
self.kf.R[2:, 2:] *= 10.
|
| 102 |
+
self.kf.P[4:, 4:] *= 1000. # give high uncertainty to the unobservable initial velocities
|
| 103 |
+
self.kf.P *= 10.
|
| 104 |
+
self.kf.Q[-1, -1] *= 0.01
|
| 105 |
+
self.kf.Q[4:, 4:] *= 0.01
|
| 106 |
+
|
| 107 |
+
self.kf.x[:4] = convert_bbox_to_z(bbox)
|
| 108 |
+
self.time_since_update = 0
|
| 109 |
+
self.id = KalmanBoxTracker.count
|
| 110 |
+
KalmanBoxTracker.count += 1
|
| 111 |
+
self.history = []
|
| 112 |
+
self.hits = 0
|
| 113 |
+
self.hit_streak = 0
|
| 114 |
+
self.age = 0
|
| 115 |
+
|
| 116 |
+
def update(self, bbox):
|
| 117 |
+
"""
|
| 118 |
+
Updates the state vector with observed bbox.
|
| 119 |
+
"""
|
| 120 |
+
self.time_since_update = 0
|
| 121 |
+
self.history = []
|
| 122 |
+
self.hits += 1
|
| 123 |
+
self.hit_streak += 1
|
| 124 |
+
self.kf.update(convert_bbox_to_z(bbox))
|
| 125 |
+
|
| 126 |
+
def predict(self):
|
| 127 |
+
"""
|
| 128 |
+
Advances the state vector and returns the predicted bounding box estimate.
|
| 129 |
+
"""
|
| 130 |
+
if ((self.kf.x[6] + self.kf.x[2]) <= 0):
|
| 131 |
+
self.kf.x[6] *= 0.0
|
| 132 |
+
self.kf.predict()
|
| 133 |
+
self.age += 1
|
| 134 |
+
if (self.time_since_update > 0):
|
| 135 |
+
self.hit_streak = 0
|
| 136 |
+
self.time_since_update += 1
|
| 137 |
+
self.history.append(convert_x_to_bbox(self.kf.x))
|
| 138 |
+
return self.history[-1]
|
| 139 |
+
|
| 140 |
+
def get_state(self):
|
| 141 |
+
"""
|
| 142 |
+
Returns the current bounding box estimate.
|
| 143 |
+
"""
|
| 144 |
+
return convert_x_to_bbox(self.kf.x)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def associate_detections_to_trackers(detections, trackers, iou_threshold=0.3):
|
| 148 |
+
"""
|
| 149 |
+
Assigns detections to tracked object (both represented as bounding boxes)
|
| 150 |
+
Returns 3 lists of matches, unmatched_detections and unmatched_trackers
|
| 151 |
+
"""
|
| 152 |
+
if (len(trackers) == 0):
|
| 153 |
+
return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int)
|
| 154 |
+
|
| 155 |
+
iou_matrix = iou_batch(detections, trackers)
|
| 156 |
+
|
| 157 |
+
if min(iou_matrix.shape) > 0:
|
| 158 |
+
a = (iou_matrix > iou_threshold).astype(np.int32)
|
| 159 |
+
if a.sum(1).max() == 1 and a.sum(0).max() == 1:
|
| 160 |
+
matched_indices = np.stack(np.where(a), axis=1)
|
| 161 |
+
else:
|
| 162 |
+
matched_indices = linear_assignment(-iou_matrix)
|
| 163 |
+
else:
|
| 164 |
+
matched_indices = np.empty(shape=(0, 2))
|
| 165 |
+
|
| 166 |
+
unmatched_detections = []
|
| 167 |
+
for d, det in enumerate(detections):
|
| 168 |
+
if (d not in matched_indices[:, 0]):
|
| 169 |
+
unmatched_detections.append(d)
|
| 170 |
+
unmatched_trackers = []
|
| 171 |
+
for t, trk in enumerate(trackers):
|
| 172 |
+
if (t not in matched_indices[:, 1]):
|
| 173 |
+
unmatched_trackers.append(t)
|
| 174 |
+
|
| 175 |
+
# filter out matched with low IOU
|
| 176 |
+
matches = []
|
| 177 |
+
for m in matched_indices:
|
| 178 |
+
if (iou_matrix[m[0], m[1]] < iou_threshold):
|
| 179 |
+
unmatched_detections.append(m[0])
|
| 180 |
+
unmatched_trackers.append(m[1])
|
| 181 |
+
else:
|
| 182 |
+
matches.append(m.reshape(1, 2))
|
| 183 |
+
if (len(matches) == 0):
|
| 184 |
+
matches = np.empty((0, 2), dtype=int)
|
| 185 |
+
else:
|
| 186 |
+
matches = np.concatenate(matches, axis=0)
|
| 187 |
+
|
| 188 |
+
return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class Track:
|
| 192 |
+
def __init__(self, track_id, tlrb, score):
|
| 193 |
+
self.track_id = track_id
|
| 194 |
+
self.tlwh = [tlrb[0], tlrb[1], tlrb[2] - tlrb[0], tlrb[3] - tlrb[1]]
|
| 195 |
+
self.score = score
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Sort(object):
|
| 199 |
+
def __init__(self, det_thresh, max_age=30, min_hits=3, iou_threshold=0.3):
|
| 200 |
+
"""
|
| 201 |
+
Sets key parameters for SORT
|
| 202 |
+
"""
|
| 203 |
+
self.max_age = max_age
|
| 204 |
+
self.min_hits = min_hits
|
| 205 |
+
self.iou_threshold = iou_threshold
|
| 206 |
+
self.trackers = []
|
| 207 |
+
self.frame_count = 0
|
| 208 |
+
self.det_thresh = det_thresh
|
| 209 |
+
|
| 210 |
+
def update(self, fdets, img): # , img_info, img_size):
|
| 211 |
+
"""
|
| 212 |
+
Params:
|
| 213 |
+
dets - a numpy array of detections in the format [[x1,y1,x2,y2,score],[x1,y1,x2,y2,score],...]
|
| 214 |
+
Requires: this method must be called once for each frame even with empty detections (use np.empty((0, 5)) for frames without detections).
|
| 215 |
+
Returns the a similar array, where the last column is the object ID.
|
| 216 |
+
NOTE: The number of objects returned may differ from the number of detections provided.
|
| 217 |
+
"""
|
| 218 |
+
self.frame_count += 1
|
| 219 |
+
#####
|
| 220 |
+
remain_inds = fdets[:, 4] > self.det_thresh
|
| 221 |
+
dets = fdets[remain_inds, 0:5]
|
| 222 |
+
# get predicted locations from existing trackers.
|
| 223 |
+
trks = np.zeros((len(self.trackers), 5))
|
| 224 |
+
to_del = []
|
| 225 |
+
ret = []
|
| 226 |
+
for t, trk in enumerate(trks):
|
| 227 |
+
pos = self.trackers[t].predict()[0]
|
| 228 |
+
trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]
|
| 229 |
+
if np.any(np.isnan(pos)):
|
| 230 |
+
to_del.append(t)
|
| 231 |
+
trks = np.ma.compress_rows(np.ma.masked_invalid(trks))
|
| 232 |
+
for t in reversed(to_del):
|
| 233 |
+
self.trackers.pop(t)
|
| 234 |
+
matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets, trks, self.iou_threshold)
|
| 235 |
+
|
| 236 |
+
# update matched trackers with assigned detections
|
| 237 |
+
for m in matched:
|
| 238 |
+
self.trackers[m[1]].update(dets[m[0], :])
|
| 239 |
+
|
| 240 |
+
# create and initialise new trackers for unmatched detections
|
| 241 |
+
for i in unmatched_dets:
|
| 242 |
+
trk = KalmanBoxTracker(dets[i, :])
|
| 243 |
+
self.trackers.append(trk)
|
| 244 |
+
i = len(self.trackers)
|
| 245 |
+
for trk in reversed(self.trackers):
|
| 246 |
+
d = trk.get_state()[0]
|
| 247 |
+
if (trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits):
|
| 248 |
+
# ret.append(np.concatenate((d, [trk.id + 1])).reshape(1, -1)) # +1 as MOT benchmark requires positive
|
| 249 |
+
ret.append(Track(trk.id + 1, d, 1))
|
| 250 |
+
i -= 1
|
| 251 |
+
# remove dead tracklet
|
| 252 |
+
if (trk.time_since_update > self.max_age):
|
| 253 |
+
self.trackers.pop(i)
|
| 254 |
+
# if (len(ret) > 0):
|
| 255 |
+
# return np.concatenate(ret)
|
| 256 |
+
return ret # np.empty((0, 5))
|
tracking_utils/__pycache__/evaluation.cpython-38.pyc
ADDED
|
Binary file (3.35 kB). View file
|
|
|
tracking_utils/__pycache__/io.cpython-38.pyc
ADDED
|
Binary file (2.54 kB). View file
|
|
|
tracking_utils/__pycache__/log.cpython-38.pyc
ADDED
|
Binary file (595 Bytes). View file
|
|
|
tracking_utils/evaluation.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import copy
|
| 4 |
+
import motmetrics as mm
|
| 5 |
+
mm.lap.default_solver = 'lap'
|
| 6 |
+
|
| 7 |
+
from tracking_utils.io import read_results, unzip_objs
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Evaluator(object):
|
| 11 |
+
|
| 12 |
+
def __init__(self, data_root, seq_name, data_type):
|
| 13 |
+
self.data_root = data_root
|
| 14 |
+
self.seq_name = seq_name
|
| 15 |
+
self.data_type = data_type
|
| 16 |
+
|
| 17 |
+
self.load_annotations()
|
| 18 |
+
self.reset_accumulator()
|
| 19 |
+
|
| 20 |
+
def load_annotations(self):
|
| 21 |
+
assert self.data_type == 'mot'
|
| 22 |
+
|
| 23 |
+
gt_filename = os.path.join(self.data_root, self.seq_name, 'gt', 'gt.txt')
|
| 24 |
+
self.gt_frame_dict = read_results(gt_filename, self.data_type, is_gt=True)
|
| 25 |
+
self.gt_ignore_frame_dict = read_results(gt_filename, self.data_type, is_ignore=True)
|
| 26 |
+
|
| 27 |
+
def reset_accumulator(self):
|
| 28 |
+
self.acc = mm.MOTAccumulator(auto_id=True)
|
| 29 |
+
|
| 30 |
+
def eval_frame(self, frame_id, trk_tlwhs, trk_ids, rtn_events=False):
|
| 31 |
+
# results
|
| 32 |
+
trk_tlwhs = np.copy(trk_tlwhs)
|
| 33 |
+
trk_ids = np.copy(trk_ids)
|
| 34 |
+
|
| 35 |
+
# gts
|
| 36 |
+
gt_objs = self.gt_frame_dict.get(frame_id, [])
|
| 37 |
+
gt_tlwhs, gt_ids = unzip_objs(gt_objs)[:2]
|
| 38 |
+
|
| 39 |
+
# ignore boxes
|
| 40 |
+
ignore_objs = self.gt_ignore_frame_dict.get(frame_id, [])
|
| 41 |
+
ignore_tlwhs = unzip_objs(ignore_objs)[0]
|
| 42 |
+
|
| 43 |
+
# remove ignored results
|
| 44 |
+
keep = np.ones(len(trk_tlwhs), dtype=bool)
|
| 45 |
+
iou_distance = mm.distances.iou_matrix(ignore_tlwhs, trk_tlwhs, max_iou=0.5)
|
| 46 |
+
if len(iou_distance) > 0:
|
| 47 |
+
match_is, match_js = mm.lap.linear_sum_assignment(iou_distance)
|
| 48 |
+
match_is, match_js = map(lambda a: np.asarray(a, dtype=int), [match_is, match_js])
|
| 49 |
+
match_ious = iou_distance[match_is, match_js]
|
| 50 |
+
|
| 51 |
+
match_js = np.asarray(match_js, dtype=int)
|
| 52 |
+
match_js = match_js[np.logical_not(np.isnan(match_ious))]
|
| 53 |
+
keep[match_js] = False
|
| 54 |
+
trk_tlwhs = trk_tlwhs[keep]
|
| 55 |
+
trk_ids = trk_ids[keep]
|
| 56 |
+
#match_is, match_js = mm.lap.linear_sum_assignment(iou_distance)
|
| 57 |
+
#match_is, match_js = map(lambda a: np.asarray(a, dtype=int), [match_is, match_js])
|
| 58 |
+
#match_ious = iou_distance[match_is, match_js]
|
| 59 |
+
|
| 60 |
+
#match_js = np.asarray(match_js, dtype=int)
|
| 61 |
+
#match_js = match_js[np.logical_not(np.isnan(match_ious))]
|
| 62 |
+
#keep[match_js] = False
|
| 63 |
+
#trk_tlwhs = trk_tlwhs[keep]
|
| 64 |
+
#trk_ids = trk_ids[keep]
|
| 65 |
+
|
| 66 |
+
# get distance matrix
|
| 67 |
+
iou_distance = mm.distances.iou_matrix(gt_tlwhs, trk_tlwhs, max_iou=0.5)
|
| 68 |
+
|
| 69 |
+
# acc
|
| 70 |
+
self.acc.update(gt_ids, trk_ids, iou_distance)
|
| 71 |
+
|
| 72 |
+
if rtn_events and iou_distance.size > 0 and hasattr(self.acc, 'last_mot_events'):
|
| 73 |
+
events = self.acc.last_mot_events # only supported by https://github.com/longcw/py-motmetrics
|
| 74 |
+
else:
|
| 75 |
+
events = None
|
| 76 |
+
return events
|
| 77 |
+
|
| 78 |
+
def eval_file(self, filename):
|
| 79 |
+
self.reset_accumulator()
|
| 80 |
+
|
| 81 |
+
result_frame_dict = read_results(filename, self.data_type, is_gt=False)
|
| 82 |
+
#frames = sorted(list(set(self.gt_frame_dict.keys()) | set(result_frame_dict.keys())))
|
| 83 |
+
frames = sorted(list(set(result_frame_dict.keys())))
|
| 84 |
+
for frame_id in frames:
|
| 85 |
+
trk_objs = result_frame_dict.get(frame_id, [])
|
| 86 |
+
trk_tlwhs, trk_ids = unzip_objs(trk_objs)[:2]
|
| 87 |
+
self.eval_frame(frame_id, trk_tlwhs, trk_ids, rtn_events=False)
|
| 88 |
+
|
| 89 |
+
return self.acc
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def get_summary(accs, names, metrics=('mota', 'num_switches', 'idp', 'idr', 'idf1', 'precision', 'recall')):
|
| 93 |
+
names = copy.deepcopy(names)
|
| 94 |
+
if metrics is None:
|
| 95 |
+
metrics = mm.metrics.motchallenge_metrics
|
| 96 |
+
metrics = copy.deepcopy(metrics)
|
| 97 |
+
|
| 98 |
+
mh = mm.metrics.create()
|
| 99 |
+
summary = mh.compute_many(
|
| 100 |
+
accs,
|
| 101 |
+
metrics=metrics,
|
| 102 |
+
names=names,
|
| 103 |
+
generate_overall=True
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
return summary
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def save_summary(summary, filename):
|
| 110 |
+
import pandas as pd
|
| 111 |
+
writer = pd.ExcelWriter(filename)
|
| 112 |
+
summary.to_excel(writer)
|
| 113 |
+
writer.close()
|
tracking_utils/io.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Dict
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from tracking_utils.log import logger
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def write_results(filename, results_dict: Dict, data_type: str):
|
| 9 |
+
if not filename:
|
| 10 |
+
return
|
| 11 |
+
path = os.path.dirname(filename)
|
| 12 |
+
if not os.path.exists(path):
|
| 13 |
+
os.makedirs(path)
|
| 14 |
+
|
| 15 |
+
if data_type in ('mot', 'mcmot', 'lab'):
|
| 16 |
+
save_format = '{frame},{id},{x1},{y1},{w},{h},1,-1,-1,-1\n'
|
| 17 |
+
elif data_type == 'kitti':
|
| 18 |
+
save_format = '{frame} {id} pedestrian -1 -1 -10 {x1} {y1} {x2} {y2} -1 -1 -1 -1000 -1000 -1000 -10 {score}\n'
|
| 19 |
+
else:
|
| 20 |
+
raise ValueError(data_type)
|
| 21 |
+
|
| 22 |
+
with open(filename, 'w') as f:
|
| 23 |
+
for frame_id, frame_data in results_dict.items():
|
| 24 |
+
if data_type == 'kitti':
|
| 25 |
+
frame_id -= 1
|
| 26 |
+
for tlwh, track_id in frame_data:
|
| 27 |
+
if track_id < 0:
|
| 28 |
+
continue
|
| 29 |
+
x1, y1, w, h = tlwh
|
| 30 |
+
x2, y2 = x1 + w, y1 + h
|
| 31 |
+
line = save_format.format(frame=frame_id, id=track_id, x1=x1, y1=y1, x2=x2, y2=y2, w=w, h=h, score=1.0)
|
| 32 |
+
f.write(line)
|
| 33 |
+
logger.info('Save results to {}'.format(filename))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def read_results(filename, data_type: str, is_gt=False, is_ignore=False):
|
| 37 |
+
if data_type in ('mot', 'lab'):
|
| 38 |
+
read_fun = read_mot_results
|
| 39 |
+
else:
|
| 40 |
+
raise ValueError('Unknown data type: {}'.format(data_type))
|
| 41 |
+
|
| 42 |
+
return read_fun(filename, is_gt, is_ignore)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
labels={'ped', ... % 1
|
| 47 |
+
'person_on_vhcl', ... % 2
|
| 48 |
+
'car', ... % 3
|
| 49 |
+
'bicycle', ... % 4
|
| 50 |
+
'mbike', ... % 5
|
| 51 |
+
'non_mot_vhcl', ... % 6
|
| 52 |
+
'static_person', ... % 7
|
| 53 |
+
'distractor', ... % 8
|
| 54 |
+
'occluder', ... % 9
|
| 55 |
+
'occluder_on_grnd', ... %10
|
| 56 |
+
'occluder_full', ... % 11
|
| 57 |
+
'reflection', ... % 12
|
| 58 |
+
'crowd' ... % 13
|
| 59 |
+
};
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def read_mot_results(filename, is_gt, is_ignore):
|
| 64 |
+
valid_labels = {1}
|
| 65 |
+
ignore_labels = {2, 7, 8, 12}
|
| 66 |
+
results_dict = dict()
|
| 67 |
+
if os.path.isfile(filename):
|
| 68 |
+
with open(filename, 'r') as f:
|
| 69 |
+
for line in f.readlines():
|
| 70 |
+
linelist = line.split(',')
|
| 71 |
+
if len(linelist) < 7:
|
| 72 |
+
continue
|
| 73 |
+
fid = int(linelist[0])
|
| 74 |
+
if fid < 1:
|
| 75 |
+
continue
|
| 76 |
+
results_dict.setdefault(fid, list())
|
| 77 |
+
|
| 78 |
+
box_size = float(linelist[4]) * float(linelist[5])
|
| 79 |
+
|
| 80 |
+
if is_gt:
|
| 81 |
+
if 'MOT16-' in filename or 'MOT17-' in filename:
|
| 82 |
+
label = int(float(linelist[7]))
|
| 83 |
+
mark = int(float(linelist[6]))
|
| 84 |
+
if mark == 0 or label not in valid_labels:
|
| 85 |
+
continue
|
| 86 |
+
score = 1
|
| 87 |
+
elif is_ignore:
|
| 88 |
+
if 'MOT16-' in filename or 'MOT17-' in filename:
|
| 89 |
+
label = int(float(linelist[7]))
|
| 90 |
+
vis_ratio = float(linelist[8])
|
| 91 |
+
if label not in ignore_labels and vis_ratio >= 0:
|
| 92 |
+
continue
|
| 93 |
+
else:
|
| 94 |
+
continue
|
| 95 |
+
score = 1
|
| 96 |
+
else:
|
| 97 |
+
score = float(linelist[6])
|
| 98 |
+
|
| 99 |
+
#if box_size > 7000:
|
| 100 |
+
#if box_size <= 7000 or box_size >= 15000:
|
| 101 |
+
#if box_size < 15000:
|
| 102 |
+
#continue
|
| 103 |
+
|
| 104 |
+
tlwh = tuple(map(float, linelist[2:6]))
|
| 105 |
+
#target_id = int(linelist[1].replace(".", ""))
|
| 106 |
+
target_id = linelist[1]
|
| 107 |
+
|
| 108 |
+
results_dict[fid].append((tlwh, target_id, score))
|
| 109 |
+
|
| 110 |
+
return results_dict
|
| 111 |
+
|
| 112 |
+
def unzip_objs(objs):
|
| 113 |
+
if len(objs) > 0:
|
| 114 |
+
tlwhs, ids, scores = zip(*objs)
|
| 115 |
+
else:
|
| 116 |
+
tlwhs, ids, scores = [], [], []
|
| 117 |
+
tlwhs = np.asarray(tlwhs, dtype=float).reshape(-1, 4)
|
| 118 |
+
|
| 119 |
+
return tlwhs, ids, scores
|
tracking_utils/log.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def get_logger(name='root'):
|
| 5 |
+
formatter = logging.Formatter(
|
| 6 |
+
# fmt='%(asctime)s [%(levelname)s]: %(filename)s(%(funcName)s:%(lineno)s) >> %(message)s')
|
| 7 |
+
fmt='%(asctime)s [%(levelname)s]: %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
| 8 |
+
|
| 9 |
+
handler = logging.StreamHandler()
|
| 10 |
+
handler.setFormatter(formatter)
|
| 11 |
+
|
| 12 |
+
logger = logging.getLogger(name)
|
| 13 |
+
logger.setLevel(logging.DEBUG)
|
| 14 |
+
logger.addHandler(handler)
|
| 15 |
+
return logger
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
logger = get_logger('root')
|