Deepsort目标跟踪算法绘制目标运动轨迹

Deepsort

对于跟踪到的目标,利用cv2.line连接前后帧的跟踪框中点,从而得到目标轨迹

有其他方法欢迎留言!vx:zzzz585756,私聊进目标跟踪交流群 招线上学术兼职

2021.12.20更新:

源代码链接为:

​​​​​​https://github.com/mikel-brostrom/Yolov5_DeepSort_Pytorch

添加完轨迹之后的完整代码如下,可直接运行:

链接:https://pan.baidu.com/s/1uBRgt1Pmr-awU5zhrxfUUQ 
提取码:ybci 


'''首先在跟踪主程序track.py中找到下面这一行,这一行是对跟踪框进行更新,是跟踪算法的核心
   得到的outputs存放以下信息:[x1, y1, x2, y2, track_id],即目标框的左上角和右下角坐标以及分配给它的ID
'''
outputs = self.deepsort.update(bbox_xcycwh, cls_conf, im)
# outputs = [x1, y1, x2, y2, track_id]
bbox_xyxy = outputs[:, :4]   # 提取前四列  坐标
identities = outputs[:, -1]  # 提取最后一列 ID
box_xywh = xyxy2tlwh(bbox_xyxy)  
# xyxy2tlwh是坐标格式转换,从x1, y1, x2, y2转为top left x ,top left y, w, h 具体函数看文章最后
for j in range(len(box_xywh)):
    x_center = box_xywh[j][0] + box_xywh[j][2] / 2  # 求框的中心x坐标
    y_center = box_xywh[j][1] + box_xywh[j][3] / 2  # 求框的中心y坐标
    id = outputs[j][-1]
    center = [x_center, y_center]
    dict_box.setdefault(id, []).append(center)  
# 这个字典需要提前定义 在读取每一帧的循环外面定义 dict_box = dict(),这个字典的目的就是把ID和框的中心坐标对应起来,ID是字典的key,中心坐标是字典的Value,这样才能把同ID的目标中心坐标连起来。

# 以下为画轨迹,原理就是将前后帧同ID的跟踪框中心坐标连接起来
if frame_cnt > 2:  # 第一帧无法连线,所以设置从第二帧开始,frame_cnt为当前帧号
    for key, value in dict_box.items():
        for a in range(len(value) - 1):
            color = COLORS_10[key % len(COLORS_10)]
            index_start = a
            index_end = index_start + 1
            cv2.line(ori_im, tuple(map(int, value[index_start])), tuple(map(int, value[index_end])), #map(int,"1234")转换为list[1,2,3,4]
                                            color, thickness=2, lineType=8)
# xyxy2tlwh函数  这个函数一般都会自带
def xyxy2tlwh(x):
    '''
    (top left x, top left y,width, height)
    '''
    y = torch.zeros_like(x) if isinstance(x,
                                          torch.Tensor) else np.zeros_like(x)
    y[:, 0] = x[:, 0]
    y[:, 1] = x[:, 1]
    y[:, 2] = x[:, 2] - x[:, 0]
    y[:, 3] = x[:, 3] - x[:, 1]
    return y

COLOR10是给轨迹加颜色的一个参数,是为了设置不同目标的轨迹颜色不同,如果不想这么复杂,可以改成固定颜色。

COLORS_10 =[(144,238,144),(178, 34, 34),(221,160,221),(  0,255,  0),(  0,128,  0),(210,105, 30),(220, 20, 60),
            (192,192,192),(255,228,196),( 50,205, 50),(139,  0,139),(100,149,237),(138, 43,226),(238,130,238),
            (255,  0,255),(  0,100,  0),(127,255,  0),(255,  0,255),(  0,  0,205),(255,140,  0),(255,239,213),
            (199, 21,133),(124,252,  0),(147,112,219),(106, 90,205),(176,196,222),( 65,105,225),(173,255, 47),
            (255, 20,147),(219,112,147),(186, 85,211),(199, 21,133),(148,  0,211),(255, 99, 71),(144,238,144),
            (255,255,  0),(230,230,250),(  0,  0,255),(128,128,  0),(189,183,107),(255,255,224),(128,128,128),
            (105,105,105),( 64,224,208),(205,133, 63),(  0,128,128),( 72,209,204),(139, 69, 19),(255,245,238),
            (250,240,230),(152,251,152),(  0,255,255),(135,206,235),(  0,191,255),(176,224,230),(  0,250,154),
            (245,255,250),(240,230,140),(245,222,179),(  0,139,139),(143,188,143),(255,  0,  0),(240,128,128),
            (102,205,170),( 60,179,113),( 46,139, 87),(165, 42, 42),(178, 34, 34),(175,238,238),(255,248,220),
            (218,165, 32),(255,250,240),(253,245,230),(244,164, 96),(210,105, 30)]

点个赞吧,大伙儿~~


 

  • 59
    点赞
  • 243
    收藏
    觉得还不错? 一键收藏
  • 136
    评论
DeepSORTDeep Learning-based Object Tracking)是一种基于深度学习目标跟踪算法,它可以预测目标运动轨迹。以下是使用DeepSORT进行目标跟踪画出目标运动轨迹的代码示例: 首先,安装必要的库: ```python pip install numpy pip install opencv-python pip install tensorflow pip install keras pip install filterpy pip install scikit-learn ``` 然后,导入必要的库: ```python import numpy as np import cv2 from deep_sort import preprocessing, nn_matching from deep_sort.detection import Detection from deep_sort.tracker import Tracker from tools import generate_detections as gdet ``` 接下来,定义一些变量: ```python model_filename = 'model_data/mars-small128.pb' encoder = gdet.create_box_encoder(model_filename, batch_size=1) metric = nn_matching.NearestNeighborDistanceMetric("cosine", 0.2, None) tracker = Tracker(metric) ``` 其中,`model_filename`是预训练模型的文件路径,`encoder`是用于对检测进行编码的函数,`metric`是用于计算距离的度量函数,`tracker`是目标跟踪器。 然后,读取视频并进行处理: ```python video_path = 'path/to/video.mp4' video_capture = cv2.VideoCapture(video_path) while True: ret, frame = video_capture.read() if ret != True: break frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) detections = detect_objects(frame) # 检测物体 features = encoder(frame, detections) # 特征编码 detections = [Detection(bbox, 1.0, feature) for bbox, feature in zip(detections, features)] tracker.predict() # 预测目标位置 tracker.update(detections) # 更新目标位置 for track in tracker.tracks: if not track.is_confirmed() or track.time_since_update > 1: continue bbox = track.to_tlbr() cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (0, 255, 0), 2) cv2.putText(frame, str(track.track_id), (int(bbox[0]), int(bbox[1]) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2, cv2.LINE_AA) trace = np.array(track.trace).astype(np.int32) cv2.polylines(frame, [trace], False, (0, 255, 0), 2) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows() ``` 其中,`detect_objects`函数用于检测物体,`track.to_tlbr()`用于获取目标位置,`cv2.rectangle`和`cv2.putText`用于在图像上绘制ID,`track.trace`用于获取目标运动轨迹,`cv2.polylines`用于在图像上绘制运动轨迹。 完整的代码可在 https://github.com/nwojke/deep_sort 中找到。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 136
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值