> 文章列表 > YOLOv7+双目测距(python)

YOLOv7+双目测距(python)

YOLOv7+双目测距(python)

1. YOLOv5+双目测距
2. zed+yolov5实现双目测距(直接调用,免标定)
3. zed+yolov4实现双目测距(直接调用,免标定)
4. 本文具体实现效果已在Bilibili发布,点击跳转
5. 如有需要,可以参考我上边的几篇文章进行对比👆👆👆

yolov7直接调用zed相机的代码也已经实现,可以运行10秒左右,会报cuda空间不足的错误,博主gpu为6G,可能是内存太小了。

1. 实验效果

经过一系列实验,结果表明yolov7结合双目实现测距效果不如yolov5,具体参数如下:
yolov5— 每帧速度:100-200ms
yolov7(不加多线程)— inference速度:400ms左右 NMS速度:1200-1500ms
yolov7(加多线程)— inference速度:400ms左右 NMS速度:200ms左右

inference:推理速度,指预处理之后的图像输入模型到模型输出结果的时间
NMS :你可以理解为后处理时间,对模型输出结果经行转换等

2. 相关配置:

电脑系统:win10 (linux及Ubuntu同样适配)
Python版本:3.6
相机型号:zed2i (普通双目也可用)
所用分辨率:2560x720 (这个可以自己调节)

3. 实验流程

yolov7实验步骤和yolov5一样,大致流程: 双目标定→双目校正→立体匹配→结合yolov7→深度测距
找到目标识别源代码中输出物体坐标框的代码段
找到双目测距代码中计算物体深度的代码段
将步骤2与步骤1结合,计算得到目标框中物体的深度
找到目标识别网络中显示障碍物种类的代码段,将深度值添加到里面,进行显示

4.相关代码

双目相机参数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  

以下是stereo.py里对图像进行处理的代码
这些都是网上现成的,直接套用就可以

class stereo_dd:def __init__(self,imgl,imgr):self.left  = imglself.right = imgr# 预处理def preprocess(self, img1, img2):# 彩色图->灰度图if(img1.ndim == 3):#判断为三维数组img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)  # 通过OpenCV加载的图像通道顺序是BGRif(img2.ndim == 3):img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)# 直方图均衡img1 = cv2.equalizeHist(img1)img2 = cv2.equalizeHist(img2)return img1, img2'''# 消除畸变def undistortion(self, image, camera_matrix, dist_coeff):undistortion_image = cv2.undistort(image, camera_matrix, dist_coeff)return undistortion_image'''# 消除畸变def undistortion(self, imagleft,imagright, camera_matrix_left, camera_matrix_right, dist_coeff_left,dist_coeff_right):undistortion_imagleft  = cv2.undistort(imagleft,  camera_matrix_left,  dist_coeff_left )undistortion_imagright = cv2.undistort(imagright, camera_matrix_right, dist_coeff_right)return undistortion_imagleft, undistortion_imagright# 畸变校正和立体校正def rectifyImage(self, image1, image2, map1x, map1y, map2x, map2y):rectifyed_img1 = cv2.remap(image1, map1x, map1y, cv2.INTER_AREA)rectifyed_img2 = cv2.remap(image2, map2x, map2y, cv2.INTER_AREA)return rectifyed_img1, rectifyed_img2# 立体校正检验----画线def draw_line(self, image1, image2):# 建立输出图像height = max(image1.shape[0], image2.shape[0])width = image1.shape[1] + image2.shape[1]output = np.zeros((height, width, 3), dtype=np.uint8)output[0:image1.shape[0], 0:image1.shape[1]] = image1output[0:image2.shape[0], image1.shape[1]:] = image2# 绘制等间距平行线line_interval = 50  # 直线间隔:50for k in range(height // line_interval):cv2.line(output, (0, line_interval * (k + 1)), (2 * width, line_interval * (k + 1)), (0, 255, 0), thickness=2, lineType=cv2.LINE_AA)return output# 视差计算def stereoMatchSGBM(self, left_image, right_image, down_scale=False):# SGBM匹配参数设置if left_image.ndim == 2:img_channels = 1else:img_channels = 3blockSize = 3paraml = {'minDisparity': 0,'numDisparities': 128,'blockSize': blockSize,'P1': 8 * img_channels * blockSize  2,'P2': 32 * img_channels * blockSize  2,'disp12MaxDiff': -1,'preFilterCap': 63,'uniquenessRatio': 10,'speckleWindowSize': 100,'speckleRange': 1,'mode': cv2.STEREO_SGBM_MODE_SGBM_3WAY}# 构建SGBM对象left_matcher = cv2.StereoSGBM_create(paraml)paramr = paramlparamr['minDisparity'] = -paraml['numDisparities']right_matcher = cv2.StereoSGBM_create(paramr)# 计算视差图size = (left_image.shape[1], left_image.shape[0])if down_scale == False:disparity_left = left_matcher.compute(left_image, right_image)disparity_right = right_matcher.compute(right_image, left_image)else:left_image_down = cv2.pyrDown(left_image)right_image_down = cv2.pyrDown(right_image)factor = left_image.shape[1] / left_image_down.shape[1]disparity_left_half = left_matcher.compute(left_image_down, right_image_down)disparity_right_half = right_matcher.compute(right_image_down, left_image_down)disparity_left = cv2.resize(disparity_left_half, size, interpolation=cv2.INTER_AREA)disparity_right = cv2.resize(disparity_right_half, size, interpolation=cv2.INTER_AREA)disparity_left = factor * disparity_leftdisparity_right = factor * disparity_righttrueDisp_left = disparity_left.astype(np.float32) / 16.trueDisp_right = disparity_right.astype(np.float32) / 16.return trueDisp_left, trueDisp_right

测距部分代码处理:

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=1)x = (xyxy[0] + xyxy[2]) / 2y = (xyxy[1] + xyxy[3]) / 2if (x <= 1280):t3 = time_synchronized()p = numheight_0, width_0 = im0.shape[0:2]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]config = stereoconfig.stereoCamera()map1x, map1y, map2x, map2y, Q = getRectifyTransform(height, width, config)iml_rectified, imr_rectified = rectifyImage(iml, imr, map1x, map1y, map2x, map2y)line = draw_line(iml_rectified, imr_rectified)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)points_3d = cv2.reprojectImageTo3D(disp, Q)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) / 10

主代码:

import argparse
import time
from pathlib import Path
import gol
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 stereo.dianyuntu_yolo import getRectifyTransform
from stereo import stereoconfig
from stereo.stereo import stereo_threading, MyThread
import threading
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_tracesave_img = not opt.nosave and not source.endswith('.txt')  # save inference imageswebcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))# 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 trace:model = TracedModel(model, device, opt.img_size)if 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:dataset = LoadImages(source, img_size=imgsz, stride=stride)# 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 onceold_img_w = old_img_h = imgszold_img_b = 1t0 = 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)# Warmupif 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]# Inferencet1 = time_synchronized()with torch.no_grad():   # Calculating gradients would cause a GPU memory leakpred = model(img, augment=opt.augment)[0]t2 = time_synchronized()# Apply NMSpred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)t3 = 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.txtgn = 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 xywhline = (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=1)x = (xyxy[0] + xyxy[2]) / 2y = (xyxy[1] + xyxy[3]) / 2if (x <= 1280):t3 = time_synchronized()p = numheight_0, width_0 = im0.shape[0:2]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]config = stereoconfig.stereoCamera()map1x, map1y, map2x, map2y, Q = getRectifyTransform(height, width, config)iml_rectified, imr_rectified = rectifyImage(iml, imr, map1x, map1y, map2x, map2y)line = draw_line(iml_rectified, imr_rectified)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)points_3d = cv2.reprojectImageTo3D(disp, Q)text_cxy = "*"cv2.putText(im0, text_cxy, (int(x), int(y)), cv2.FONT_ITALIC, 1.2, (0, 0, 255), 3)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, (int(xyxy[0] + (xyxy[2] - xyxy[0])), int(xyxy[1])),(int(xyxy[0] + (xyxy[2] - xyxy[0]) + 5 + 220), int(xyxy[1] + 150)),colors[int(cls)], -1)cv2.putText(im0, text_x, (int(xyxy[0] + (xyxy[2] - xyxy[0]) + 5), int(xyxy[1] + 30)),cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)cv2.putText(im0, text_y, (int(xyxy[0] + (xyxy[2] - xyxy[0]) + 5), int(xyxy[1] + 65)),cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)cv2.putText(im0, text_z, (int(xyxy[0] + (xyxy[2] - xyxy[0]) + 5), int(xyxy[1] + 100)),cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)cv2.putText(im0, text_dis, (int(xyxy[0] + (xyxy[2] - xyxy[0]) + 5), int(xyxy[1] + 145)),cv2.FONT_ITALIC, 1.2, (255, 255, 255), 3)t4 = time_synchronized()print(f'Done. ({t4 - t3:.3f}s)')print(f'{s}Done. ({t2 - t1:.3f}s)')# Print time (inference + NMS)print(f'{s}Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference, ({(1E3 * (t3 - t2)):.1f}ms) NMS')# 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 videovid_path = save_pathif isinstance(vid_writer, cv2.VideoWriter):vid_writer.release()  # release previous video writerif vid_cap:  # videofps = 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:  # streamfps, 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)cv2.namedWindow("Video", cv2.WINDOW_NORMAL)cv2.resizeWindow("Video", 1280, 480)cv2.moveWindow("Video", 0, 0)cv2.imshow("Video", im0)cv2.waitKey(1)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/a5.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('--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()

效果图如下:
实验图
检测视频

源代码后续会开源,敬请期待…
如需要更快检测速度多线程代码,请私信我