【YOLO简单测距】单目测距——基于YOLOv5的单目深度估计算法的实现

基于YOLOv5实现的深度估计示例:

结果示例

一、YOLOv5的简单介绍:

YOLOv5是一个在COCO数据集上预训练的物体检测架构和模型系列,由Ultralytics团队对未来视觉AI方法的开源研究。

YOLOv5是YOLO系列的延伸,也可以看作是基于YOLOv3、YOLOv4的改进版本。虽然没有相应的论文说明,但作者积极地在Github上开放源代码,通过分析源码,我们可以快速了解YOLOv5的网络架构和工作原理。

Github源码地址:GitHub - ultralytics/yolov5: YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite

模型权重下载可参考:

http://t.csdnimg.cn/2e8yUicon-default.png?t=O83Ahttp://t.csdnimg.cn/2e8yU

二、深度估计实现原理:

算法原理及公式:

单目深度估计涉及到摄像机的成像原理,特别是如何从图像中的物体尺寸来推算实际距离。这里使用的公式是:

其中各个变量的含义如下:

D -是目标到摄像机的实际距离,这是我们想要计算的最终结果。
F -是摄像机的焦距,这是一个固定值,根据摄像机镜头的规格可以得知。 

W-是目标在现实世界中的实际宽度或高度,这取决于具体情况;例如,在行人检测中,通常使用人的身高作为这个值。
P -是目标在图像中占据的像素数量,可以是宽度也可以是高度,这取决于我们如何测量;这个值由程序计算得出。

解释:

公式的基本思想是利用相似三角形的原理。当一个物体通过摄像机镜头成像时,物体的实际大小与其在图像传感器上投影的大小之间存在比例关系。这个比例关系由摄像机的焦距决定。

1. 焦距 (F): 摄像机的焦距决定了镜头聚焦的距离,焦距越长,视角越窄,能够拍摄到的场景范围越小,但远处的物体显得更大。
2. 目标的实际尺寸 (W): 这是目标在现实世界中的真实大小,如一个人的身高。
3. 目标在图像中的像素尺寸 (P): 这是目标在摄像机拍摄的图像中所占据的像素数。这个值可以通过图像处理软件测量得到。

计算过程:

知道了摄像机的焦距、目标的实际尺寸以及目标在图像中的像素尺寸后,就可以将这些值代入公式 D=(F*W)/P来计算目标到摄像机的实际距离

例如,如果一个摄像机的焦距是50mm,一个人的身高是1.8米,这个人在图像中的高度占据了600像素,那么这个人到摄像机的距离可以这样计算:

这意味着这个人站在摄像机大约150米远的地方。

通过这种方式,我们可以根据图像中的物体尺寸和已知的摄像机参数来估算物体与摄像机之间的距离。这种方法在计算机视觉和机器人导航等领域非常有用。

三、代码实现:

1、utils文件下增加distance.py

# 镜头焦距
foc = 1591
# 行人高度(英寸) 
real_hight_person =66.92   
# 自行车高度(英寸) 
real_hight_bicycle = 43.30 


# 自定义函数,单目测距
def detect_distance_person(h):
    dis_inch = (real_hight_person * foc) / (h - 2)
    dis_cm = dis_inch * 2.54
    dis_cm = int(dis_cm)
    dis_m = dis_cm/100
    return dis_m

def detect_distance_bicycle(h):
    dis_inch = (real_hight_bicycle * foc) / (h - 2)
    dis_cm = dis_inch * 2.54
    dis_cm = int(dis_cm)
    dis_m = dis_cm / 100
    return dis_m
Notice
a、镜头焦距可以根据摄像头的参数自行修改。
b、所有物体都是预设的固定的高度,例如,人的高度固定为:66.92in=170cm  自行车的高度固定为:43.30in=109cm;可以自定义增加检测内容。

2、detect.py文件的修改

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


def detect(save_img=False):
    global modelc
    source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
    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  仅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 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设置为True以加快恒定图像大小推断
        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]

    # 改变显示图片大小(自定义函数)
    def cv_show(p, im0):
        height, width = im0.shape[:2]
        a = 1200 / width  # 宽为1200,计算比例
        size = (1200, int(height * a))

        img_resize = cv2.resize(im0, size, interpolation=cv2.INTER_AREA)
        cv2.imshow(p, img_resize)
        cv2.waitKey(1)  # 1 millisecond

    # Run inference运行推理
    if device.type != 'cpu':
        model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # run once
    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)

        # Inference推理
        t1 = time_synchronized()
        pred = model(img, augment=opt.augment)[0]

        # Apply NMS应用NMS
        pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
        t2 = 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
            s += '%gx%g ' % img.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if len(det):
                # Rescale boxes from img_size to im0 size将框从img_size重新缩放为im0大小
                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):
                    conf2 = float(f'{conf:.2f}')
                    if conf2 > 0.4:   # 置信度小于0.4时不显示
                        # person,显示person标签的框,并单独做person的测距



                        if names[int(cls)] == 'person':
                            if save_txt:  # Write to file写入文件
                                xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(
                                    -1).tolist()  # normalized xywh归一化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
                                label = f'{names[int(cls)]} {conf:.2f}'
                                plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=2,
                                             name=names[int(cls)])   # 画框函数



                        # car,显示car标签的框,并单独做person的测距
                        if names[int(cls)] == 'car':
                            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
                                label = f'{names[int(cls)]} {conf:.2f}'
                                plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3,
                                             name=names[int(cls)])



                        if names[int(cls)] =='bicycle':
                            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
                                label = f'{names[int(cls)]} {conf:.2f}'
                                plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3,
                                             name=names[int(cls)])



            # Print time (inference + NMS)
            print(f'{s}Done. ({t2 - t1:.3f}s)')

            # Stream results,检测后显示出来
            if view_img:
                cv_show(str(p), im0)   # 该自定义函数有resize函数重构图片大小,注意不能在检测之前直接resize图像大小,会影响测距结果

            # Save results (image with detections)保存结果(带有检测的图像)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                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='yolov5s.pt', help='model.pt path(s)')
    parser.add_argument('--source', type=str, default='data/videos/test2.jpg', 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',default=True)
    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')   保存视频或者图片,路径为runs/detect
    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')
    opt = parser.parse_args()
    print(opt)
    check_requirements(exclude=('pycocotools', 'thop'))

    with torch.no_grad():
        if opt.update:  # update all models (to fix SourceChangeWarning)更新所有模型(以修复SourceChangeWarning)
            for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
                detect()
                strip_optimizer(opt.weights)
        else:
            detect()

3、polts.py文件的修改:

在utils目录下的polts.py文件的第59行,对函数进行了修改,添加了一个名为name的参数。根据name的值(人或车),函数会在画框时调用相应的测距函数(第68行和第70行,其中h表示目标的高度,第63至65行通过方框坐标计算得出)。这些测距函数是在之前定义好的distance.py文件中的。在第71行,将测距得到的距离数据追加到原本的方框标签上。

def plot_one_box(x, img, color=None, label=None, line_thickness=3, name=None):
c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))   # 传过来的x包含有框的两个对角坐标
# w = int(x[2]) - int(x[0])   # 框的宽
h = int(x[3]) - int(x[1])     # 框的高
dis_m = 1.00
    if name == 'person':    # 根据标签名称调用不同函数计算距离
        dis_m = detect_distance_person(h)
    elif name == 'car':
        dis_m = detect_distance_car(h)
    label += f'  {dis_m}m'   # 在标签后追加距离

4、运行detect.py代码即可: 

<think>好的,用户想了解如何使用YOLOv5进行离测量的实现方法。首先,我需要回忆一下相关的知识。YOLOv5本身是一个目标检测模型,主要用于识别图像中的物体并给出边界框。而离测量通常需要结合深度信息,比如单目深度估计或者立体视觉。根据用户提供的引用,特别是引用[1]和[2],里面提到了使用YOLOv5结合单目深度估计来进行离测量。 首先,我得整理出实现步骤。可能包括数据准备、模型训练、深度估计离计算这几个部分。用户提供的引用里提到需要安装库和工具,比如PyTorch、YOLOv5代码库、深度估计库如MiDaS或DPT。然后需要准备数据,包括校准相机参数,这对目测很关键,因为需要焦和传感器尺寸来计算真实离。 接下来是模型训练,用户可能需要用YOLOv5检测车辆或其他目标,然后结合深度图来获取目标的深度值。这里需要注意,YOLOv5输出的边界框中心点坐标需要映射到深度图上对应的位置,从而得到该点的深度值。然后根据相机内参和几何关系计算离。 然后要处理如何将检测框与深度信息结合。可能需要同步处理目标检测和深度估计,比如在检测到目标后,从深度图中提取对应区域的深度数据,再计算平均或中心点的深度值。这里需要代码示例,比如在检测循环中获取深度图,然后根据检测框的位置提取深度信息。 还需要考虑可视化的部分,比如在图像上标注离信息,这样用户可以看到效果。引用中提到了生成深度图和离测量图,可能需要使用OpenCV来绘制文本和边框。 另外,用户可能关心优化方法,比如如何提高测距精度。引用[3]提到YOLOv5使用了CIoU损失函数,这可能影响检测框的准确性,从而间接影响离测量的精度。所以优化检测模型本身也是关键。 最后,应该提醒用户注意相机校准的重要性,因为目测高度依赖准确的焦和传感器参数。如果校准不准确,离估算会有较大误差。同时,环境因素如光线、遮挡等也会影响深度估计的准确性,可能需要预处理或后处理步骤来优化结果。 总结一下,回答的结构应该是步骤分解,每个步骤说明需要做什么,并提供代码示例,然后给出注意事项和相关问题。需要确保引用正确的来源,比如引用[1]和[2]提到的实现步骤和结合方法。同时,代码部分要符合用户的要求,使用正确的格式,并解释关键部分的作用,比如如何从深度图获取离值。</think>### YOLOv5离测量实现方法 使用YOLOv5实现车辆离测量需要结合目标检测和单目深度估计技术,主要流程如下: $$离公式:D = \frac{f \times H}{h}$$ 其中$f$为焦,$H$为物体实际高度,$h$为像素高度[^1] **实现步骤:** 1. **环境配置** ```bash git clone https://github.com/ultralytics/yolov5 pip install -r yolov5/requirements.txt pip install opencv-python torchvision midas-py ``` 2. **数据准备** - 采集包含标定物的道路场景图像 - 获取相机参数:焦$f$、传感器尺寸$s$ - 标注车辆检测框并记录真实离数据 3. **目标检测实现** ```python import torch model = torch.hub.load('ultralytics/yolov5', 'yolov5s') results = model(img) detections = results.pandas().xyxy[0] # 获取检测结果 ``` 4. **深度估计集成(以MiDaS为例)** ```python midas = torch.hub.load('intel-isl/MiDaS', 'MiDaS_small') depth_map = midas(torch.tensor(img).unsqueeze(0)) ``` 5. **离计算核心逻辑** ```python for _, row in detections.iterrows(): x_center = (row.xmin + row.xmax) / 2 y_center = (row.ymin + row.ymax) / 2 depth = depth_map[0, int(y_center), int(x_center)] distance = (f * real_height) / (row.ymax - row.ymin) # 需预先校准 ``` **可视化实现** ```python cv2.putText(img, f"{distance:.2f}m", (int(x_center), int(y_center)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 2) ``` **关键优化点** 1. 使用CIoU损失函数提升检测框精度[^3] 2. 融合多帧深度信息提升稳定性 3. 建立车辆类型-尺寸映射表(轿车/卡车等) 4. 使用标定板进行相机参数动态校准 **注意事项** - 测量精度受限于检测框质量与深度估计准确性 - 需保证检测目标底部接触地面平面 - 建议测量离范围在5-50米之间 - 不同光照条件需重新校准参数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值