yolov5实现实时目标检测和测距(pycharm)

首先大家可以参考这篇博客部署好自己的环境: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

三、detect.py文件的修改

将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)

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

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ROS研究员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值