目标跟踪算法:
sort算法:
sort算法流程图
关联成功的检测box与追踪box处理:使用检测的box对追踪结果进行KalmanFilter权重以及参数更新,同时记录关联追踪box的计数次数;
未关联成功的box处理:对检测的box进行KalmanFilter初始化,并且加入追踪列表中;
未关联成功的追踪box处理:首先判断该追踪box失去关联的计数次数是否大于最大的阈值max_age,如果大于则从追踪列表删除;否则,就将失去关联计数加1。
当然,还会存在关联几次min_hits之后在追踪列表显示进行输出;
至于关联是否成功是通过检测box与追踪box的IoU计算出来,然后组成代价矩阵,通过匈牙利算法找出最大匹配对。最后通过阈值来判断是否关联。
传送门:https://blog.csdn.net/Small_Munich/article/details/112631175
其中设计两个算法:
卡尔曼滤波和匈牙利算法匹配:
卡尔曼滤波:本质上是一种去噪的操作,和物理学上的误差分析特别类似,但是运用循环迭代的思想。
匈牙利算法是一种运筹学的基本算法,核心就是用最小的代价进行最大化匹配。
sort算法的优缺点:不能得到
sort,代码分析
在这里插入代码片
"""
SORT: A Simple, Online and Realtime Tracker
Copyright (C) 2016 Alex Bewley alex@dynamicdetection.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import print_function
from numba import jit #是python的一个JIT库,通过装饰器来实现运行时的加速
import os.path
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches #用于绘制常见图像(如矩形,椭圆,圆形,多边形)
from skimage import io
from sklearn.utils.linear_assignment_ import linear_assignment
import glob
import time
import argparse
from filterpy.kalman import KalmanFilter #filterpy包含了一些常用滤波器的库
@jit #用了jit装饰器,可加速for循环的计算
def iou(bb_test,bb_gt):
"""
Computes IOU between two bboxes in the form [x1,y1,x2,y2]
"""
xx1 = np.maximum(bb_test[0], bb_gt[0])
yy1 = np.maximum(bb_test[1], bb_gt[1])
xx2 = np.minimum(bb_test[2], bb_gt[2])
yy2 = np.minimum(bb_test[3], bb_gt[3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
o = wh / ((bb_test[2]-bb_test[0])*(bb_test[3]-bb_test[1]) #IOU=(bb_test和bb_gt框相交部分面积)/(bb_test框面积+bb_gt框面积 - 两者相交面积)
+ (bb_gt[2]-bb_gt[0])*(bb_gt[3]-bb_gt[1]) - wh)
return(o)
def convert_bbox_to_z(bbox): #将bbox由[x1,y1,x2,y2]形式转为 [框中心点x,框中心点y,框面积s,宽高比例r]^T
"""
Takes a bounding box in the form [x1,y1,x2,y2] and returns z in the form
[x,y,s,r] where x,y is the centre of the box and s is the scale/area and r is
the aspect ratio
"""
w = bbox[2]-bbox[0]
h = bbox[3]-bbox[1]
x = bbox[0]+w/2.
y = bbox[1]+h/2.
s = w*h #scale is just area
r = w/float(h)
return np.array([x,y,s,r]).reshape((4,1)) #将数组转为4行一列形式,即[x,y,s,r]^T
def convert_x_to_bbox(x,score=None): #将[x,y,s,r]形式的bbox,转为[x1,y1,x2,y2]形式
"""
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
[x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
"""
w = np.sqrt(x[2]*x[3]) #w=sqrt(w*h * w/h)
h = x[2]/w #h=w*h/w
if(score==None): #如果检测框不带置信度
return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.]).reshape((1,4)) #返回[x1,y1,x2,y2]
else: #如果加测框带置信度
return np.array([x[0]-w/2.,x[1]-h/2.,x[0]+w/2.,x[1]+h/2.,score]).reshape((1,5)) #返回[x1,y1,x2,y2,score]
class KalmanBoxTracker(object):
"""
This class represents the internel state of individual tracked objects observed as bbox.
"""
count = 0
def __init__(self,bbox):
"""
Initialises a tracker using initial bounding box. 使用初始边界框初始化跟踪器
"""
#define constant velocity model #定义匀速模型
self.kf = KalmanFilter(dim_x=7, dim_z=4) #状态变量是7维, 观测值是4维的,按照需要的维度构建目标
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],[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]])
self.kf.H = np.array([[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]])
self.kf.R[2:,2:] *= 10.
self.kf.P[4:,4:] *= 1000. #give high uncertainty to the unobservable initial velocities 对未观测到的初始速度给出高的不确定性
self.kf.P *= 10. # 默认定义的协方差矩阵是np.eye(dim_x),将P中的数值与10, 1000相乘,赋值不确定性
self.kf.Q[-1,-1] *= 0.01
self.kf.Q[4:,4:] *= 0.01
self.kf.x[:4] = convert_bbox_to_z(bbox) #将bbox转为 [x,y,s,r]^T形式,赋给状态变量X的前4位
self.time_since_update = 0
self.id = KalmanBoxTracker.count
KalmanBoxTracker.count += 1
self.history = []
self.hits = 0
self.hit_streak = 0
self.age = 0
def update(self,bbox):
"""
Updates the state vector with observed bbox.
"""
self.time_since_update = 0
self.history = []
self.hits += 1
self.hit_streak += 1
self.kf.update(convert_bbox_to_z(bbox))
def predict(self):
"""
Advances the state vector and returns the predicted bounding box estimate.
"""
if((self.kf.x[6]+self.kf.x[2])<=0):
self.kf.x[6] *= 0.0
self.kf.predict()
self.age += 1
if(self.time_since_update>0):
self.hit_streak = 0
self.time_since_update += 1
self.history.append(convert_x_to_bbox(self.kf.x))
return self.history[-1]
def get_state(self):
"""
Returns the current bounding box estimate.
"""
return convert_x_to_bbox(self.kf.x)
def associate_detections_to_trackers(detections,trackers,iou_threshold = 0.3): #用于将检测与跟踪进行关联
"""
Assigns detections to tracked object (both represented as bounding boxes)
Returns 3 lists of matches, unmatched_detections and unmatched_trackers
"""
if(len(trackers)==0): #如果跟踪器为空
return np.empty((0,2),dtype=int), np.arange(len(detections)), np.empty((0,5),dtype=int)
iou_matrix = np.zeros((len(detections),len(trackers)),dtype=np.float32) # 检测器与跟踪器IOU矩阵
for d,det in enumerate(detections):
for t,trk in enumerate(trackers):
iou_matrix[d,t] = iou(det,trk) #计算检测器与跟踪器的IOU并赋值给IOU矩阵对应位置
matched_indices = linear_assignment(-iou_matrix) # 参考:https://blog.csdn.net/herr_kun/article/details/86509591 加上负号是因为linear_assignment求的是最小代价组合,而我们需要的是IOU最大的组合方式,所以取负号
unmatched_detections = [] #未匹配上的检测器
for d,det in enumerate(detections):
if(d not in matched_indices[:,0]): #如果检测器中第d个检测结果不在匹配结果索引中,则d未匹配上
unmatched_detections.append(d)
unmatched_trackers = [] #未匹配上的跟踪器
for t,trk in enumerate(trackers):
if(t not in matched_indices[:,1]): #如果跟踪器中第t个跟踪结果不在匹配结果索引中,则t未匹配上
unmatched_trackers.append(t)
#filter out matched with low IOU 过滤掉那些IOU较小的匹配对
matches = [] #存放过滤后的匹配结果
for m in matched_indices: #遍历粗匹配结果
if(iou_matrix[m[0],m[1]]<iou_threshold): #m[0]是检测器ID, m[1]是跟踪器ID,如它们的IOU小于阈值则将它们视为未匹配成功
unmatched_detections.append(m[0])
unmatched_trackers.append(m[1])
else:
matches.append(m.reshape(1,2)) #将过滤后的匹配对维度变形成1x2形式
if(len(matches)==0): #如果过滤后匹配结果为空,那么返回空的匹配结果
matches = np.empty((0,2),dtype=int)
else: #如果过滤后匹配结果非空,则按0轴方向继续添加匹配对
matches = np.concatenate(matches,axis=0)
return matches, np.array(unmatched_detections), np.array(unmatched_trackers) #其中跟踪器数组是5列的(最后一列是ID)
class Sort(object):
def __init__(self,max_age=1,min_hits=3):
"""
Sets key parameters for SORT
"""
self.max_age = max_age
self.min_hits = min_hits
self.trackers = []
self.frame_count = 0
def update(self,dets): #输入的是检测结果[x1,y1,x2,y2,score]形式
"""
Params:
dets - a numpy array of detections in the format [[x1,y1,x2,y2,score],[x1,y1,x2,y2,score],...]
Requires: this method must be called once for each frame even with empty detections. #每一帧都得调用一次,即便检测结果为空
Returns the a similar array, where the last column is the object ID. #返回相似的数组,最后一列是目标ID
NOTE: The number of objects returned may differ from the number of detections provided. #返回的目标数量可能与提供的检测数量不同
"""
self.frame_count += 1 #帧计数
#get predicted locations from existing trackers.
trks = np.zeros((len(self.trackers),5)) # 根据当前所有卡尔曼跟踪器的个数创建二维零矩阵,维度为:卡尔曼跟踪器ID个数x 5 (这5列内容为bbox与ID)
to_del = [] #存放待删除
ret = [] #存放最后返回的结果
for t,trk in enumerate(trks): #循环遍历卡尔曼跟踪器列表
pos = self.trackers[t].predict()[0] #用卡尔曼跟踪器t 预测 对应物体在当前帧中的bbox
trk[:] = [pos[0], pos[1], pos[2], pos[3], 0]
if(np.any(np.isnan(pos))): #如果预测的bbox为空,那么将第t个卡尔曼跟踪器删除
to_del.append(t)
trks = np.ma.compress_rows(np.ma.masked_invalid(trks)) #将预测为空的卡尔曼跟踪器所在行删除,最后trks中存放的是上一帧中被跟踪的所有物体在当前帧中预测的非空bbox
for t in reversed(to_del): #对to_del数组进行倒序遍历
self.trackers.pop(t) #从跟踪器中删除 to_del中的上一帧跟踪器ID
matched, unmatched_dets, unmatched_trks = associate_detections_to_trackers(dets,trks) #对传入的检测结果 与 上一帧跟踪物体在当前帧中预测的结果做关联,返回匹配的目标矩阵matched, 新增目标的矩阵unmatched_dets, 离开画面的目标矩阵unmatched_trks
#update matched trackers with assigned detections
for t,trk in enumerate(self.trackers): # 对卡尔曼跟踪器做遍历
if(t not in unmatched_trks): #如果上一帧中的t还在当前帧画面中(即不在当前预测的离开画面的矩阵unmatched_trks中)
d = matched[np.where(matched[:,1]==t)[0],0] #说明卡尔曼跟踪器t是关联成功的,在matched矩阵中找到与其关联的检测器d
trk.update(dets[d,:][0]) #用关联的检测结果d来更新卡尔曼跟踪器(即用后验来更新先验)
#create and initialise new trackers for unmatched detections #对于新增的未匹配的检测结果,创建并初始化跟踪器
for i in unmatched_dets: #新增目标
trk = KalmanBoxTracker(dets[i,:]) #将新增的未匹配的检测结果dets[i,:]传入KalmanBoxTracker
self.trackers.append(trk) #将新创建和初始化的跟踪器trk 传入trackers
i = len(self.trackers)
for trk in reversed(self.trackers): #对新的卡尔曼跟踪器集进行倒序遍历
d = trk.get_state()[0] #获取trk跟踪器的状态 [x1,y1,x2,y2]
if((trk.time_since_update < 1) and (trk.hit_streak >= self.min_hits or self.frame_count <= self.min_hits)):
ret.append(np.concatenate((d,[trk.id+1])).reshape(1,-1)) # +1 as MOT benchmark requires positive
i -= 1
#remove dead tracklet
if(trk.time_since_update > self.max_age):
self.trackers.pop(i)
if(len(ret)>0):
return np.concatenate(ret)
return np.empty((0,5))
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='SORT demo')
parser.add_argument('--display', dest='display', help='Display online tracker output (slow) [False]',action='store_true')
args = parser.parse_args()
return args
if __name__ == '__main__':
# all train
sequences = ['PETS09-S2L1','TUD-Campus','TUD-Stadtmitte','ETH-Bahnhof','ETH-Sunnyday','ETH-Pedcross2','KITTI-13','KITTI-17','ADL-Rundle-6','ADL-Rundle-8','Venice-2']
args = parse_args()
display = args.display
phase = 'train'
total_time = 0.0
total_frames = 0
colours = np.random.rand(32,3) #used only for display
if(display):
if not os.path.exists('mot_benchmark'):
print('\n\tERROR: mot_benchmark link not found!\n\n Create a symbolic link to the MOT benchmark\n (https://motchallenge.net/data/2D_MOT_2015/#download). E.g.:\n\n $ ln -s /path/to/MOT2015_challenge/2DMOT2015 mot_benchmark\n\n')
exit()
plt.ion() #用于动态绘制显示图像
fig = plt.figure()
if not os.path.exists('output'):
os.makedirs('output')
for seq in sequences:
mot_tracker = Sort() #create instance of the SORT tracker 创建Sort 跟踪实例
seq_dets = np.loadtxt('data/%s/det.txt'%(seq),delimiter=',') #load detections #加载检测结果
with open('output/%s.txt'%(seq),'w') as out_file:
print("Processing %s."%(seq))
for frame in range(int(seq_dets[:,0].max())): #确定视频序列总帧数,并进行for循环
frame += 1 #detection and frame numbers begin at 1 #由于视频序列帧数是从1开始的,因此加1
dets = seq_dets[seq_dets[:,0]==frame,2:7] #提取检测结果中的[x1,y1,w,h,score]到dets
dets[:,2:4] += dets[:,0:2] #convert to [x1,y1,w,h] to [x1,y1,x2,y2] 将dets中的第2,3列的数加上第0,1列的数后赋值给2,3列;
total_frames += 1 #总帧数累计
if(display): #如果要求显示结果
ax1 = fig.add_subplot(111, aspect='equal')
fn = 'mot_benchmark/%s/%s/img1/%06d.jpg'%(phase,seq,frame) #原图像路径名
im =io.imread(fn) #加载图像
ax1.imshow(im) #显示图像
plt.title(seq+' Tracked Targets')
start_time = time.time()
trackers = mot_tracker.update(dets) #sort跟踪器更新
cycle_time = time.time() - start_time #sort跟踪器耗时
total_time += cycle_time #sort跟踪器总共耗费时间
for d in trackers:
print('%d,%d,%.2f,%.2f,%.2f,%.2f,1,-1,-1,-1'%(frame,d[4],d[0],d[1],d[2]-d[0],d[3]-d[1]),file=out_file) #打印: frame,ID,x1,y1,x2,y2,1,-1,-1,-1
if(display): #如果显示,将目标检测框画上
d = d.astype(np.int32)
ax1.add_patch(patches.Rectangle((d[0],d[1]),d[2]-d[0],d[3]-d[1],fill=False,lw=3,ec=colours[d[4]%32,:]))
ax1.set_adjustable('box-forced')
if(display):
fig.canvas.flush_events()
plt.draw()
ax1.cla()
print("Total Tracking took: %.3f for %d frames or %.1f FPS"%(total_time,total_frames,total_frames/total_time))
if(display):
print("Note: to get real runtime results run without the option: --display")
```python
sort的缺点:
那么这样的话,一旦物体受到遮挡或者其他原因没有被检测到,卡尔曼滤波预测的状态信息将无法和检测结果进行匹配,该追踪片段将会提前结束。
遮挡结束后,车辆检测可能又将被继续执行,那么SORT只能分配给该物体一个新的ID编号,代表一个新的追踪片段的开始。所以SORT的缺点是
受遮挡等情况影响较大,会有大量的ID切换
sort的优点:
模型简单,效率高
deepsort:
deepsort模型和sort的区别是:
很显然,DeepSORT中采用了一个简单(运算量不大)的CNN来提取被检测物体(检测框物体中)的外观特征(低维向量表示),在每次(每帧)检测+追踪后,进行一次物体外观特征的提取并保存。
后面每执行一步时,都要执行一次当前帧被检测物体外观特征与之前存储的外观特征的相似度计算,这个相似度将作为一个重要的判别依据(不是唯一的,因为作者说是将运动特征与外观特征结合作为判别依据,这个运动特征就是SORT中卡尔曼滤波做的事)
那么这个网络最后输出的是一个128维的向量。有关残差网络和上图表中残差模块的结构就不多说,很简单。
值得关注的是,由于DeepSORT主要被用来做行人追踪的,那么输入的大小为128(高)x 64(宽)的矩形框。如果你需要做其他物体追踪,可能要把网络模型的输入进行修改。
在这里插入代码片:
在这里插入代码片
class Net(nn.Module):
def __init__(self, num_classes=751 ,reid=False):
super(Net,self).__init__()
# 3 128 64
self.conv = nn.Sequential(
nn.Conv2d(3,64,3,stride=1,padding=1),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
# nn.Conv2d(32,32,3,stride=1,padding=1),
# nn.BatchNorm2d(32),
# nn.ReLU(inplace=True),
nn.MaxPool2d(3,2,padding=1),
)
# 32 64 32
self.layer1 = make_layers(64,64,2,False)
# 32 64 32
self.layer2 = make_layers(64,128,2,True)
# 64 32 16
self.layer3 = make_layers(128,256,2,True)
# 128 16 8
self.layer4 = make_layers(256,512,2,True)
# 256 8 4
self.avgpool = nn.AvgPool2d((8,4),1)
# 256 1 1
self.reid = reid
self.classifier = nn.Sequential(
nn.Linear(512, 256),
nn.BatchNorm1d(256),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(256, num_classes),
)
def forward(self, x):
x = self.conv(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0),-1)
# B x 128
if self.reid:
x = x.div(x.norm(p=2,dim=1,keepdim=True))
return x
# classifier
x = self.classifier(x)
return x
DeepSORT中的卡尔曼滤波:
但个人认为其中最值得学习的是其提出了,解决处理测量值到跟踪器之间的转换关系且一定程度解决了由于物体被遮挡时间太久,卡尔曼滤波器预测结果发散的问题——级联匹配:
卡尔曼滤波:相对于Sort算法中7个维度的信息,Deepsort中使用了8个维度的信息,分别为目标框中心坐标(u,v),长宽比γ,高h以及这四个变量的一阶导数,表示变换速率。且和Sort中一样,其都定义为一个恒速模型,即后面四个变量都设定为常数。这部分个人认为改动不大,相当将原来的面积部分——改动为检测框的长框比和其中一维高或宽的变化
我们在SORT深度解析时提到过,SORT中的卡尔曼滤波算法使用的状态是一个7维的向量。即
x
=
[
u
,
v
,
s
,
r
,
u
˙
,
v
˙
,
s
˙
]
T
\mathbf{x}=[u, v, s, r, \dot{u}, \dot{v}, \dot{s}]^T
x=[u,v,s,r,u˙,v˙,s˙]T
在DeepSORT中,使用的状态是一个8维的向量:
(
u
,
v
,
γ
,
h
,
x
˙
,
y
˙
,
γ
˙
,
h
)
(u, v, \gamma, h, \dot{x}, \dot{y}, \dot{\gamma}, h)
(u,v,γ,h,x˙,y˙,γ˙,h)
相较于SORT中的状态,多了一个长宽比(aspect ratio)的变化率。这是合情合理的,毕竟像SORT中假设物体检测框的长宽比是固定的,实际过程中,随着镜头移动或者物体与相机的相对运动,物体的长宽比也是会发生变化的。
观测状态的定义:在Sort中,当卡尔曼滤波检测到结果,立即会将结果进行跟新,也即去和检测框进行IOU匹配。而在Deepsort中,我们把检测到的结果分为确定态和非确定态,初始时均为非确定态,只有连续3帧的匹配上(这里的匹配,和Sort中的直接IOU匹配类似)才能转为确定态,而转为确定态的预测结果,则会根检测框进行Matching Cascade-级联匹配。这一步的改变,我认为是DeepSort中优越与Sort的重要因素。
指派分配问题:
代价矩阵的定义:在Sort中,对于代价矩阵,即是直接计算卡尔曼滤波预测出来的结果和检测网络结果的IOU作为代价矩阵。而在DeepSort中,由上面所说的,在非确定态下和Sort类似,都是以IOU为代价矩阵。而在确定态下DeepSort引入了马氏距离和余弦距离。在DeepSort中马氏距离最终用于筛选掉不符合要求的框,而余弦距离才是作为真正的代价矩阵的计算。其中余弦距离计算的不是卡尔曼预测的结果和检测网络的结果,而是计算REID网络作用与前两者之后的结果。REID网络详情等下次再说。
在卡尔曼滤波结果中,对于确定态的跟踪框集合我们记为T,当前目标检测出来的结果集合我们记为D
REID网络:
第一步
我们先将这两者T和D内的结果对应的图像送到REID网络中(我们这里先不管得到的是什么),然后去计算网络计算出来结果的余弦距离,以此作为代价矩阵costmatrix这里记为C。
第二步
我们再去计算检测和预测结果的马氏距离,然后根据统计学和实验所得的阈值,去除掉不符合马氏距离和余弦距离阈值的匹配项。(这里马氏距离仅仅作为去除不符合的匹配项而已)
第三步
根据预测框的更新状态(这里更新状态是指,这个预测框距离上一次被匹配成功的时间),越新的预测框(也即距离上一次被匹配上的帧数越短的),越优先根据C的结果进行匈牙利算法进行匹配——也即作者认为,越新的框越有可能和当前的检测框匹配上。
级联匹配算法,相对于提升了每个预测器的寿命,不至于只要检测不到就会被删除。
核心代码就在下面了,这下面的代码,我个人觉得是整个DeepSort的核心代码了。
核心代码:
在这里插入代码片
def _match(self, detections):
# 计算阈值筛选过的cost_matrix
def gated_metric(tracks, dets, track_indices, detection_indices):
features = np.array([dets[i].feature for i in detection_indices])
targets = np.array([tracks[i].track_id for i in track_indices])
# 这里使用的是cosine distance
cost_matrix = self.metric.distance(features, targets)
# 根据马氏距离,卡方分布阈值筛选cost_matrix
cost_matrix = linear_assignment.gate_cost_matrix(self.kf, cost_matrix, tracks, dets, track_indices,detection_indices)
return cost_matrix
# 将跟踪器分为确定性状态跟踪器和不确定性状态跟踪器
confirmed_tracks = [i for i, t in enumerate(self.tracks) if t.is_confirmed()]
unconfirmed_tracks = [i for i, t in enumerate(self.tracks) if not t.is_confirmed()]
# Associate confirmed tracks using appearance features.
# 对于确定性的跟踪器结果,使用外观特征进行和检测器结果匹配
matches_a, unmatched_tracks_a, unmatched_detections = \
linear_assignment.matching_cascade(gated_metric, self.metric.matching_threshold, self.max_age,
self.tracks, detections, confirmed_tracks)
# Associate remaining tracks together with unconfirmed tracks using IOU.
# 剩下的跟踪框和不确定状态的跟踪框使用IOU进行匹配
iou_track_candidates = unconfirmed_tracks + [k for k in unmatched_tracks_a if self.tracks[k].time_since_update == 1]
unmatched_tracks_a = [k for k in unmatched_tracks_a if self.tracks[k].time_since_update != 1]
matches_b, unmatched_tracks_b, unmatched_detections = \
linear_assignment.min_cost_matching(iou_matching.iou_cost, self.max_iou_distance, self.tracks,
detections, iou_track_candidates, unmatched_detections)
matches = matches_a + matches_b
unmatched_tracks = list(set(unmatched_tracks_a + unmatched_tracks_b))
return matches, unmatched_tracks, unmatched_detections
最后根据B中的结果去划分匹配上的集合和未匹配上的集合。
根据预测框的更新状态(这里更新状态是指,这个预测框距离上一次被匹配成功的时间),越新的预测框(也即距离上一次被匹配上的帧数越短的),越优先根据C的结果进行匈牙利算法进行匹配——也即作者认为,越新的框越有可能和当前的检测框匹配上。
最后根据B中的结果去划分匹配上的集合和未匹配上的集合。
同时,DeepSORT对追踪的初始化、新生与消失进行了设定。
初始化:如果一个检测没有和之前记录的track相关联,那么从该检测开始,初始化一个新的目标(并不是新生)
新生:如果一个目标被初始化后,且在前三帧中均被正常的捕捉和关联成功,那么该物体产生一个新的track,否则将被删除。
消失:如果超过了设定的最大保存时间(原文中叫做predefined maximum age)没有被关联到的话,那么说明这个物体离开了视频画面,该物体的信息(记录的外观特征和行为特征)将会被删除。
惯例中(类似SORT),解决分配问题使用的是匈牙利算法(仅使用运动特征计算代价矩阵),该算法解决了由滤波算法预测的位置与检测出来的位置间的匹配。DeepSORT中,作者结合了外观特征(由小型CNN提取的128维向量)和运动特征(卡尔曼滤波预测的结果)来计算代价矩阵,从而根据该代价矩阵使用匈牙利算法进行目标的匹配。
模型图片过程;
bytrtrack:模型,代码分析:
IOU模型: 代码分析:
应用场景描述:
问题与挑战:
形态变化 - 姿态变化是目标跟踪中常见的干扰问题。运动目标发生姿态变化时, 会导致它的特征以及外观模型发生改变, 容易导致跟踪失败。例如:体育比赛中的运动员、马路上的行人
尺度变化 - 尺度的自适应也是目标跟踪中的关键问题。当目标尺度缩小时, 由于跟踪框不能自适应跟踪, 会将很多背景信息包含在内, 导致目标模型的更新错误:当目标尺度增大时, 由于跟踪框不能将目标完全包括在内, 跟踪框内目标信息不全, 也会导致目标模型的更新错误。因此, 实现尺度自适应跟踪是十分必要的。
遮挡与消失 - 目标在运动过程中可能出现被遮挡或者短暂的消失情况。当这种情况发生时, 跟踪框容易将遮挡物以及背景信息包含在跟踪框内, 会导致后续帧中的跟踪目标漂移到遮挡物上面。若目标被完全遮挡时, 由于找不到目标的对应模型, 会导致跟踪失败
图像模糊 - 光照强度变化, 目标快速运动, 低分辨率等情况会导致图像模型, 尤其是在运动目标与背景相似的情况下更为明显。因此, 选择有效的特征对目标和背景进行区分非常必要
.相似目标容易被当成同一目标;
解决方案:
应用场景:
人员检测:计算画面中行人的数目,并确定其位置。
可用于计算区域人员密度过高告警。
可用于范围监测告警(越界监测):例如闯红灯、翻墙等事件。
异常行为检测:目标突然发生剧烈变化,如打架斗殴等行为。
还可以和车型识别、车颜色识别、车辆逆流检测等结合。实现对车辆特点的全识别。
应用场景:
a.可用于交通疏散,针对有可能发生拥堵的区域提前进行部署。
b.可用于追踪黑名单车辆:车辆检测可识别车辆类型、车辆颜色等等,这些信息均可用来定位目标。
c.防车辆套牌方案:车辆识别和车牌识别结合,防止车辆套牌案件发生
评价指标:
MOTA和MOTP共同衡量算法连续跟踪目标的能力(即,在连续帧中能准确判断目标的个数,精确的划定其位置,从而实现不间断的连续跟踪)
MOTA 越接近于 1 表示跟踪器性能越好,由于有跳变数的存在,当看到 MOTA 可能存在小于 0 的情况。
M
O
T
A
=
1
−
F
N
+
F
P
+
I
D
S
W
G
T
∈
(
−
∞
,
1
]
M O T A=1-\frac{F N+F P+I D S W}{G T} \in(-\infty, 1]
MOTA=1−GTFN+FP+IDSW∈(−∞,1]
FN 为 False Negative(漏报),整个视频漏报数量之和。
FP 为 False Positve(误报),整个视频误报数量之和。
IDSW 为 ID Switch(ID 切换总数,误配):上图图 (a),从红色的切换到了蓝色,记为一个 IDSW,整个视频误配数量之和。
GT 是 Ground Truth 物体的数量,整个视频 GT 数量之和。
MOTA 主要考虑的是 tracking 中所有对象匹配错误,主要是 FP、FN、IDs、MOTA 给出的是非常直观的衡量跟踪其在检测物体和保持轨迹时的性能,与目标检测精度无关。
MOTP:多目标跟踪精确度 (Multiple Object Tracking Precision)
衡量单摄像头多目标跟踪位置误差的一个指标
MOTP = ∑ t , i d t , i ∑ t c t \operatorname{MOTP}=\frac{\sum_{t, i} d_{t, i}}{\sum_t c_t} MOTP=∑tct∑t,idt,i
MT 大多数跟踪(Mostly Tracked)
这里需要注意的一点是:不管这条轨迹上 ID 如何的变化(比如预测的时候发生了变化),但只要还是这条轨迹占到真实轨迹的 80% 以上就可以认为是 MT。(下面这张图希望可以帮助理解
ML 大部分缺失跟踪(Mostly Lost)
一条轨迹只被跟踪到 20% 以下就可以认为是 ML
PT 部分跟踪(Partially Tracked)除了 MT、ML ,其他的都认为是 PT
IDP:识别精确度 (Identification Precision) 是指每个行人框中行人 ID 识别的精确度。
I
D
P
=
I
D
T
P
I
D
T
P
+
I
D
F
P
I D P=\frac{I D T P}{I D T P+I D F P}
IDP=IDTP+IDFPIDTP
I
D
R
=
I
D
T
P
I
D
T
P
+
I
D
F
N
I D R=\frac{I D T P}{I D T P+I D F N}
IDR=IDTP+IDFNIDTP
类似于nlp的p r f1系列。
{‘idf1’: ‘IDF1’, ‘idp’: ‘IDP’, ‘idr’: ‘IDR’, ‘recall’: ‘Rcll’, ‘precision’: ‘Prcn’, ‘num_unique_objects’: ‘GT’, ‘mostly_tracked’: ‘MT’, ‘partially_tracked’: ‘PT’, ‘mostly_lost’: ‘ML’, ‘num_false_positives’: ‘FP’, ‘num_misses’: ‘FN’, ‘num_switches’: ‘IDs’, ‘num_fragmentations’: ‘FM’, ‘mota’: ‘MOTA’, ‘motp’: ‘MOTP’, ‘num_transfer’: ‘IDt’, ‘num_ascend’: ‘IDa’, ‘num_migrate’: ‘IDm’}