YOLO v5与双目测距结合,实现目标的识别和定位测距

article/2025/10/12 14:34:49

YOLO v5与双目测距结合,实现目标的识别和定位测距

  • 1、首先安装YOLO v5
  • 2、数据集的标定
  • 3、双目测距代码的单独运行调试
  • 4、YOLO v5与双目测距的代码的结合
  • 5、最终识别测距效果
  • 6、代码下载调试运行
  • 7、最终演示视频
      • 欢迎各位点赞投币收藏哦🤣🤣🤣![【毕业设计-基于YOLO V5智能追踪记录装置的设计-哔哩哔哩】https://b23.tv/iTkkRJ](https://b23.tv/iTkkRJ)
  • 8、需要指导的小伙伴可以加我QQ哦~

系统环境:VMware Fusion 虚拟机 Ubuntu18.04
CPU: intel core i7 8750H
python版本:python3.6.13(anaconda安装的python3.6的虚拟环境)
yolov5模型版本:YOLO v5s
双目摄像头间距:12cm
双目摄像头焦距:100度/3mm
双目摄像头输出分辨率为:2560*720。

1、首先安装YOLO v5

YOLO v5的安装请参考我的另一篇博客:https://blog.csdn.net/qq_40700822/article/details/118487596

2、数据集的标定

参考我的另一篇博客:https://blog.csdn.net/qq_40700822/article/details/118550250

3、双目测距代码的单独运行调试

参考我的另一篇博客:https://blog.csdn.net/qq_40700822/article/details/115765728

4、YOLO v5与双目测距的代码的结合

我用的双目相机长这样,某宝220元购入的。
在这里插入图片描述

要想将双目测距的代码加入到YOLO v5中,就需要将YOLO v5检测目标的代码看懂,这部分学起来对我来说是比较吃力的。

我这里的结合用的比较简单,就是把双目测距的代码加入到了yolov5的detect.py中。具体加在了打印目标框的位置,如下代码所示。

detect_and_strereo_video_003.py

 # -*- coding: utf-8 -*-
import argparse
import time
from pathlib import Pathimport cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import randomimport numpy as np 
from PIL import Image, ImageDraw, ImageFontfrom 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_synchronizedfrom stereo.dianyuntu_yolo import preprocess, undistortion, getRectifyTransform, draw_line, rectifyImage,\stereoMatchSGBM, hw3ToN3, DepthColor2Cloud, view_cloudfrom stereo import stereoconfig_040_2num = 210 #207 209 210 211
def detect(save_img=False):num = 210source, weights, view_img, save_txt, imgsz = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_sizewebcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(('rtsp://', 'rtmp://', 'http://') )# Directoriessave_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# Initializeset_logging()device = select_device(opt.device)half = device.type != 'cpu'  # half precision only supported on CUDA# Load modelmodel = attempt_load(weights, map_location=device)  # load FP32 modelstride = int(model.stride.max())  # model strideimgsz = check_img_size(imgsz, s=stride)  # check img_sizeif half:model.half()  # to FP16# Second-stage classifierclassify = Falseif classify:modelc = load_classifier(name='resnet101', n=2)  # initializemodelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()# Set Dataloadervid_path, vid_writer = None, Noneif webcam:view_img = check_imshow()cudnn.benchmark = True  # set True to speed up constant image size inferencedataset = LoadStreams(source, img_size=imgsz, stride=stride)else:save_img = Truedataset = LoadImages(source, img_size=imgsz, stride=stride)print("img_size:")print(imgsz)# Get names and colorsnames = model.module.names if hasattr(model, 'module') else model.namescolors = [[random.randint(0, 255) for _ in range(3)] for _ in names]# Run inferenceif device.type != 'cpu':model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # run oncet0 = 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/32img /= 255.0  # 0 - 255 to 0.0 - 1.0if img.ndimension() == 3:img = img.unsqueeze(0)# Inferencet1 = time_synchronized()pred = model(img, augment=opt.augment)[0]# Apply NMSpred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)t2 = time_synchronized()# Apply Classifierif classify:pred = apply_classifier(pred, modelc, img, im0s)# Process detectionsfor i, det in enumerate(pred):  # detections per imageif webcam:  # batch_size >= 1p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.countelse:p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)p = Path(p)  # to Pathsave_path = str(save_dir / p.name)  # img.jpgtxt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # img.txts += '%gx%g ' % img.shape[2:]  # print stringgn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwhif len(det):# Rescale boxes from img_size to im0 sizedet[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()# Print resultsfor c in det[:, -1].unique():n = (det[:, -1] == c).sum()  # detections per classs += f"{n} {names[int(c)]} {'s' * (n > 1)} , "  # add to string# Write resultsfor *xyxy, conf, cls in reversed(det):if save_txt:  # Write to filexywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywhprint("xywh  x : %d, y : %d"%(xywh[0],xywh[1]) )line = (cls, *xywh, conf) if opt.save_conf else (cls, *xywh)  # label formatwith open(txt_path + '.txt', 'a') as f:f.write(('%g ' * len(line)).rstrip() % line + '\n')if save_img or view_img:  # Add bbox to imagelabel = f'{names[int(cls)]} {conf:.2f} 'plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)##print label x,y zuobiao x = (xyxy[0] + xyxy[2]) / 2y = (xyxy[1] + xyxy[3]) / 2#print(" %s is  x: %d y: %d " %(label,x,y) )height_0, width_0 = im0.shape[0:2]if (x <= int(width_0/2) ):t3 = time_synchronized()#################################stereo codep = numstring = ''#print("P is %d" %p )# 读取数据集的图片#iml = cv2.imread('./stereo/yolo/zuo/%szuo%d.bmp' %(string,p) )  # 左图#imr = cv2.imread('./stereo/yolo/you/%syou%d.bmp' %(string,p) )  # 右图#iml = cv2.imread('./stereo/yolo/zuo/%szuo%d.bmp' %(string,p) )  # 左图#imr = cv2.imread('./stereo/yolo/you/%syou%d.bmp' %(string,p) )  # 右图#height_0, width_0 = im0.shape[0:2]#print("width_0 =  %d "  % width_0)#print("height_0 = %d "  % height_0)iml = im0[0:int(height_0), 0:int(width_0/2)]imr = im0[0:int(height_0), int(width_0/2):int(width_0) ]height, width = iml.shape[0:2]#cv2.imshow("iml",iml)#cv2.imshow("imr",im0)#cv2.waitKey(0)#print("width =  %d "  % width)#print("height = %d "  % height)# 读取相机内参和外参config = stereoconfig_040_2.stereoCamera()# 立体校正map1x, map1y, map2x, map2y, Q = getRectifyTransform(height, width, config)  # 获取用于畸变校正和立体校正的映射矩阵以及用于计算像素空间坐标的重投影矩阵#print("Print Q!")#print("Q[2,3]:%.3f"%Q[2,3])iml_rectified, imr_rectified = rectifyImage(iml, imr, map1x, map1y, map2x, map2y)# 绘制等间距平行线,检查立体校正的效果line = draw_line(iml_rectified, imr_rectified)#cv2.imwrite('./yolo/%s检验%d.png' %(string,p), line)# 消除畸变iml = undistortion(iml, config.cam_matrix_left, config.distortion_l)imr = undistortion(imr, config.cam_matrix_right, config.distortion_r)# 立体匹配iml_, imr_ = preprocess(iml, imr)  # 预处理,一般可以削弱光照不均的影响,不做也可以iml_rectified_l, imr_rectified_r = rectifyImage(iml_, imr_, map1x, map1y, map2x, map2y)disp, _ = stereoMatchSGBM(iml_rectified_l, imr_rectified_r, True) #cv2.imwrite('./yolo/%s视差%d.png' %(string,p), disp)# 计算像素点的3D坐标(左相机坐标系下)points_3d = cv2.reprojectImageTo3D(disp, Q)  # 可以使用上文的stereo_config.py给出的参数#points_3d = points_3d'''#print("x is :%.3f" %points_3d[int(y), int(x), 0] )print('点 (%d, %d) 的三维坐标 (x:%.3fcm, y:%.3fcm, z:%.3fcm)' % (int(x), int(y), points_3d[int(y), int(x), 0]/10, points_3d[int(y), int(x), 1]/10, points_3d[int(y), int(x), 2]/10) )'''count = 0#try:while( (points_3d[int(y), int(x), 2] < 0) | (points_3d[int(y), int(x), 2] > 2500) ):count += 1x += countif( 0 < points_3d[int(y), int(x), 2] < 2300 ):breaky += countif( 0 < points_3d[int(y), int(x), 2] < 2300 ):breakcount += 1x -= countif( 0 < points_3d[int(y), int(x), 2] < 2300 ):breaky -= countif( 0 < points_3d[int(y), int(x), 2] < 2300 ):break#if(count%2==1):#    x += 1#else:#    y += 1text_cxy = "*"cv2.putText(im0, text_cxy, (x, y) ,  cv2.FONT_ITALIC, 1.2, (0,0,255), 3)#print("count is %d" %count)print('点 (%d, %d) 的三维坐标 (x:%.1fcm, y:%.1fcm, z:%.1fcm)' % (int(x), int(y), points_3d[int(y), int(x), 0]/10, points_3d[int(y), int(x), 1]/10, points_3d[int(y), int(x), 2]/10) )dis = ( (points_3d[int(y), int(x), 0] ** 2 + points_3d[int(y), int(x), 1] ** 2 + points_3d[int(y), int(x), 2] **2) ** 0.5 ) / 10print('点 (%d, %d) 的 %s 距离左摄像头的相对距离为 %0.1f cm' %(x, y,label, dis) )text_x = "x:%.1fcm" %(points_3d[int(y), int(x), 0]/10)text_y = "y:%.1fcm" %(points_3d[int(y), int(x), 1]/10)text_z = "z:%.1fcm" %(points_3d[int(y), int(x), 2]/10)text_dis = "dis:%.1fcm" %discv2.rectangle(im0,(xyxy[0]+(xyxy[2]-xyxy[0]),xyxy[1]),(xyxy[0]+(xyxy[2]-xyxy[0])+5+220,xyxy[1]+150),colors[int(cls)],-1);cv2.putText(im0, text_x, (xyxy[0]+(xyxy[2]-xyxy[0])+5, xyxy[1]+30),  cv2.FONT_ITALIC, 1.2, (255,255,255), 3)cv2.putText(im0, text_y, (xyxy[0]+(xyxy[2]-xyxy[0])+5, xyxy[1]+65),  cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)cv2.putText(im0, text_z, (xyxy[0]+(xyxy[2]-xyxy[0])+5, xyxy[1]+100), cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)cv2.putText(im0, text_dis, (xyxy[0]+(xyxy[2]-xyxy[0])+5, xyxy[1]+145), cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)t4 = time_synchronized()print(f'Done. ({t4 - t3:.3f}s)')# Print time (inference + NMS)print(f'{s}Done. ({t2 - t1:.3f}s)')# Stream resultsif 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)else:  # 'video'if vid_path != save_path:  # new videovid_path = save_pathif isinstance(vid_writer, cv2.VideoWriter):vid_writer.release()  # release previous video writerfourcc = 'mp4v'  # output video codecfps = 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))vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), 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='last_dead_fish_1000.pt', help='model.pt path(s)')parser.add_argument('--source', type=str, default='./shuangmu_dead_fish_011.mp4' , help='source')  # file/folder, 0 for webcamparser.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('--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()with torch.no_grad():if opt.update:  # update all models (to fix SourceChangeWarning)for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:detect()strip_optimizer(opt.weights)else:detect()

5、最终识别测距效果

由于我使用的死鱼的模型,所以测试就使用的死鱼照片测试的。
效果如下图所示。

近景效果。
在这里插入图片描述

远景效果。
在这里插入图片描述

6、代码下载调试运行

yolov5加双目测距的代码,下载后直接运行detect_and_stereo_video_003.py即可开始识别定位。注意是在yolov5的环境运行的。
资源包下载地址:
https://download.csdn.net/download/qq_40700822/87226878?spm=1001.2014.3001.5503

运行detect_and_stereo_video_003.py程序后出现以下情况表示,运行成功,可以把自己的模型替换掉我的模型,实现其他物体的识别测距和定位。注意摄像头的型号规格。
在这里插入图片描述

7、最终演示视频

欢迎各位点赞投币收藏哦🤣🤣🤣!【毕业设计-基于YOLO V5智能追踪记录装置的设计-哔哩哔哩】https://b23.tv/iTkkRJ

8、需要指导的小伙伴可以加我QQ哦~

$ QQ=1024062844
$ 加QQ群免费获取资料哦:544210336

http://chatgpt.dhexx.cn/article/6rdZt1T3.shtml

相关文章

单目视觉的运动目标跟踪定位

[转] http://www.leiphone.com/news/201704/z87wjT8j9s94tMnG.html 市场上空间定位的技术方案分为单目、双目以及激光雷达三大阵营&#xff0c;其中激光雷达由于成本高昂市场接受度较低&#xff0c;而在都是基于计算机视觉的单目和双目中&#xff0c;双目则显得更受欢迎。在国内…

目标定位

声明&#xff1a;本文引用吴恩达教授的DeepLearning课程内容。 图像分类&#xff1a;图片分类问题并不陌生&#xff0c;例如&#xff0c;输入一张图片到多层卷积神经网络。这就是卷积神经网络&#xff0c;它会输出一个特征向量&#xff0c;并反馈给 softmax 单元来预测图片类型…

目标定位与检测

学习笔记仅用作自己复习 https://b23.tv/JAqvgA Object Recognition Object Detection Object Localization 位置表示&#xff0c;x,y中心点坐标&#xff0c;w宽度,h高度&#xff0c;就可以得到矩形框的范围。&#xff08;先找中心点再得到矩形框&#xff09; 黄色全连接层是…

定位目标地理位置

获取目标地理位置 一、GPS简介及分布二、定位工具&#xff1a;Seeker三、反向代理&#xff1a;Ngrok四、实战&#xff1a;获取目标地理位置1.运行 seeker2.上传 ngrok3.短链接伪装4.转发链接 一、GPS简介及分布 物理位置定位&#xff1a;根据P的定位不准确&#xff0c;容易被欺…

目标定位算法(四)之移动目标定位算法

文章目录 移动目标定位算法1.移动目标计算机仿真建模2.基于距离观测的运动目标定位3.纯方位角的运动目标定位 移动目标定位算法 实时探测目标并对目标进行实时定位。 1.移动目标计算机仿真建模 假定目标做匀速直线运动&#xff0c;第i个观测站的位置为(x,y)&#xff0c;目标…

目标定位跟踪系统概述

一、观测系统&#xff1a;目标、观测站、坐标系。 观测站如雷达、声纳等传感器。坐标系&#xff1a;二维、三维直角坐标系&#xff08;描述确定位置&#xff09;&#xff1b;极坐标系&#xff08;r,cita&#xff09;、球坐标系(r,cita,fai)&#xff08;利用角度描述位置&#x…

目标定位算法(三)之基于角度的定位算法

文章目录 基于角度测量的定位算法1.双战角度定位2.三角测量法定位 基于角度测量的定位算法 又叫纯方位目标定位&#xff0c;它的测量信息是目标与观测站之间的角度&#xff0c;包括方向角和俯仰角等。 1.双战角度定位 例&#xff1a;有两个观测站&#xff0c;其中A观测站的位…

目标检测之目标定位

目标检测是计算机视觉领域中一个新兴的应用方向&#xff0c;相比前两年&#xff0c;它的性能越来越好。在构建对象检测之前&#xff0c;我们先了解一下对象定位&#xff0c;首先我们看看它的定义。 图片分类任务我们已经熟悉了&#xff0c;就是算法遍历图片&#xff0c;判断其中…

深度学习——目标定位

目标定位 图片分类任务我们已经熟悉了&#xff0c;就是算法遍历图片&#xff0c;判断其中的对象是不是汽车&#xff0c;这就是图片分类。这节课我们要学习构建神经网络的另一个问题&#xff0c;即定位分类问题。这意味着&#xff0c;我们不仅要用算法判断图片中是不是一辆汽车&…

目标检测及目标定位

一、概述 本文是关于目标检测后根据物体的坐标来确定物体所处的区域&#xff0c;适用于需要根据物体在图像中的位置来分别判断的情况&#xff0c;而且对应的是YOLOv5模型。YOLOv5目标检测的内容可以看看我之前的一篇文章YOLOv5训练自己的数据集_ONEPIECE_00的博客-CSDN博客 本…

一、目标定位

1、目标定位是要求图像中只有一个目标&#xff0c;则构建这个目标的位置信息&#xff0c;如一个网络输出8个值&#xff0c;一个是是否有目标的pc&#xff0c;4个目标位置信息的bx,by,bh,bw&#xff0c;其中bx,by为目标中心点坐标&#xff0c;bh,bw为目标的高和宽&#xff0c;最…

3-1 目标定位

目标定位&#xff08; Object localization&#xff09; 图片分类任务就是算法遍历图片&#xff0c;判断其中的对象是不是某个指定的类别&#xff0c;这就是图片分类。 定位分类问题。意味着我们不仅要用算法判断图片中是不是一辆汽车&#xff0c;还要在图片中标记出它的位置&a…

深度学习(十五):目标定位 Object Localization

这是一系列深度学习的介绍&#xff0c;本文不会涉及公式推导&#xff0c;主要是一些算法思想的随笔记录。 适用人群&#xff1a;深度学习初学者&#xff0c;转AI的开发人员。 编程语言&#xff1a;Python 参考资料&#xff1a;吴恩达老师的深度学习系列视频 吴恩达老师深度学习…

第二十五节,初步认识目标定位、特征点检测、目标检测

一 目标定位(单个物体) 对象检测&#xff0c;它是计算机视觉领域中一个新兴的应用方向&#xff0c;相比前两年&#xff0c;它的性能越来越好。在构建对象检测之前&#xff0c;我们先了解一下对象定位&#xff0c;首先我们看看它的定义。 图片分类任务我们已经熟悉了&#xff0c…

目标定位和特征点检测

1. 目标定位 目标检测是计算机视觉领域中的一个新兴的应用方向&#xff0c;在构建目标检测之前&#xff0c;我们首先了解一下object localization目标定位。 前面说过的图片分类任务就是算法遍历图片&#xff0c;判断其中的对象是不是汽车&#xff0c;主要是图片分类 这里所…

目标定位(Object localization)

来源&#xff1a;Coursera吴恩达深度学习课程 在构建目标检测之前&#xff0c;建议先了解一下目标定位&#xff08;object localization&#xff09;。 在上图的这个例子中&#xff0c;图片分类&#xff08;image classification&#xff09;不仅要判断图片中是不是一辆汽车&a…

学习云计算从哪里入手

学习云计算从哪里入手 1、 学习思路 a) 学习前建议先了解 i. 什么是云计算 ii. 云计算对当前的商业模式有什么影响 iii. 云计算所涉及到的技术 iv. 云计算的现状 b) 云计算可以分为广义的和狭义的两类&…

云计算学习(1)

原文来自于HCIA-Cloud Computing 华为云计算工程师认证 --hsyl007学习笔记收集整理 &#xff0c;个人博客地址 http://hsyl007.work/zblog/ 什么是云计算 云计算就在身边 将资源准备好&#xff0c;通过特定技术随时随地使用这些资源去执行特定任务的方式基本就属于云计算类…

大数据与云计算学习(2)

四、分布式数据库HABSE 1、请阐述HBase和传统关系数据库的区别 正确答案&#xff1a; 我的答案&#xff1a; &#xff08;1&#xff09;数据类型&#xff1a;关系数据库采用关系模型&#xff0c;具有丰富的数据类型和存储方式&#xff0c;HBase则采用了更加简单的数据模型&a…

云计算学习笔记(一):云计算基础

文章转载只能用于非商业性质&#xff0c;且不能带有虚拟货币、积分、注册等附加条件。转载须注明出处http://blog.csdn.net/flowingflying以及作者恺风Wei 本系列将对云计算进行学习&#xff0c;目前资料来自《云计算-概念、技术与架构》&#xff08;第一作者&#xff1a;Tomas…