基于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/2e8yUhttp://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' # 在标签后追加距离