YOLOv7测距+碰撞检测

news2024/10/7 10:19:27

YOLOv7测距+碰撞检测

  • 1. 相关配置
  • 2. 测距原理
  • 3. 标定和测距
  • 4. 碰撞检测
    • 4.1 相关代码
    • 4.2 主代码
  • 5. 实验效果

相关链接
1. YOLOV5 + 单目测距(python)
2. YOLOV7 + 单目测距(python)
3. 具体实现效果已在Bilibili发布,点击跳转

本篇博文工程源码下载见文章末尾

1. 相关配置

系统:win 10
YOLO版本:yolov7
拍摄视频设备:安卓手机
电脑显卡:NVIDIA 2080Ti(CPU也可以跑,GPU只是起到加速推理效果)

2. 测距原理

单目测距原理相较于双目十分简单,无需进行立体匹配,仅需利用下边公式线性转换即可:

                                        D = (F*W)/P

其中D是目标到摄像机的距离, F是摄像机焦距(焦距需要自己进行标定获取), W是目标的宽度或者高度(行人检测一般以人的身高为基准), P是指目标在图像中所占据的像素

了解基本原理后,下边就进行实操阶段

3. 标定和测距

具体方法步骤在 YOLOV7 + 单目测距(python)这篇文章已经写过,大家可以移步此文

4. 碰撞检测

碰撞检测也可换成风险检测,无非是设置距离阈值,当距离在一定范围为安全距离,小于阈值为高风险或者碰撞

4.1 相关代码

代码中设置距离 dis_m<8 为高风险,系统显示红框,反之显示绿框

if save_img or view_img:  # Add bbox to image
      x1 = int(xyxy[0])  # 获取四个边框坐标
      y1 = int(xyxy[1])
      x2 = int(xyxy[2])
      y2 = int(xyxy[3])
      h = y2 - y1
      label = f'{names[int(cls)]} {conf:.2f}'
      if label is not None:
          if (label.split())[0] == 'car':
              dis_m = person_distance(h)  # 调用函数,计算行人实际高度
              label += f'  {dis_m}m'  # 将行人距离显示写在标签后
              if dis_m < 8:
                  plot_one_box(xyxy, im0, label=label, color=(0, 0, 255), line_thickness=1)
              else:
                  plot_one_box(xyxy, im0, label=label, color=(0, 255, 0), line_thickness=1)

请添加图片描述

4.2 主代码

import argparse
import time
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
    scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path
from utils.plots import plot_one_box
from utils.torch_utils import select_device, load_classifier, time_synchronized, TracedModel
from distance import person_distance,car_distance

def detect(save_img=False):
    source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
    save_img = not opt.nosave and not source.endswith('.txt')  # save inference images
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://', 'https://'))

    # Directories
    save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Initialize
    set_logging()
    device = select_device(opt.device)
    half = device.type != 'cpu'  # half precision only supported on CUDA

    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    stride = int(model.stride.max())  # model stride
    imgsz = check_img_size(imgsz, s=stride)  # check img_size

    if trace:
        model = TracedModel(model, device, opt.img_size)

    if half:
        model.half()  # to FP16

    # Second-stage classifier
    classify = False
    if classify:
        modelc = load_classifier(name='resnet101', n=2)  # initialize
        modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()

    # Set Dataloader
    vid_path, vid_writer = None, None
    if webcam:
        view_img = check_imshow()
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride)
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride)

    # Get names and colors
    names = model.module.names if hasattr(model, 'module') else model.names
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]

    # Run inference
    if device.type != 'cpu':
        model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # run once
    old_img_w = old_img_h = imgsz
    old_img_b = 1

    t0 = time.time()
    for path, img, im0s, vid_cap in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.half() if half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)

        # Warmup
        if device.type != 'cpu' and (old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
            old_img_b = img.shape[0]
            old_img_h = img.shape[2]
            old_img_w = img.shape[3]
            for i in range(3):
                model(img, augment=opt.augment)[0]

        # Inference
        t1 = time_synchronized()
        with torch.no_grad():   # Calculating gradients would cause a GPU memory leak
            pred = model(img, augment=opt.augment)[0]
        t2 = time_synchronized()

        # Apply NMS
        pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
        t3 = time_synchronized()

        # Apply Classifier
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)

        # Process detections
        for i, det in enumerate(pred):  # detections per image
            if webcam:  # batch_size >= 1
                p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
            else:
                p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # img.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # img.txt
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)  # label format
                        with open(txt_path + '.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or view_img:  # Add bbox to image
                        x1 = int(xyxy[0])  # 获取四个边框坐标
                        y1 = int(xyxy[1])
                        x2 = int(xyxy[2])
                        y2 = int(xyxy[3])
                        h = y2 - y1
                        label = f'{names[int(cls)]} {conf:.2f}'
                        if label is not None:
                            if (label.split())[0] == 'car':
                                dis_m = person_distance(h)  # 调用函数,计算行人实际高度
                                label += f'  {dis_m}m'  # 将行人距离显示写在标签后
                                if dis_m < 8:
                                    plot_one_box(xyxy, im0, label=label, color=(0, 0, 255), line_thickness=1)
                                else:
                                    plot_one_box(xyxy, im0, label=label, color=(0, 255, 0), line_thickness=1)

            # Print time (inference + NMS)
            print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')

            # Stream results
            if view_img:
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                    print(f" The image with the result is saved in: {save_path}")
                else:  # 'video' or 'stream'
                    if vid_path != save_path:  # new video
                        vid_path = save_path
                        if isinstance(vid_writer, cv2.VideoWriter):
                            vid_writer.release()  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                            save_path += '.mp4'
                        vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer.write(im0)

    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        #print(f"Results saved to {save_dir}{s}")

    print(f'Done. ({time.time() - t0:.3f}s)')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)')
    parser.add_argument('--source', type=str, default='inference/images', help='source')  # file/folder, 0 for webcam
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='display results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default='runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--no-trace', action='store_true', help='don`t trace model')
    opt = parser.parse_args()
    print(opt)
    #check_requirements(exclude=('pycocotools', 'thop'))

    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)
            for opt.weights in ['yolov7.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

5. 实验效果

实验效果如下,如果把相机架在车上,效果会更好

YOLOv7测距+碰撞检测

工程源码下载链接:https://github.com/up-up-up-up/yolov7_Monocular_security_testing

更多测距代码见博客主页

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/496068.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

vscode+gdbserver实现图形化调试Linux应用

一、环境&#xff1a; 1.远程Linux主机Ubuntu22.04&#xff1b; 2.vscode 1.76 二、环境搭建 1.Ubuntu 安装gdb、gdbserver、openssh-server 2.vscode 安装Remote Development、C/C 3.远程连接Linux 点击左下角的绿色按钮&#xff0c;然后选择connect to host----->…

Day1 组队竞赛、删除公共字符

✨个人主页&#xff1a; 北 海 &#x1f389;所属专栏&#xff1a; C/C相关题解 &#x1f383;操作环境&#xff1a; Visual Studio 2019 版本 16.11.17 文章目录 选择题1.C基础语法 编程题组队竞赛删除公共字符 选择题 1.C基础语法 题目&#xff1a;以下程序的运行结果是&am…

RSA加密为什么能保证安全

问题&#xff1a;我们都知道RSA加密是安全的&#xff0c;但是我们在使用的使用&#xff0c;怎么使用才能保证数据的安全传输呢&#xff1f; 一、原则&#xff1a;公钥机密、私钥解密、私钥签名、公钥验签 公钥私钥都可以加密和解密数据&#xff0c;但是因为持有公钥和私钥的人…

【Elsevier】中科院2区TOP, 高被引119篇, 稳定检索22年, 1周可见刊,5月15截稿~

一、【期刊简介】 中科院2区软计算类SCI (TOP) 【期刊概况】IF:8.0-9.0, JCR1区, 中科院2区&#xff1b; 【终审周期】走期刊部系统&#xff0c;3-5个月左右录用&#xff1b; 【检索情况】SCI&EI双检&#xff1b;正刊&#xff1b; 【数据库收录年份】2001年&#xff1…

【测试】概念篇

目录 &#x1f31f;一、了解软件测试 &#x1f308;1、什么是软件测试 &#x1f308;2、软件测试与开发的区别&#xff08;常考&#xff09; &#x1f308;3、一个优秀的软件测试人员应该具备的素质 &#x1f31f;二、需求与测试用例、软件错误&#xff0c;软件生…

一旦80%的开发人员都开始利用ChatGPT提升工作效率后,挑战与机遇在哪里?

其实我现在已经开始逐渐开始喜欢上ChatGPT了&#xff0c;上班时间摸摸鱼&#xff0c;和ChatGPT畅谈一下理想&#xff0c;遇见一些不太熟练的代码也懒得去上网查了&#xff0c;直接问一问ChatGPT&#xff0c;然后自己再放置到自己的代码里&#xff0c;改一改&#xff0c;很完美。…

快递出入库管理APP开发 收发快递更方便

网购的盛行让收发快递成为很多人日常生活必不可少的一个环节&#xff0c;对于快递公司来说&#xff0c;每天有那么多的快递&#xff0c;如果没有一个好用的管理系统的话&#xff0c;不仅麻烦还很容易出现纰漏&#xff0c;所以快递出入库管理APP软件就显得很必要了。 快递…

python-imageio库简单使用

目录 imread_v2() get_reader() 使用imageio方法将彩色视频变为黑白视频 相关&#xff1a;python-动图制作及分解_觅远的博客-CSDN博客 imageio是一个用于读取和写入图像及视频数据的库&#xff0c;支持多种格式&#xff0c;且可以使用NumPy数组进行操作。常用方法&#xff…

JS逆向 -- 某平台登录加密分析

一、打开网站&#xff0c;使用账号密码登录 账号&#xff1a;aiyou123.com 密码&#xff1a;123456 二、通过F12抓包&#xff0c;抓到如下数据&#xff0c;发现密码加密了 三、加密结果是32位&#xff0c;首先考虑是md5加密。 四、全局搜索pwd&#xff0c;点击右上角&#xf…

C# 纯text文本字符添加上下角标

工作的需求&#xff0c;需要在GridView列HeaderText中插入带入带有上标和下标的字符串&#xff0c;比如这样的一个字符串&#xff1a;。。 解决办法&#xff1a;使用转义字符加Unicode的NumEntity就可以实现了。定义字符串如下&#xff1a;"O"。其中O为 。 实现&…

Linux系统目录树结构以及解释

FHS标准 Filesystem Hierarchy Standard&#xff08;文件系统层次化标准&#xff09;的缩写&#xff0c;多数Linux版本采用这种文件组织形式&#xff0c;类似于Windows操作系统中c盘的文件目录&#xff0c;FHS采用树形结构组织文件。FHS定义了系统中每个区域的用途、所需要的最…

rk平台调试音频(从驱动到apk)

需要实现的功能&#xff1a; 输入&#xff1a;hdmiin、uvc、mic可以实时切换 输出&#xff1a;耳机和HDMI OUT同时输出声音 这里注意&#xff1a;mic是存在hedset情况&#xff0c;4节耳机&#xff0c;即可输出又可输出同时进行 开发情况&#xff1a; 一、先熟悉大致的Andro…

【24】核心易中期刊推荐——图像处理研究大数据及智能处理研究

🚀🚀🚀NEW!!!核心易中期刊推荐栏目来啦 ~ 📚🍀 核心期刊在国内的应用范围非常广,核心期刊发表论文是国内很多作者晋升的硬性要求,并且在国内属于顶尖论文发表,具有很高的学术价值。在中文核心目录体系中,权威代表有CSSCI、CSCD和北大核心。其中,中文期刊的数…

springboot内嵌tomcat文件上传路径不存在问题原因

错误提示: 临时文件目录被删除,导致文件上传报错,我们使用的是linux系统,10天没有使用,就会被删除 代码: 解决办法: 配置文件中自定义临时文件上传目录 server:port: 9090tomcat:basedir: /crm/tmp 特殊情况: 当我上传小文件的时候可以上传成功,大文件的时候上传失败 猜测可…

利用Linux的corntab定时任务和shell脚本,解决傻妞卡死、发信息没反应、一直卡在即将重启、查询数据异常等问题

利用Linux的corntab定时任务和shell脚本&#xff0c;解决傻妞卡死、数据异常等问题 安装corntab创建shell脚本添加corntab定时任务 原理 定时杀死傻妞进程&#xff0c;并自动重启傻妞 安装corntab Linux crontab是用来定期执行程序的命令。 CentOS安装命令如下 yum -y insta…

【Android -- 开发工具】Source Insight 4.0 安装和使用教程

简介 Source Insight 工具是一款功能强大的代码阅读器&#xff0c;它能使大量的代码产生联系&#xff0c;方便阅读&#xff0c;而且支持各种语言的程序代码。 安装 & 激活 1. 下载 下载地址 直接点击下载即可&#xff0c;我下载的是 4.0 版本。 然后按照步骤安装完成即…

chatGPT给出Python time.sleep()假死(挂起)的解决办法

1. time.sleep()假死&#xff08;挂起&#xff09;的原因与解决办法 最近&#xff0c;使用chatGPT帮着写程序&#xff0c;完成通过API获取天气数据的程序&#xff0c;运行起来后出现了状况&#xff1a;莫名其妙的的假死&#xff08;程序被挂起来&#xff0c;不执行了&#xff…

项目结构如何改造(利用RuoYi-Vue脚手架开发一个健身房会员管理系统,改造项目结构)

项目结构如何改造&#xff08;利用RuoYi-Vue脚手架开发一个健身房会员管理系统&#xff0c;改造项目结构&#xff09; 1. 全局查找替换&#xff08;Ctrl Shift R&#xff09;2. 全局查找替换版本号3. 全局查找替换模块名4. 修改项目名5. ShiftF6 重命名模块6. ShiftF6 重命名…

Nginx配置使用GeoIP2模块

一、Nginx简介 Nginx(engine x)是一个免费的、开源的、高性能的HTTP和反向代理服务器&#xff0c;也是一个IMAP/POP3/SMTP服务器。Nginx是由伊戈尔赛索耶夫为俄罗斯访问量第二的Rambler.ru站点&#xff08;俄文&#xff1a;Рамблер&#xff09;开发的&#xff0c;第一个…

不废话!CentOS 8 安装docker的详细过程

目录 1.更新系统 2. 安装依赖包 3.添加 Docker YUM 仓库 4.安装 Docker 5.启动 Docker 6.设置 Docker 开机自启 7.测试 Docker 1.更新系统 dnf update 这里直接输入y&#xff0c;耐心等待更新即可 直到看到complete表示更新完毕 2. 安装依赖包 Docker 需要一些依赖包才能正常…