赞
踩
首先大家可以参考这篇博客部署好自己的环境:http://t.csdnimg.cn/erGYw
本文前提:已实现yolov5通过摄像头实时目标检测
首先需要知道自己所用的相机的像素焦距,并将其加入测距代码distance.py文件里
苗的高度18.1(单位英寸→对应cm/2.54)
- foc = 933.33 # 镜头焦距
- real_hight_miao = 18.1 # 苗高度
-
-
- # 自定义函数,单目测距
- def miao_distance(h):
- dis_inch = (real_hight_miao * foc) / (h - 2)
- dis_cm = dis_inch * 2.54
- dis_cm = int(dis_cm)
- dis_m = dis_cm/100
- return dis_m
然后在detect.py文件中加入以下代码
from distance import miao_distance
将if len(det):到if save_crop:中的代码替换为下面所示
- if len(det):
- # Rescale boxes from img_size to im0 size
- det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
-
- # Print results
- for c in det[:, 5].unique():
- n = (det[:, 5] == 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):
-
- 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 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 save_crop or view_img: # Add bbox to image
- x1 = int(xyxy[0]) # 获取四个边框坐标
- y1 = int(xyxy[1])
- x2 = int(xyxy[2])
- y2 = int(xyxy[3])
- h = y2 - y1
- if names[int(cls)] == "miao":
- c = int(cls) # integer class 整数类 1111111111
- label = None if hide_labels else (
- names[c] if hide_conf else f'{names[c]} {conf:.2f}') # 111
- dis_m = miao_distance(h) # 调用函数,计算苗实际高度
- label += f' {dis_m}m' # 将苗的距离显示写在标签后
- txt = '{0}'.format(label)
- annotator.box_label(xyxy, txt, color=colors(c, True))
-
-
- if save_crop:
- save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
运行代码即可得到最终结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。