ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

yolov5 原码讲解笔记 —— detect.py

2022-08-10 17:36:58  阅读:193  来源: 互联网

标签:yolov5 detect help -- parser add path save 原码


yolov5 在目标检测中占有非常重要的地位,在工业界,也是最受欢迎的目标检测架构之一。

yolov5 原码地址:https://github.com/ultralytics/yolov5

本机环境:windows10,CPU 跑模型

其中 detect.py 代码是检测代码,你可以直接跑这个代码看 yolov5 模型的效果,其中yolov5准备了2张图片 bus.jpg 和 zidane.jpg,可以看到模型检测效果,也可以添加自己图片查看模型效果。

 

yolov5 detect.py 代码讲解:

(1)导入所需要的库函数和包。定义ROOT,ROOT 最后返回的是 detect,py 在 yolov5-master 中的相对位置。

 1 import argparse
 2 import os
 3 import platform
 4 import sys
 5 from pathlib import Path
 6 from tkinter.tix import Tree
 7 
 8 import torch
 9 import torch.backends.cudnn as cudnn
10 
11 # Path.resolve() 使路径成为绝对路径,解析任何符号链接。返回一个新的路径对象
12 FILE = Path(__file__).resolve()
13 ROOT = FILE.parents[0]  # YOLOv5 root directory
14 # sys.path是python的搜索模块的路径集,是一个list
15 # 可以在python 环境下使用sys.path.append(path)添加相关的路径,但在退出python环境后自己添加的路径就会自动消失!
16 if str(ROOT) not in sys.path:
17     sys.path.append(str(ROOT))  # add ROOT to PATH
18 # os.path.relpa此方法返回一个字符串值,该字符串值表示从起始目录到给定路径的相对文件路径。
19 ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative
20 
21 from models.common import DetectMultiBackend
22 from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
23 from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
24                            increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
25 from utils.plots import Annotator, colors, save_one_box
26 from utils.torch_utils import select_device, time_sync

(2)从主函数开始执行。

1 if __name__ == "__main__":
2     opt = parse_opt()
3     main(opt)

(3)parse_opt() 是对函数输入参数进行解析和打印显示。

 1 def parse_opt():
 2     parser = argparse.ArgumentParser()
 3     # 模型路径
 4     parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
 5     parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
 6     # 数据集的yaml路径
 7     parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
 8     parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
 9     parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
10     parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
11     parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
12     parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
13     parser.add_argument('--view-img', action='store_true', help='show results')
14     parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
15     parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
16     parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
17     parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
18     parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
19     parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
20     parser.add_argument('--augment', action='store_true', help='augmented inference')
21     parser.add_argument('--visualize', action='store_true', help='visualize features')
22     parser.add_argument('--update', action='store_true', help='update all models')
23     # 结果保存路径
24     parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
25     parser.add_argument('--name', default='exp', help='save results to project/name')
26     parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
27     # 画线边框厚度
28     parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
29     parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
30     parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
31     parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
32     parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
33     opt = parser.parse_args()
34     # 列表乘法就是复制
35     opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
36     # vars() 函数返回对象object的属性和属性值的字典对象。
37     print_args(vars(opt))
38     return opt

(4) 其中 check_requirements 用来对 python 版本和 requirements.txt 文件必须要安装的包的版本进行检测。run()函数则是执行目标检测的主函数。

1 def main(opt):
2     check_requirements(exclude=('tensorboard', 'thop'))
3     run(**vars(opt))

(5) run() 函数代码段1

  获取关于检测目标的基本信息判断。

 1     # 把source从pathlib类型转换成str类型
 2     source = str(source)
 3     save_img = not nosave and not source.endswith('.txt')  # save inference images
 4     # suffix是返回路径中文件所有后缀名的最后一个元素
 5     is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
 6     # 判断source是否是url
 7     is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
 8     # isnumeric判断是否只由数字组成,
 9     webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
10     if is_url and is_file:
11         source = check_file(source)  # download

(6)run() 函数代码段2

  创建保存结果文件夹,如果已经存在exp,那么就会创建exp2, exp3, ....,以此类推,以免覆盖原来的结果。

1     # Directories,新建保存文件目录,如果不存在,则创建
2     save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
3     (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

(7)run() 函数代码段3

  检测模型当前运行环境,导入检测模型,并且检验输入模型中的图片的大小是否是每个维度步幅的倍数,不是则警告提示。

1     # Load model
2     device = select_device(device)
3     model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
4     stride, names, pt = model.stride, model.names, model.pt
5     imgsz = check_img_size(imgsz, s=stride)  # check image size

(8)run() 函数代码段4

  导入数据,这里会自动读取存放在 data/images 下的图片,如果你想要检测自己的图片,可以把自己的图片放在这个目录下即可。

 1     # Dataloader
 2     if webcam:
 3         view_img = check_imshow()
 4         cudnn.benchmark = True  # set True to speed up constant image size inference
 5         dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
 6         bs = len(dataset)  # batch_size
 7     else:
 8         dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
 9         bs = 1  # batch_size
10     vid_path, vid_writer = [None] * bs, [None] * bs

(9)run() 函数代码段5

  1. 预热学习策略;

  2. 循环检测每张图片;

  3. 分别对图片进行预处理、模型检测和非极大值抑制 (NMS) 3个步骤,最后 pred 返回的就是模型检测并经过NMS处理的最终结果。

 1     # Run inference
 2     model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup
 3     seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
 4     # path:图片路径  im:Padded resize后的图片  im0s:原图  vid_cap:视频相关参数  s:图片信息
 5     for path, im, im0s, vid_cap, s in dataset:
 6         # 计算时间
 7         t1 = time_sync()
 8         # torch.from_numpy()方法把数组转换成张量
 9         # to(device)表示将所有最开始读取数据时的tensor变量copy一份到device所指定的GPU上去,之后的运算都在GPU上进行
10         im = torch.from_numpy(im).to(device)
11         # im.half()是把数据类型转换成float16
12         im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
13         im /= 255  # 0 - 255 to 0.0 - 1.0
14         if len(im.shape) == 3:
15             # tensor维度中使用None可以在所处纬度中多一维
16             im = im[None]  # expand for batch dim
17         t2 = time_sync()
18         dt[0] += t2 - t1
19 
20         # Inference
21         # stem可以返回最后一项除了后缀以外的名字
22         visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
23         pred = model(im, augment=augment, visualize=visualize)  # 得到模型预测结果
24         t3 = time_sync()
25         dt[1] += t3 - t2
26 
27         # NMS
28         pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
29         dt[2] += time_sync() - t3

(10)run() 函数代码段6

  1. 循环处理每一次预测的结果

  2. 如果检测到边界框,那么就把 resize 后的框的大小调整尺度到原图大小,再利用 annotator.box_label 把标签(检测结果和置信值)和框画到原图上,最终保存图片

 1         # Process predictions
 2         for i, det in enumerate(pred):  # per image
 3             seen += 1
 4             if webcam:  # batch_size >= 1
 5                 p, im0, frame = path[i], im0s[i].copy(), dataset.count
 6                 s += f'{i}: '
 7             else:
 8                 p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
 9 
10             p = Path(p)  # to Path
11             save_path = str(save_dir / p.name)  # im.jpg (p.name是获取最后一项)
12             txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
13             s += '%gx%g ' % im.shape[2:]  # print string
14             gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
15             imc = im0.copy() if save_crop else im0  # for save_crop
16             annotator = Annotator(im0, line_width=line_thickness, example=str(names))
17             if len(det):
18                 # Rescale boxes from img_size to im0 size
19                 # 第一参数是resize后图片的大小,第二个参数是边框的大小,第三个参数是原图的大小a, round()是四舍五入法求整数
20                 det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
21 
22                 # Print results
23                 for c in det[:, -1].unique():
24                     n = (det[:, -1] == c).sum()  # detections per class
25                     s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string,如果n>1,那么就变成复数添加s
26 
27                 # Write results
28                 for *xyxy, conf, cls in reversed(det):   # 逆序显示图片
29                     if save_txt:  # Write to file
30                         xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
31                         line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
32                         with open(f'{txt_path}.txt', 'a') as f:
33                             f.write(('%g ' * len(line)).rstrip() % line + '\n')
34 
35                     if save_img or save_crop or view_img:  # Add bbox to image
36                         c = int(cls)  # integer class
37                         # 显示标签和置信值
38                         label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
39                         # 把注释画到边框和标签上
40                         annotator.box_label(xyxy, label, color=colors(c, True))
41                     if save_crop:  # 保存裁剪图片
42                         save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
43 
44             # Stream results
45             im0 = annotator.result()  # convert self.im to numpy
46             if view_img:
47                 if platform.system() == 'Linux' and p not in windows:
48                     windows.append(p)
49                     cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
50                     cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
51                 cv2.imshow(str(p), im0)
52                 cv2.waitKey(1)  # 1 millisecond
53 
54             # Save results (image with detections)
55             if save_img:
56                 if dataset.mode == 'image':
57                     cv2.imwrite(save_path, im0)
58                 else:  # 'video' or 'stream'
59                     if vid_path[i] != save_path:  # new video
60                         vid_path[i] = save_path
61                         if isinstance(vid_writer[i], cv2.VideoWriter):
62                             vid_writer[i].release()  # release previous video writer
63                         if vid_cap:  # video
64                             fps = vid_cap.get(cv2.CAP_PROP_FPS)
65                             w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
66                             h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
67                         else:  # stream
68                             fps, w, h = 30, im0.shape[1], im0.shape[0]
69                         save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
70                         vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
71                     vid_writer[i].write(im0)
72 
73         # Print time (inference-only)
74         LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')

(11)run() 函数代码段7

  显示代码运行时间以及图片处理大小、检测类别等信息。

1     # Print results
2     t = tuple(x / seen * 1E3 for x in dt)  # speeds per image
3     LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
4     if save_txt or save_img:
5         s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
6         LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
7     if update:
8         strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)

代码运行结果:

 

          

 

标签:yolov5,detect,help,--,parser,add,path,save,原码
来源: https://www.cnblogs.com/ttweixiao-IT-program/p/16573200.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有