当前位置:   article > 正文

yolov5实现实时目标检测和测距(pycharm)_yolov5摄像头实时检测

yolov5摄像头实时检测

首先大家可以参考这篇博客部署好自己的环境:http://t.csdnimg.cn/erGYw

本文前提:已实现yolov5通过摄像头实时目标检测

一、测距文件的编写

首先需要知道自己所用的相机的像素焦距,并将其加入测距代码distance.py文件里

苗的高度18.1(单位英寸→对应cm/2.54)

  1. foc = 933.33 # 镜头焦距
  2. real_hight_miao = 18.1 # 苗高度
  3. # 自定义函数,单目测距
  4. def miao_distance(h):
  5. dis_inch = (real_hight_miao * foc) / (h - 2)
  6. dis_cm = dis_inch * 2.54
  7. dis_cm = int(dis_cm)
  8. dis_m = dis_cm/100
  9. return dis_m

二、测距文件的引入

然后在detect.py文件中加入以下代码

from distance import miao_distance

三、detect.py文件的修改

将if len(det):到if save_crop:中的代码替换为下面所示

  1. if len(det):
  2. # Rescale boxes from img_size to im0 size
  3. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
  4. # Print results
  5. for c in det[:, 5].unique():
  6. n = (det[:, 5] == c).sum() # detections per class
  7. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  8. # Write results
  9. for *xyxy, conf, cls in reversed(det):
  10. if save_txt: # Write to file
  11. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  12. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  13. with open(txt_path + '.txt', 'a') as f:
  14. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  15. if save_img or save_crop or view_img: # Add bbox to image
  16. x1 = int(xyxy[0]) # 获取四个边框坐标
  17. y1 = int(xyxy[1])
  18. x2 = int(xyxy[2])
  19. y2 = int(xyxy[3])
  20. h = y2 - y1
  21. if names[int(cls)] == "miao":
  22. c = int(cls) # integer class 整数类 1111111111
  23. label = None if hide_labels else (
  24. names[c] if hide_conf else f'{names[c]} {conf:.2f}') # 111
  25. dis_m = miao_distance(h) # 调用函数,计算苗实际高度
  26. label += f' {dis_m}m' # 将苗的距离显示写在标签后
  27. txt = '{0}'.format(label)
  28. annotator.box_label(xyxy, txt, color=colors(c, True))
  29. if save_crop:
  30. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

运行代码即可得到最终结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/642115
推荐阅读
相关标签
  

闽ICP备14008679号