基于yolo v5与Deep Sort进行车辆以及速度检测与目标跟踪实战

这篇具有很好参考价值的文章主要介绍了基于yolo v5与Deep Sort进行车辆以及速度检测与目标跟踪实战。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

项目实验结果展示:

基于yolo v5与Deep Sort进行车辆以及速度检测与目标跟踪实战——项目可以私聊

该项目可以作为毕业设计,以及企业级的项目开发,主要包含了车辆的目标检测、目标跟踪以及车辆的速度计算,同样可以进行二次开发。

这里附上主要的检测代码

import torch
import numpy as np
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.torch_utils import select_device
from utils.datasets import letterbox
import cv2
from deep_sort.utils.parser import get_config
from deep_sort.deep_sort import DeepSort
from haversine import haversine, Unit
from sys import platform as _platform



class Detector:
    """
    yolo目标检测
    """

    def __init__(self):

        self.img_size = 1280
        self.conf_thres = 0.5
        self.iou_thres=0.5

        # 目标检测权重
        self.weights = 'weights/highway_m_300.pt'
        self.device = '0' if torch.cuda.is_available() else 'cpu'
        self.device = select_device(self.device)
        model = attempt_load(self.weights, map_location=self.device)
        model.to(self.device).eval()

        # 判断系统,支持MACOS 和 windows
        if _platform == "darwin":
            # MAC OS X
            model.float()
        else:
            # Windows
            model.half()
        
        # 
        self.m = model
        self.names = model.module.names if hasattr(
            model, 'module') else model.names



    # 图片预处理
    def preprocess(self, img):

        img = letterbox(img, new_shape=self.img_size)[0]
        img = img[:, :, ::-1].transpose(2, 0, 1)
        img = np.ascontiguousarray(img)
        img = torch.from_numpy(img).to(self.device)

        if _platform == "darwin":
            # MAC OS X
            img = img.float() 
        else:
            # Windows
            img = img.half()

        img /= 255.0  # 图像归一化
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        return img

    # 目标检测
    def yolo_detect(self, im):

        img = self.preprocess(im)

        pred = self.m(img, augment=False)[0]
        pred = pred.float()
        pred = non_max_suppression(pred, self.conf_thres, self.iou_thres )

        pred_boxes = []
        for det in pred:

            if det is not None and len(det):
                det[:, :4] = scale_coords(
                    img.shape[2:], det[:, :4], im.shape).round()

                for *x, conf, cls_id in det:
                    lbl = self.names[int(cls_id)]
                    x1, y1 = int(x[0]), int(x[1])
                    x2, y2 = int(x[2]), int(x[3])
                    pred_boxes.append(
                        (x1, y1, x2, y2, lbl, conf))

        return pred_boxes


        


class Tracker:
    """
    deepsort追踪
    """
    def __init__(self):

        cfg = get_config()
        cfg.merge_from_file("deep_sort/configs/deep_sort.yaml")
        self.deepsort = DeepSort(cfg.DEEPSORT.REID_CKPT,
                            max_dist=cfg.DEEPSORT.MAX_DIST, min_confidence=cfg.DEEPSORT.MIN_CONFIDENCE,
                            nms_max_overlap=cfg.DEEPSORT.NMS_MAX_OVERLAP, max_iou_distance=cfg.DEEPSORT.MAX_IOU_DISTANCE,
                            max_age=cfg.DEEPSORT.MAX_AGE, n_init=cfg.DEEPSORT.N_INIT, nn_budget=cfg.DEEPSORT.NN_BUDGET,
                            use_cuda=True)


    def update_tracker(self,image, yolo_bboxes):

        bbox_xywh = []
        confs = []
        clss = []

        for x1, y1, x2, y2, cls_id, conf in yolo_bboxes:

            obj = [
                int((x1+x2)/2), int((y1+y2)/2),
                x2-x1, y2-y1
            ]
            bbox_xywh.append(obj)
            confs.append(conf)
            clss.append(cls_id)

        xywhs = torch.Tensor(bbox_xywh)
        confss = torch.Tensor(confs)

        #更新追踪结果
        outputs = self.deepsort.update(xywhs, confss, clss, image)
        

        bboxes2draw = []
        for value in list(outputs):
            x1, y1, x2, y2, cls_, track_id = value

            bboxes2draw.append(
                (x1, y1, x2, y2, cls_, track_id)
            )
        

        return bboxes2draw





class PixelMapper(object):
    """
    Create an object for converting pixels to geographic coordinates,
    using four points with known locations which form a quadrilteral in both planes
    Parameters
    ----------
    pixel_array : (4,2) shape numpy array
        The (x,y) pixel coordinates corresponding to the top left, top right, bottom right, bottom left
        pixels of the known region
    lonlat_array : (4,2) shape numpy array
        The (lon, lat) coordinates corresponding to the top left, top right, bottom right, bottom left
        pixels of the known region
    """
    def __init__(self, pixel_array, lonlat_array):
        assert pixel_array.shape==(4,2), "Need (4,2) input array"
        assert lonlat_array.shape==(4,2), "Need (4,2) input array"
        self.M = cv2.getPerspectiveTransform(np.float32(pixel_array),np.float32(lonlat_array))
        self.invM = cv2.getPerspectiveTransform(np.float32(lonlat_array),np.float32(pixel_array))
        
    def pixel_to_lonlat(self, pixel):
        """
        Convert a set of pixel coordinates to lon-lat coordinates
        Parameters
        ----------
        pixel : (N,2) numpy array or (x,y) tuple
            The (x,y) pixel coordinates to be converted
        Returns
        -------
        (N,2) numpy array
            The corresponding (lon, lat) coordinates
        """
        if type(pixel) != np.ndarray:
            pixel = np.array(pixel).reshape(1,2)
        assert pixel.shape[1]==2, "Need (N,2) input array" 
        pixel = np.concatenate([pixel, np.ones((pixel.shape[0],1))], axis=1)
        lonlat = np.dot(self.M,pixel.T)
        
        return (lonlat[:2,:]/lonlat[2,:]).T
    
    def lonlat_to_pixel(self, lonlat):
        """
        Convert a set of lon-lat coordinates to pixel coordinates
        Parameters
        ----------
        lonlat : (N,2) numpy array or (x,y) tuple
            The (lon,lat) coordinates to be converted
        Returns
        -------
        (N,2) numpy array
            The corresponding (x, y) pixel coordinates
        """
        if type(lonlat) != np.ndarray:
            lonlat = np.array(lonlat).reshape(1,2)
        assert lonlat.shape[1]==2, "Need (N,2) input array" 
        lonlat = np.concatenate([lonlat, np.ones((lonlat.shape[0],1))], axis=1)
        pixel = np.dot(self.invM,lonlat.T)
        
        return (pixel[:2,:]/pixel[2,:]).T


class SpeedEstimate:
    def __init__(self):

        # 配置相机画面与地图的映射点,需要根据自己镜头和地图上的点重新配置
        quad_coords = {
            "lonlat": np.array([
                [30.221866, 120.287402], # top left
                [30.221527,120.287632], # top right
                [30.222098,120.285806], # bottom left
                [30.221805,120.285748] # bottom right
            ]),
            "pixel": np.array([
                [196,129],# top left
                [337,111], # top right
                [12,513], # bottom left
                [530,516] # bottom right
            ])
        }

        self.pm = PixelMapper(quad_coords["pixel"], quad_coords["lonlat"])

    def pixel2lonlat(self,x,y):
        # 像素坐标转为经纬度
        return self.pm.pixel_to_lonlat((x,y))[0]
    
    def pixelDistance(self,pa_x,pa_y,pb_x,pb_y):
        # 相机画面两点在地图上实际的距离

        lonlat_a = self.pm.pixel_to_lonlat((pa_x,pa_y))
        lonlat_b = self.pm.pixel_to_lonlat((pb_x,pb_y))
        
        lonlat_a = tuple(lonlat_a[0])
        lonlat_b = tuple(lonlat_b[0])
        
        return haversine(lonlat_a, lonlat_b, unit='m')


    

    

项目需求+V: gldz_super   文章来源地址https://www.toymoban.com/news/detail-625107.html

到了这里,关于基于yolo v5与Deep Sort进行车辆以及速度检测与目标跟踪实战的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 改进 YOLO V5 的密集行人检测算法研究(论文研读)——目标检测

    改进 YOLO V5 的密集行人检测算法研究(论文研读)——目标检测

    针对在人员密集区或相互拥挤场景下进行的行人目标检测时,因行人遮挡或人像交叠所导致的跟踪目标丢失、检测识别率低的问题,提出了一种融合注意力机制的改进 YOLO V5 算法。 通过引入注意力机制来深入挖掘特征通道间关系和特征图空间信息,进一步增强了对行人目标可

    2024年02月01日
    浏览(18)
  • 【D435i深度相机YOLO V5结合实现目标检测】

    参考:Ubutntu下使用realsense d435i(三):使用yolo v5测量目标物中心点三维坐标 欢迎大家阅读2345VOR的博客【D435i深度相机YOLO V5结合实现目标检测】🥳🥳🥳 2345VOR鹏鹏主页: 已获得CSDN《嵌入式领域优质创作者》称号👻👻👻,座右铭:脚踏实地,仰望星空🛹🛹🛹 本文章属于

    2024年02月08日
    浏览(30)
  • 目标检测改进系列1:yolo v5网络中OTA损失函数替换

    标签分配(Label Assignment)标签分配策略是对训练过程中各个Anchor划分正负属性,并分配各自学习目标的策略方法,在整体上通过标签是否是非负即正可以分为硬标签分配和软标签分配。其中,硬标签分配可以分成静态分配策略和动态分配策略两类。 动态 静态分配策略 静态标

    2024年02月13日
    浏览(14)
  • realsense D455深度相机+YOLO V5结合实现目标检测(一)

    realsense D455深度相机+YOLO V5结合实现目标检测(一)

    realsense D455深度相机+YOLO V5结合实现目标检测(二)第二篇链接 可以实现将D435,D455深度相机和yolo v5结合到一起,在识别物体的同时,还能测到物体相对与相机的距离。 说明一下为什么需要做这个事情?1.首先为什么需要用到realsense D455深度相机? 因为他是普通的相机还加了一个

    2024年02月06日
    浏览(10)
  • Python Apex YOLO V5 6.2 目标检测 全过程记录

    Python Apex YOLO V5 6.2 目标检测 全过程记录

    博文目录 效果展示 Python YOLO V5 实时截屏与目标检测 GitHub Windows Python PyCharm 开发环境搭建 Windows Python PyTorch CUDA 11.7 TensorRT 环境配置 先根据上述两篇文章将开发环境和虚拟环境都创建好, 然后下载 YOLO V5 6.2 或 YOLO V5 7.0 (最新) 的源码, 用 PyCharm 打开, 选择刚刚创建的虚拟环境 W

    2024年02月03日
    浏览(43)
  • 使用OpenCV进行YOLO对象检测

    使用OpenCV进行YOLO对象检测

    点击上方“ 小白学视觉 ”,选择加\\\" 星标 \\\"或“ 置顶 ” 什么是YOLO? YOLO 是“You Only Look Once”一词的缩写。这是一种算法,可以(实时)检测和识别图片中的各种对象。YOLO 中的对象检测是作为回归问题完成的,并提供检测到的图像的类别概率。YOLO 算法采用卷积神经网络

    2023年04月21日
    浏览(6)
  • MATLAB基于视频的车辆检测方法

    MATLAB基于视频的车辆检测方法

    摘要 改革开放以后,随着经济的高速发展,交通问题越来越开始影响着人们的生产和生活,由于汽车拥有量的急剧增加,城市交通问题日益严重,因此交通问题开始成为人们关心的社会热点。在我国,近年来,交通事故频繁发生,有效的交通监测和管理已迫在眉睫。 本文主

    2023年04月25日
    浏览(10)
  • 基于OpenCV的车辆检测与记数

    基于OpenCV的车辆检测与记数

    本文提出一种简单有效的基于opencv的车辆检测与计数方法。 首先通过高速公路上的摄像头 获取到一段车流量视频 , 先预处理 :利用灰度线性变换,为了只关注视频中车辆移动的特征,不关注不同车辆的不同颜色的干扰特征; 然后对灰度视频去除背景 ,进一步抑制车辆外的

    2024年02月03日
    浏览(5)
  • 基于opencv深度学习,交通目标检测,行人车辆检测,人流统计,交通流量检测

    基于opencv深度学习,交通目标检测,行人车辆检测,人流统计,交通流量检测

    文章目录 0 前言+ 1. 目标检测概况+ 1.1 什么是目标检测?+ 1.2 发展阶段 2. 行人检测+ 2.1 行人检测简介+ 2.2 行人检测技术难点+ 2.3 行人检测实现效果+ 2.4 关键代码-训练过程 最后 设计项目案例演示地址: 链接 毕业设计代做一对一指导项目方向涵盖: 1.1 什么是目标检测? 目标检

    2024年02月04日
    浏览(12)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包