YOLOV8 + 双目测距

news/2024/7/11 1:48:27 标签: YOLO, 数码相机

YOLOV8 + 双目测距

  • 1. 环境配置
  • 2. 测距流程和原理
    • 2.1 测距流程
    • 2.2 测距原理
  • 3. 代码部分解析
    • 3.1 相机参数stereoconfig.py
    • 3.2 测距部分
    • 3.3 主代码yolov8-stereo.py
  • 4. 实验结果
    • 4.1 测距
    • 4.2 测距+跟踪
    • 4.3 测距+跟踪+分割
    • 4.4 视频展示

相关文章
1. YOLOv5+双目测距(python)
2. YOLOv7+双目测距(python)

如果有用zed相机,可以进我主页👇👇👇直接调用内部相机参数,精度比双目测距好很多
https://blog.csdn.net/qq_45077760

下载链接(求STAR):https://github.com/up-up-up-up/YOLOv8-stereo

1. 环境配置

具体可见: Windows+YOLOV8环境配置

2. 测距流程和原理

2.1 测距流程

大致流程: 双目标定→双目校正→立体匹配→结合yolov8→深度测距

  1. 找到目标识别源代码中输出物体坐标框的代码段。
  2. 找到双目测距代码中计算物体深度的代码段。
  3. 将步骤2与步骤1结合,计算得到目标框中物体的深度。
  4. 找到目标识别网络中显示障碍物种类的代码段,将深度值添加到里面,进行显示

注:我所做的是在20m以内的检测,没计算过具体误差,当然标定误差越小精度会好一点,其次注意光线、亮度等影响因素,当然检测范围效果跟相机的好坏也有很大关系
在这里插入图片描述

2.2 测距原理

如果想了解双目测距原理,请移步该文章 双目三维测距(python)

3. 代码部分解析

3.1 相机参数stereoconfig.py

双目相机标定误差越小越好,我这里误差为0.1,尽量使误差在0.2以下

import numpy as np
# 双目相机参数
class stereoCamera(object):
    def __init__(self):

        self.cam_matrix_left = np.array([[1101.89299, 0, 1119.89634],
                                         [0, 1100.75252, 636.75282],
                                         [0, 0, 1]])
        self.cam_matrix_right = np.array([[1091.11026, 0, 1117.16592],
                                          [0, 1090.53772, 633.28256],
                                          [0, 0, 1]])

        self.distortion_l = np.array([[-0.08369, 0.05367, -0.00138, -0.0009, 0]])
        self.distortion_r = np.array([[-0.09585, 0.07391, -0.00065, -0.00083, 0]])

        self.R = np.array([[1.0000, -0.000603116945856524, 0.00377055351856816],
                           [0.000608108737333211, 1.0000, -0.00132288199083992],
                           [-0.00376975166958581, 0.00132516525298933, 1.0000]])

        self.T = np.array([[-119.99423], [-0.22807], [0.18540]])
        self.baseline = 119.99423  

3.2 测距部分

这一部分我用了多线程加快速度,计算目标检测框中心点的深度值

config = stereoconfig_040_2.stereoCamera()
map1x, map1y, map2x, map2y, Q = getRectifyTransform(720, 1280, config)
thread = MyThread(stereo_threading, args=(config, im0, map1x, map1y, map2x, map2y, Q))
thread.start()
results = model.predict(im0, save=False, conf=0.5)
annotated_frame = results[0].plot()
boxes = results[0].boxes.xywh.cpu()
for i, box in enumerate(boxes):
    # for box, class_idx in zip(boxes, classes):
    x_center, y_center, width, height = box.tolist()
    x1 = x_center - width / 2
    y1 = y_center - height / 2
    x2 = x_center + width / 2
    y2 = y_center + height / 2
    if (0 < x2 < 1280):
        thread.join()
        points_3d = thread.get_result()
        # gol.set_value('points_3d', points_3d)
        a = points_3d[int(y_center), int(x_center), 0] / 1000
        b = points_3d[int(y_center), int(x_center), 1] / 1000
        c = points_3d[int(y_center), int(x_center), 2] / 1000
        distance = ((a ** 2 + b ** 2 + c ** 2) ** 0.5)

3.3 主代码yolov8-stereo.py

(1)加入了多线程处理,加快处理速度
(2)如果想打开相机,直接把cap = cv2.VideoCapture(‘a1.mp4’)改成cap = cv2.VideoCapture(0)即可

import cv2
import torch
import argparse
from ultralytics import YOLO
from stereo import stereoconfig_040_2
from stereo.stereo import stereo_40
from stereo.stereo import stereo_threading, MyThread
from stereo.dianyuntu_yolo import preprocess, undistortion, getRectifyTransform, draw_line, rectifyImage, \
    stereoMatchSGBM

def main():
    cap = cv2.VideoCapture('ultralytics/assets/a1.mp4')
    model = YOLO('yolov8n.pt')
    cv2.namedWindow('00', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('00', 1280, 360)  # 设置宽高
    out_video = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), 30, (2560, 720))
    while True:
        ret, im0 = cap.read()
        if not ret:
            print("Video frame is empty or video processing has been successfully completed.")
            break
        # img = cv2.cvtColor(image_net, cv2.COLOR_BGRA2BGR)
        config = stereoconfig_040_2.stereoCamera()
        map1x, map1y, map2x, map2y, Q = getRectifyTransform(720, 1280, config)
        thread = MyThread(stereo_threading, args=(config, im0, map1x, map1y, map2x, map2y, Q))
        thread.start()
        results = model.predict(im0, save=False, conf=0.5)
        annotated_frame = results[0].plot()
        boxes = results[0].boxes.xywh.cpu()
        for i, box in enumerate(boxes):
            # for box, class_idx in zip(boxes, classes):
            x_center, y_center, width, height = box.tolist()
            x1 = x_center - width / 2
            y1 = y_center - height / 2
            x2 = x_center + width / 2
            y2 = y_center + height / 2
            if (0 < x2 < 1280):
                thread.join()
                points_3d = thread.get_result()
                # gol.set_value('points_3d', points_3d)
                a = points_3d[int(y_center), int(x_center), 0] / 1000
                b = points_3d[int(y_center), int(x_center), 1] / 1000
                c = points_3d[int(y_center), int(x_center), 2] / 1000
                distance = ((a ** 2 + b ** 2 + c ** 2) ** 0.5)
                if (distance != 0):
                    text_dis_avg = "dis:%0.2fm" % distance
                    cv2.putText(annotated_frame, text_dis_avg, (int(x2 + 5), int(y1 + 30)), cv2.FONT_ITALIC, 1.2,
                                (0, 255, 255), 3)
        cv2.imshow('00', annotated_frame)
        out_video.write(annotated_frame)
        key = cv2.waitKey(1)
        if key == 'q':
            break
    out_video.release()
    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', type=str, default='yolov8n.pt', help='model.pt path(s)')
    parser.add_argument('--svo', type=str, default=None, help='optional svo file')
    parser.add_argument('--img_size', type=int, default=416, help='inference size (pixels)')
    parser.add_argument('--conf_thres', type=float, default=0.4, help='object confidence threshold')
    opt = parser.parse_args()

    with torch.no_grad():
        main()

4. 实验结果

可实现测距、跟踪和分割功能,实现不同功能仅需修改以下代码,具体见 此篇文章

4.1 测距

在这里插入图片描述

4.2 测距+跟踪

在这里插入图片描述

4.3 测距+跟踪+分割

在这里插入图片描述

4.4 视频展示


http://www.niftyadmin.cn/n/5474849.html

相关文章

2.接口自动化测试学习-执行excel测试用例

1.接口自动化测试规划 编程语言 编程工具 自动化测试框架&#xff1a;pytest 报告可视化&#xff1a;allure 持续方案&#xff1a;CI持续集成-jenkins 仓库服务器&#xff08;自动化执行&#xff09;&#xff1a;github/gitlab/gitee 测试管理工具&#xff1a;jira 2.项目代码…

详解事件循环

浏览器的进程模型 何为进程&#xff1f; 程序运行需要有它自己专属的内存空间&#xff0c;可以把这块内存空间简单的理解为进程 每个应用至少有一个进程&#xff0c;进程之间相互独立&#xff0c;即使要通信&#xff0c;也需要双方同意。 何为线程 &#xff1f; 有了进程后…

uniapp - 微信小程序 - 使用uCharts的一些问题

文章目录 uniapp - 微信小程序 - 使用uCharts的一些问题一、开发者工具显示正常&#xff0c;真机调试统计图不随页面滚动二、数据过多开启滚动条&#xff0c;无法滑动滚动条三、饼图点击不显示提示窗/点击位置bug、多个同类型统计图点击不显示提示框问题四、 formatter 自定义 …

基于Spring Boot的汽车租赁系统设计与实现

基于Spring Boot的汽车租赁系统设计与实现 开发语言&#xff1a;Java框架&#xff1a;springbootJDK版本&#xff1a;JDK1.8数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/idea 系统部分展示 租赁订单列表管理&#xff0c;在租赁订单列表管理可以查…

【Unity每日一记】鼠标相关API

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;uni…

后端开发教程

一、基础准备 编程语言选择&#xff1a;对于后端开发&#xff0c;常见的编程语言有Java、Python、Ruby、PHP、C#等。这些语言各有特点&#xff0c;如Java以其稳定性和跨平台性被广泛使用&#xff0c;Python则以其简洁易读的语法和丰富的库受到开发者的喜爱。选择哪种语言取决于…

maven deploy 400 Bad Request 问题解决

1.deloy 400报错 首先我们要搞懂Nexus中的 type类型 group:group的意思也就是把所有仓库分为一个组,什么意思呢,就是我现在有central和releases和snapshots这3个仓库, 这三个type都是不同的,也是比如我把本地的项目打成jar包放到releases中 我拉取的时候 我们配的是 public…

【论文速读】| 大语言模型平台安全:将系统评估框架应用于OpenAI的ChatGPT插件

本次分享论文为&#xff1a;LLM Platform Security: Applying a Systematic Evaluation Framework to OpenAI’s ChatGPT Plugins 基本信息 原文作者&#xff1a;Umar Iqbal, Tadayoshi Kohno, Franziska Roesner 作者单位&#xff1a;华盛顿大学圣路易斯分校&#xff0c;华盛…