0


yolov5——detect.py代码【注释、详解、使用教程】

yolov5——detect.py代码【注释、详解、使用教程】

yolov5——detect.py代码【注释、详解、使用教程】

根据目前的最新版本的yolov5代码做出注释和详解以及使用教程,对了目前已经是v6,不知道你看博客的时候是什么版本呢,总的来说越来越先进越来越完善,越来越适合无脑啊哈哈哈,没你说哈IIII
在这里插入图片描述

1. 函数parse_opt()

  1. defparse_opt():"""
  2. weights: 训练的权重路径,可以使用自己训练的权重,也可以使用官网提供的权重
  3. 默认官网的权重yolov5s.pt(yolov5n.pt/yolov5s.pt/yolov5m.pt/yolov5l.pt/yolov5x.pt/区别在于网络的宽度和深度以此增加)
  4. source: 测试数据,可以是图片/视频路径,也可以是'0'(电脑自带摄像头),也可以是rtsp等视频流, 默认data/images
  5. data: 配置数据文件路径, 包括image/label/classes等信息, 训练自己的文件, 需要作相应更改, 可以不用管
  6. 如果设置了只显示个别类别即使用了--classes = 0 或二者1, 2, 3等, 则需要设置该文件,数字和类别相对应才能只检测某一个类
  7. imgsz: 网络输入图片大小, 默认的大小是640
  8. conf-thres: 置信度阈值, 默认为0.25
  9. iou-thres: 做nms的iou阈值, 默认为0.45
  10. max-det: 保留的最大检测框数量, 每张图片中检测目标的个数最多为1000类
  11. device: 设置设备CPU/CUDA, 可以不用设置
  12. view-img: 是否展示预测之后的图片/视频, 默认False, --view-img 电脑界面出现图片或者视频检测结果
  13. save-txt: 是否将预测的框坐标以txt文件形式保存, 默认False, 使用--save-txt 在路径runs/detect/exp*/labels/*.txt下生成每张图片预测的txt文件
  14. save-conf: 是否将置信度conf也保存到txt中, 默认False
  15. save-crop: 是否保存裁剪预测框图片, 默认为False, 使用--save-crop 在runs/detect/exp*/crop/剪切类别文件夹/ 路径下会保存每个接下来的目标
  16. nosave: 不保存图片、视频, 要保存图片,不设置--nosave 在runs/detect/exp*/会出现预测的结果
  17. classes: 设置只保留某一部分类别, 形如0或者0 2 3, 使用--classes = n, 则在路径runs/detect/exp*/下保存的图片为n所对应的类别, 此时需要设置data
  18. agnostic-nms: 进行NMS去除不同类别之间的框, 默认False
  19. augment: TTA测试时增强/多尺度预测
  20. visualize: 是否可视化网络层输出特征
  21. update: 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
  22. project:保存测试日志的文件夹路径
  23. name:保存测试日志文件夹的名字, 所以最终是保存在project/name中
  24. exist_ok: 是否重新创建日志文件, False时重新创建文件
  25. line-thickness: 画框的线条粗细
  26. hide-labels: 可视化时隐藏预测类别
  27. hide-conf: 可视化时隐藏置信度
  28. half: 是否使用F16精度推理, 半进度提高检测速度
  29. dnn: 用OpenCV DNN预测
  30. """
  31. parser = argparse.ArgumentParser()
  32. parser.add_argument('--weights', nargs='+',type=str, default=ROOT /'yolov5s.pt',help='model path(s)')
  33. parser.add_argument('--source',type=str, default=ROOT /'data/images',help='file/dir/URL/glob, 0 for webcam')
  34. parser.add_argument('--data',type=str, default=ROOT /'data/coco128.yaml',help='(optional) dataset.yaml path')
  35. parser.add_argument('--imgsz','--img','--img-size', nargs='+',type=int, default=[640],help='inference size h,w')
  36. parser.add_argument('--conf-thres',type=float, default=0.25,help='confidence threshold')
  37. parser.add_argument('--iou-thres',type=float, default=0.45,help='NMS IoU threshold')
  38. parser.add_argument('--max-det',type=int, default=1000,help='maximum detections per image')
  39. parser.add_argument('--device', default='',help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  40. parser.add_argument('--view-img', action='store_true',help='show results')
  41. parser.add_argument('--save-txt', action='store_true',help='save results to *.txt')
  42. parser.add_argument('--save-conf', action='store_true',help='save confidences in --save-txt labels')
  43. parser.add_argument('--save-crop', action='store_true',help='save cropped prediction boxes')
  44. parser.add_argument('--nosave', action='store_true',help='do not save images/videos')
  45. parser.add_argument('--classes', nargs='+',type=int,help='filter by class: --classes 0, or --classes 0 2 3')
  46. parser.add_argument('--agnostic-nms', action='store_true',help='class-agnostic NMS')
  47. parser.add_argument('--augment', action='store_true',help='augmented inference')
  48. parser.add_argument('--visualize', action='store_true',help='visualize features')
  49. parser.add_argument('--update', action='store_true',help='update all models')
  50. parser.add_argument('--project', default=ROOT /'runs/detect',help='save results to project/name')
  51. parser.add_argument('--name', default='exp',help='save results to project/name')
  52. parser.add_argument('--exist-ok', action='store_true',help='existing project/name ok, do not increment')
  53. parser.add_argument('--line-thickness', default=3,type=int,help='bounding box thickness (pixels)')
  54. parser.add_argument('--hide-labels', default=False, action='store_true',help='hide labels')
  55. parser.add_argument('--hide-conf', default=False, action='store_true',help='hide confidences')
  56. parser.add_argument('--half', action='store_true',help='use FP16 half-precision inference')
  57. parser.add_argument('--dnn', action='store_true',help='use OpenCV DNN for ONNX inference')
  58. opt = parser.parse_args()# 扩充维度, 如果是一位就扩充一位
  59. opt.imgsz *=2iflen(opt.imgsz)==1else1# expand# 输出所有参数
  60. print_args(FILE.stem, opt)return opt

2. 函数main()

  1. defmain(opt):# 检查环境/打印参数,主要是requrement.txt的包是否安装,用彩色显示设置的参数
  2. check_requirements(exclude=('tensorboard','thop'))# 执行run()函数
  3. run(**vars(opt))

3. 函数run()

3.1 run函数——传入参数

  1. defrun(weights=ROOT /'yolov5s.pt',# model.pt path(s) # 权重文件地址 默认 weights/可以是自己的路径
  2. source=ROOT /'data/images',# file/dir/URL/glob, 0 for webcam 0 自带电脑摄像头, 默认data/images/
  3. data=ROOT /'data/coco128.yaml',# dataset.yaml path, data文件路径,包括类别/图片/标签等信息
  4. imgsz=(640,640),# inference size (height, width) 输入图片的大小 默认640*640
  5. conf_thres=0.25,# confidence threshold # object置信度阈值 默认0.25 用在nms中
  6. iou_thres=0.45,# NMS IOU threshold # 做nms的iou阈值 默认0.45 用在nms中
  7. max_det=1000,# maximum detections per image 每张图片最多的目标数量 用在nms
  8. device='',# cuda device, i.e. 0 or 0,1,2,3 or cpu 设置代码执行的设备 cuda device, i.e. 0 or 0,1,2,3 or cpu
  9. view_img=False,# show results 是否展示预测之后的图片或视频 默认False
  10. save_txt=False,# save results to *.txt 是否将预测的框坐标以txt文件形式保存, 默认False, 使用--save-txt 在路径runs/detect/exp*/labels/*.txt下生成每张图片预测的txt文件
  11. save_conf=False,# save confidences in --save-txt labels 是否将置信度conf也保存到txt中, 默认False
  12. save_crop=False,# save cropped prediction boxes 是否保存裁剪预测框图片, 默认为False, 使用--save-crop runs/detect/exp*/crop/剪切类别文件夹/ 路径下会保存每个接下来的目标
  13. nosave=False,# do not save images/videos 不保存图片、视频, 要保存图片,不设置--nosave runs/detect/exp*/会出现预测的结果
  14. classes=None,# filter by class: --class 0, or --class 0 2 3 设置只保留某一部分类别, 形如0或者0 2 3, 使用--classes = n, 则在路径runs/detect/exp*/下保存的图片为n所对应的类别, 此时需要设置data
  15. agnostic_nms=False,# class-agnostic NMS 进行NMS去除不同类别之间的框, 默认False
  16. augment=False,# augmented inference TTA测试时增强/多尺度预测,可以提分
  17. visualize=False,# visualize features 是否可视化网络层输出特征
  18. update=False,# update all models 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
  19. project=ROOT /'runs/detect',# save results to project/name 保存测试日志的文件夹路径
  20. name='exp',# save results to project/name 每次实验的名称
  21. exist_ok=False,# existing project/name ok, do not increment 是否重新创建日志文件, False时重新创建文件
  22. line_thickness=3,# bounding box thickness (pixels) 画框的线条粗细
  23. hide_labels=False,# hide labels 可视化时隐藏预测类别
  24. hide_conf=False,# hide confidences 可视化时隐藏置信度
  25. half=False,# use FP16 half-precision inference 是否使用F16精度推理, 半进度提高检测速度
  26. dnn=False,# use OpenCV DNN for ONNX inference OpenCV DNN预测):

3.2 run函数——初始化配置

  1. ################################################# 1. 初始化配置 ###################################################### 输入的路径变为字符串
  2. source =str(source)# 是否保存图片和txt文件
  3. save_img =not nosave andnot source.endswith('.txt')# save inference images# 判断文件是否是视频流# Path()提取文件名 例如:Path("./data/test_images/bus.jpg") Path.name->bus.jpg Path.parent->./data/test_images Path.suffix->.jpg
  4. is_file = Path(source).suffix[1:]in(IMG_FORMATS + VID_FORMATS)# 提取文件后缀名是否符合要求的文件,例如:是否格式是jpg, png, asf, avi等# .lower()转化成小写 .upper()转化成大写 .title()首字符转化成大写,其余为小写, .startswith('http://')返回True or Flase
  5. is_url = source.lower().startswith(('rtsp://','rtmp://','http://','https://'))# .isnumeric()是否是由数字组成,返回True or False
  6. webcam = source.isnumeric()or source.endswith('.txt')or(is_url andnot is_file)if is_url and is_file:# 返回文件
  7. source = check_file(source)# download# Directories# 预测路径是否存在,不存在新建,按照实验文件以此递增新建
  8. save_dir = increment_path(Path(project)/ name, exist_ok=exist_ok)# increment run(save_dir /'labels'if save_txt else save_dir).mkdir(parents=True, exist_ok=True)# make dir# Load model# 获取设备 CPU/CUDA
  9. device = select_device(device)# 检测编译框架PYTORCH/TENSORFLOW/TENSORRT
  10. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)
  11. stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
  12. # 确保输入图片的尺寸imgsz能整除stride=32 如果不能则调整为能被整除并返回
  13. imgsz = check_img_size(imgsz, s=stride)# check image size# Half# 如果不是CPU,使用半进度(图片半精度/模型半精度)
  14. half &=(pt or jit or onnx or engine)and device.type!='cpu'# FP16 supported on limited backends with CUDAif pt or jit:
  15. model.model.half()if half else model.model.float()# TENSORRT加速elif engine and model.trt_fp16_input != half:
  16. LOGGER.info('model '+('requires'if model.trt_fp16_input else'incompatible with')+' --half. Adjusting automatically.')
  17. half = model.trt_fp16_input

3.3 run函数——加载数据

  1. ################################################# 2. 加载数据 ###################################################### Dataloader 加载数据# 使用视频流或者页面if webcam:
  2. view_img = check_imshow()
  3. cudnn.benchmark =True# set True to speed up constant image size inference
  4. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  5. bs =len(dataset)# batch_sizeelse:# 直接从source文件下读取图片
  6. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
  7. bs =1# batch_size# 保存的路径
  8. vid_path, vid_writer =[None]* bs,[None]* bs

3.4 run函数——输入预测

  1. model.warmup(imgsz=(1if pt else bs,3,*imgsz), half=half)# warmup
  2. dt, seen =[0.0,0.0,0.0],0for path, im, im0s, vid_cap, s in dataset:
  3. t1 = time_sync()# 转化到GPU
  4. im = torch.from_numpy(im).to(device)# 是否使用半精度
  5. im = im.half()if half else im.float()# uint8 to fp16/32
  6. im /=255# 0 - 255 to 0.0 - 1.0iflen(im.shape)==3:# 增加一个维度
  7. im = im[None]# expand for batch dim
  8. t2 = time_sync()
  9. dt[0]+= t2 - t1
  10. # Inference# 可是化文件路径
  11. visualize = increment_path(save_dir / Path(path).stem, mkdir=True)if visualize elseFalse"""
  12. pred.shape=(1, num_boxes, 5+num_class)
  13. h,w为传入网络图片的长和宽,注意dataset在检测时使用了矩形推理,所以这里h不一定等于w
  14. num_boxes = h/32 * w/32 + h/16 * w/16 + h/8 * w/8
  15. pred[..., 0:4]为预测框坐标=预测框坐标为xywh(中心点+宽长)格式
  16. pred[..., 4]为objectness置信度
  17. pred[..., 5:-1]为分类结果
  18. """
  19. pred = model(im, augment=augment, visualize=visualize)
  20. t3 = time_sync()# 预测的时间
  21. dt[1]+= t3 - t2

3.5 run函数——NMS

  1. # NMS# 非极大值抑制"""
  2. pred: 网络的输出结果
  3. conf_thres:置信度阈值
  4. ou_thres:iou阈值
  5. classes: 是否只保留特定的类别
  6. agnostic_nms: 进行nms是否也去除不同类别之间的框
  7. max-det: 保留的最大检测框数量
  8. ---NMS, 预测框格式: xywh(中心点+长宽)-->xyxy(左上角右下角)
  9. pred是一个列表list[torch.tensor], 长度为batch_size
  10. 每一个torch.tensorshape为(num_boxes, 6), 内容为box + conf + cls
  11. """
  12. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)# 预测+NMS的时间
  13. dt[2]+= time_sync()- t3

3.6 run函数——保存打印

  1. # Process predictions# 对每张图片做处理for i, det inenumerate(pred):# per image
  2. seen +=1if webcam:# batch_size >= 1# 如果输入源是webcam则batch_size>=1 取出dataset中的一张图片
  3. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  4. s += f'{i}: 'else:# 但是大部分我们一般都是从LoadImages流读取本都文件中的照片或者视频 所以batch_size=1# p: 当前图片/视频的绝对路径 如 F:\yolo_v5\yolov5-U\data\images\bus.jpg# s: 输出信息 初始为 ''# im0: 原始图片 letterbox + pad 之前的图片# frame: 视频流
  5. p, im0, frame = path, im0s.copy(),getattr(dataset,'frame',0)# 当前路径yolov5/data/images/
  6. p = Path(p)# to Path# 图片/视频的保存路径save_path 如 runs\\detect\\exp8\\bus.jpg
  7. save_path =str(save_dir / p.name)# im.jpg# 设置保存框坐标的txt文件路径,每张图片对应一个框坐标信息
  8. txt_path =str(save_dir /'labels'/ p.stem)+(''if dataset.mode =='image'else f'_{frame}')# im.txt# 设置打印图片的信息
  9. s +='%gx%g '% im.shape[2:]# print string
  10. gn = torch.tensor(im0.shape)[[1,0,1,0]]# normalization gain whwh# 保存截图
  11. imc = im0.copy()if save_crop else im0 # for save_crop
  12. annotator = Annotator(im0, line_width=line_thickness, example=str(names))iflen(det):# Rescale boxes from img_size to im0 size# 将预测信息映射到原图
  13. det[:,:4]= scale_coords(im.shape[2:], det[:,:4], im0.shape).round()# Print results# 打印检测到的类别数量for c in det[:,-1].unique():
  14. n =(det[:,-1]== c).sum()# detections per class
  15. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "# add to string# Write results# 保存结果: txt/图片画框/crop-imagefor*xyxy, conf, cls inreversed(det):# 将每个图片的预测信息分别存入save_dir/labels下的xxx.txt中 每行: class_id + score + xywhif save_txt:# Write to file
  16. xywh =(xyxy2xywh(torch.tensor(xyxy).view(1,4))/ gn).view(-1).tolist()# normalized xywh
  17. line =(cls,*xywh, conf)if save_conf else(cls,*xywh)# label formatwithopen(txt_path +'.txt','a')as f:
  18. f.write(('%g '*len(line)).rstrip()% line +'\n')# # 在原图上画框 + 将预测到的目标剪切出来 保存成图片 保存在save_dir/crops下 在原图像画图或者保存结果if save_img or save_crop or view_img:# Add bbox to image
  19. c =int(cls)# integer class
  20. label =Noneif hide_labels else(names[c]if hide_conf else f'{names[c]} {conf:.2f}')
  21. annotator.box_label(xyxy, label, color=colors(c,True))if save_crop:# 在原图上画框 + 将预测到的目标剪切出来 保存成图片 保存在save_dir/crops
  22. save_one_box(xyxy, imc,file=save_dir /'crops'/ names[c]/ f'{p.stem}.jpg', BGR=True)# Stream results
  23. im0 = annotator.result()# 显示图片if view_img:
  24. cv2.imshow(str(p), im0)
  25. cv2.waitKey(1)# 1 millisecond# Save results (image with detections)# 保存图片if save_img:if dataset.mode =='image':
  26. cv2.imwrite(save_path, im0)else:# 'video' or 'stream'if vid_path[i]!= save_path:# new video
  27. vid_path[i]= save_path
  28. ifisinstance(vid_writer[i], cv2.VideoWriter):
  29. vid_writer[i].release()# release previous video writerif vid_cap:# video
  30. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  31. w =int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  32. h =int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))else:# stream
  33. fps, w, h =30, im0.shape[1], im0.shape[0]
  34. save_path =str(Path(save_path).with_suffix('.mp4'))# force *.mp4 suffix on results videos
  35. vid_writer[i]= cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps,(w, h))
  36. vid_writer[i].write(im0)# Print time (inference-only)
  37. LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')

4. detect.py全部注释

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license"""
  2. Run inference on images, videos, directories, streams, etc.
  3. Usage - sources:
  4. $ python path/to/detect.py --weights yolov5s.pt --source 0 # webcam # 直播软件/电脑摄像头
  5. img.jpg # image
  6. vid.mp4 # video
  7. path/ # directory
  8. path/*.jpg # glob
  9. 'https://youtu.be/Zgi9g1ksQHc' # YouTube
  10. 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
  11. Usage - formats:
  12. $ python path/to/detect.py --weights yolov5s.pt # PyTorch
  13. yolov5s.torchscript # TorchScript
  14. yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
  15. yolov5s.xml # OpenVINO
  16. yolov5s.engine # TensorRT
  17. yolov5s.mlmodel # CoreML (MacOS-only)
  18. yolov5s_saved_model # TensorFlow SavedModel
  19. yolov5s.pb # TensorFlow GraphDef
  20. yolov5s.tflite # TensorFlow Lite
  21. yolov5s_edgetpu.tflite # TensorFlow Edge TPU
  22. """import argparse
  23. import os
  24. import sys
  25. from pathlib import Path
  26. import cv2
  27. import torch
  28. import torch.backends.cudnn as cudnn
  29. FILE = Path(__file__).resolve()
  30. ROOT = FILE.parents[0]# YOLOv5 root directoryifstr(ROOT)notin sys.path:
  31. sys.path.append(str(ROOT))# add ROOT to PATH
  32. ROOT = Path(os.path.relpath(ROOT, Path.cwd()))# relativefrom models.common import DetectMultiBackend
  33. from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
  34. from utils.general import(LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,
  35. increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)from utils.plots import Annotator, colors, save_one_box
  36. from utils.torch_utils import select_device, time_sync
  37. # 预测不更新梯度
  38. @torch.no_grad()defrun(weights=ROOT /'yolov5s.pt',# model.pt path(s) # 权重文件地址 默认 weights/可以是自己的路径
  39. source=ROOT /'data/images',# file/dir/URL/glob, 0 for webcam 0 自带电脑摄像头, 默认data/images/
  40. data=ROOT /'data/coco128.yaml',# dataset.yaml path, data文件路径,包括类别/图片/标签等信息
  41. imgsz=(640,640),# inference size (height, width) 输入图片的大小 默认640*640
  42. conf_thres=0.25,# confidence threshold # object置信度阈值 默认0.25 用在nms中
  43. iou_thres=0.45,# NMS IOU threshold # 做nms的iou阈值 默认0.45 用在nms中
  44. max_det=1000,# maximum detections per image 每张图片最多的目标数量 用在nms中
  45. device='',# cuda device, i.e. 0 or 0,1,2,3 or cpu 设置代码执行的设备 cuda device, i.e. 0 or 0,1,2,3 or cpu
  46. view_img=False,# show results 是否展示预测之后的图片或视频 默认False
  47. save_txt=False,# save results to *.txt 是否将预测的框坐标以txt文件形式保存, 默认False, 使用--save-txt 在路径runs/detect/exp*/labels/*.txt下生成每张图片预测的txt文件
  48. save_conf=False,# save confidences in --save-txt labels 是否将置信度conf也保存到txt中, 默认False
  49. save_crop=False,# save cropped prediction boxes 是否保存裁剪预测框图片, 默认为False, 使用--save-crop 在runs/detect/exp*/crop/剪切类别文件夹/ 路径下会保存每个接下来的目标
  50. nosave=False,# do not save images/videos 不保存图片、视频, 要保存图片,不设置--nosave runs/detect/exp*/会出现预测的结果
  51. classes=None,# filter by class: --class 0, or --class 0 2 3 设置只保留某一部分类别, 形如0或者0 2 3, 使用--classes = n, 则在路径runs/detect/exp*/下保存的图片为n所对应的类别, 此时需要设置data
  52. agnostic_nms=False,# class-agnostic NMS 进行NMS去除不同类别之间的框, 默认False
  53. augment=False,# augmented inference TTA测试时增强/多尺度预测,可以提分
  54. visualize=False,# visualize features 是否可视化网络层输出特征
  55. update=False,# update all models 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
  56. project=ROOT /'runs/detect',# save results to project/name 保存测试日志的文件夹路径
  57. name='exp',# save results to project/name 每次实验的名称
  58. exist_ok=False,# existing project/name ok, do not increment 是否重新创建日志文件, False时重新创建文件
  59. line_thickness=3,# bounding box thickness (pixels) 画框的线条粗细
  60. hide_labels=False,# hide labels 可视化时隐藏预测类别
  61. hide_conf=False,# hide confidences 可视化时隐藏置信度
  62. half=False,# use FP16 half-precision inference 是否使用F16精度推理, 半进度提高检测速度
  63. dnn=False,# use OpenCV DNN for ONNX inference OpenCV DNN预测):################################################# 1. 初始化配置 ###################################################### 输入的路径变为字符串
  64. source =str(source)# 是否保存图片和txt文件
  65. save_img =not nosave andnot source.endswith('.txt')# save inference images# 判断文件是否是视频流# Path()提取文件名 例如:Path("./data/test_images/bus.jpg") Path.name->bus.jpg Path.parent->./data/test_images Path.suffix->.jpg
  66. is_file = Path(source).suffix[1:]in(IMG_FORMATS + VID_FORMATS)# 提取文件后缀名是否符合要求的文件,例如:是否格式是jpg, png, asf, avi等# .lower()转化成小写 .upper()转化成大写 .title()首字符转化成大写,其余为小写, .startswith('http://')返回True or Flase
  67. is_url = source.lower().startswith(('rtsp://','rtmp://','http://','https://'))# .isnumeric()是否是由数字组成,返回True or False
  68. webcam = source.isnumeric()or source.endswith('.txt')or(is_url andnot is_file)if is_url and is_file:# 返回文件
  69. source = check_file(source)# download# Directories# 预测路径是否存在,不存在新建,按照实验文件以此递增新建
  70. save_dir = increment_path(Path(project)/ name, exist_ok=exist_ok)# increment run(save_dir /'labels'if save_txt else save_dir).mkdir(parents=True, exist_ok=True)# make dir# Load model# 获取设备 CPU/CUDA
  71. device = select_device(device)# 检测编译框架PYTORCH/TENSORFLOW/TENSORRT
  72. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)
  73. stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
  74. # 确保输入图片的尺寸imgsz能整除stride=32 如果不能则调整为能被整除并返回
  75. imgsz = check_img_size(imgsz, s=stride)# check image size# Half# 如果不是CPU,使用半进度(图片半精度/模型半精度)
  76. half &=(pt or jit or onnx or engine)and device.type!='cpu'# FP16 supported on limited backends with CUDAif pt or jit:
  77. model.model.half()if half else model.model.float()# TENSORRT加速elif engine and model.trt_fp16_input != half:
  78. LOGGER.info('model '+('requires'if model.trt_fp16_input else'incompatible with')+' --half. Adjusting automatically.')
  79. half = model.trt_fp16_input
  80. ################################################# 2. 加载数据 ###################################################### Dataloader 加载数据# 使用视频流或者页面if webcam:
  81. view_img = check_imshow()
  82. cudnn.benchmark =True# set True to speed up constant image size inference
  83. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  84. bs =len(dataset)# batch_sizeelse:# 直接从source文件下读取图片
  85. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
  86. bs =1# batch_size# 保存的路径
  87. vid_path, vid_writer =[None]* bs,[None]* bs
  88. ################################################# 3. 网络预测 ###################################################### Run inference# warmup 热身
  89. model.warmup(imgsz=(1if pt else bs,3,*imgsz), half=half)# warmup
  90. dt, seen =[0.0,0.0,0.0],0for path, im, im0s, vid_cap, s in dataset:
  91. t1 = time_sync()# 转化到GPU
  92. im = torch.from_numpy(im).to(device)# 是否使用半精度
  93. im = im.half()if half else im.float()# uint8 to fp16/32
  94. im /=255# 0 - 255 to 0.0 - 1.0iflen(im.shape)==3:# 增加一个维度
  95. im = im[None]# expand for batch dim
  96. t2 = time_sync()
  97. dt[0]+= t2 - t1
  98. # Inference# 可是化文件路径
  99. visualize = increment_path(save_dir / Path(path).stem, mkdir=True)if visualize elseFalse"""
  100. pred.shape=(1, num_boxes, 5+num_class)
  101. h,w为传入网络图片的长和宽,注意dataset在检测时使用了矩形推理,所以这里h不一定等于w
  102. num_boxes = h/32 * w/32 + h/16 * w/16 + h/8 * w/8
  103. pred[..., 0:4]为预测框坐标=预测框坐标为xywh(中心点+宽长)格式
  104. pred[..., 4]为objectness置信度
  105. pred[..., 5:-1]为分类结果
  106. """
  107. pred = model(im, augment=augment, visualize=visualize)
  108. t3 = time_sync()# 预测的时间
  109. dt[1]+= t3 - t2
  110. # NMS# 非极大值抑制"""
  111. pred: 网络的输出结果
  112. conf_thres:置信度阈值
  113. ou_thres:iou阈值
  114. classes: 是否只保留特定的类别
  115. agnostic_nms: 进行nms是否也去除不同类别之间的框
  116. max-det: 保留的最大检测框数量
  117. ---NMS, 预测框格式: xywh(中心点+长宽)-->xyxy(左上角右下角)
  118. pred是一个列表list[torch.tensor], 长度为batch_size
  119. 每一个torch.tensorshape为(num_boxes, 6), 内容为box + conf + cls
  120. """
  121. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)# 预测+NMS的时间
  122. dt[2]+= time_sync()- t3
  123. # Second-stage classifier (optional)# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)# Process predictions# 对每张图片做处理for i, det inenumerate(pred):# per image
  124. seen +=1if webcam:# batch_size >= 1# 如果输入源是webcam则batch_size>=1 取出dataset中的一张图片
  125. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  126. s += f'{i}: 'else:# 但是大部分我们一般都是从LoadImages流读取本都文件中的照片或者视频 所以batch_size=1# p: 当前图片/视频的绝对路径 如 F:\yolo_v5\yolov5-U\data\images\bus.jpg# s: 输出信息 初始为 ''# im0: 原始图片 letterbox + pad 之前的图片# frame: 视频流
  127. p, im0, frame = path, im0s.copy(),getattr(dataset,'frame',0)# 当前路径yolov5/data/images/
  128. p = Path(p)# to Path# 图片/视频的保存路径save_path 如 runs\\detect\\exp8\\bus.jpg
  129. save_path =str(save_dir / p.name)# im.jpg# 设置保存框坐标的txt文件路径,每张图片对应一个框坐标信息
  130. txt_path =str(save_dir /'labels'/ p.stem)+(''if dataset.mode =='image'else f'_{frame}')# im.txt# 设置打印图片的信息
  131. s +='%gx%g '% im.shape[2:]# print string
  132. gn = torch.tensor(im0.shape)[[1,0,1,0]]# normalization gain whwh# 保存截图
  133. imc = im0.copy()if save_crop else im0 # for save_crop
  134. annotator = Annotator(im0, line_width=line_thickness, example=str(names))iflen(det):# Rescale boxes from img_size to im0 size# 将预测信息映射到原图
  135. det[:,:4]= scale_coords(im.shape[2:], det[:,:4], im0.shape).round()# Print results# 打印检测到的类别数量for c in det[:,-1].unique():
  136. n =(det[:,-1]== c).sum()# detections per class
  137. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "# add to string# Write results# 保存结果: txt/图片画框/crop-imagefor*xyxy, conf, cls inreversed(det):# 将每个图片的预测信息分别存入save_dir/labels下的xxx.txt中 每行: class_id + score + xywhif save_txt:# Write to file
  138. xywh =(xyxy2xywh(torch.tensor(xyxy).view(1,4))/ gn).view(-1).tolist()# normalized xywh
  139. line =(cls,*xywh, conf)if save_conf else(cls,*xywh)# label formatwithopen(txt_path +'.txt','a')as f:
  140. f.write(('%g '*len(line)).rstrip()% line +'\n')# # 在原图上画框 + 将预测到的目标剪切出来 保存成图片 保存在save_dir/crops下 在原图像画图或者保存结果if save_img or save_crop or view_img:# Add bbox to image
  141. c =int(cls)# integer class
  142. label =Noneif hide_labels else(names[c]if hide_conf else f'{names[c]} {conf:.2f}')
  143. annotator.box_label(xyxy, label, color=colors(c,True))if save_crop:# 在原图上画框 + 将预测到的目标剪切出来 保存成图片 保存在save_dir/crops下
  144. save_one_box(xyxy, imc,file=save_dir /'crops'/ names[c]/ f'{p.stem}.jpg', BGR=True)# Stream results
  145. im0 = annotator.result()# 显示图片if view_img:
  146. cv2.imshow(str(p), im0)
  147. cv2.waitKey(1)# 1 millisecond# Save results (image with detections)# 保存图片if save_img:if dataset.mode =='image':
  148. cv2.imwrite(save_path, im0)else:# 'video' or 'stream'if vid_path[i]!= save_path:# new video
  149. vid_path[i]= save_path
  150. ifisinstance(vid_writer[i], cv2.VideoWriter):
  151. vid_writer[i].release()# release previous video writerif vid_cap:# video
  152. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  153. w =int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  154. h =int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))else:# stream
  155. fps, w, h =30, im0.shape[1], im0.shape[0]
  156. save_path =str(Path(save_path).with_suffix('.mp4'))# force *.mp4 suffix on results videos
  157. vid_writer[i]= cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps,(w, h))
  158. vid_writer[i].write(im0)# Print time (inference-only)
  159. LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')# Print results# 打印每张图片的速度
  160. t =tuple(x / seen *1E3for x in dt)# speeds per image
  161. LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}'% t)# 保存图片或者txtif save_txt or save_img:
  162. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}"if save_txt else''
  163. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")if update:
  164. strip_optimizer(weights)# update model (to fix SourceChangeWarning)defparse_opt():"""
  165. weights: 训练的权重路径,可以使用自己训练的权重,也可以使用官网提供的权重
  166. 默认官网的权重yolov5s.pt(yolov5n.pt/yolov5s.pt/yolov5m.pt/yolov5l.pt/yolov5x.pt/区别在于网络的宽度和深度以此增加)
  167. source: 测试数据,可以是图片/视频路径,也可以是'0'(电脑自带摄像头),也可以是rtsp等视频流, 默认data/images
  168. data: 配置数据文件路径, 包括image/label/classes等信息, 训练自己的文件, 需要作相应更改, 可以不用管
  169. 如果设置了只显示个别类别即使用了--classes = 0 或二者1, 2, 3等, 则需要设置该文件,数字和类别相对应才能只检测某一个类
  170. imgsz: 网络输入图片大小, 默认的大小是640
  171. conf-thres: 置信度阈值, 默认为0.25
  172. iou-thres: nmsiou阈值, 默认为0.45
  173. max-det: 保留的最大检测框数量, 每张图片中检测目标的个数最多为1000
  174. device: 设置设备CPU/CUDA, 可以不用设置
  175. view-img: 是否展示预测之后的图片/视频, 默认False, --view-img 电脑界面出现图片或者视频检测结果
  176. save-txt: 是否将预测的框坐标以txt文件形式保存, 默认False, 使用--save-txt 在路径runs/detect/exp*/labels/*.txt下生成每张图片预测的txt文件
  177. save-conf: 是否将置信度conf也保存到txt中, 默认False
  178. save-crop: 是否保存裁剪预测框图片, 默认为False, 使用--save-crop runs/detect/exp*/crop/剪切类别文件夹/ 路径下会保存每个接下来的目标
  179. nosave: 不保存图片、视频, 要保存图片,不设置--nosave runs/detect/exp*/会出现预测的结果
  180. classes: 设置只保留某一部分类别, 形如0或者0 2 3, 使用--classes = n, 则在路径runs/detect/exp*/下保存的图片为n所对应的类别, 此时需要设置data
  181. agnostic-nms: 进行NMS去除不同类别之间的框, 默认False
  182. augment: TTA测试时增强/多尺度预测, 可以提分
  183. visualize: 是否可视化网络层输出特征
  184. update: 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
  185. project: 保存测试日志的文件夹路径
  186. name: 保存测试日志文件夹的名字, 所以最终是保存在project/name
  187. exist_ok: 是否重新创建日志文件, False时重新创建文件
  188. line-thickness: 画框的线条粗细
  189. hide-labels: 可视化时隐藏预测类别
  190. hide-conf: 可视化时隐藏置信度
  191. half: 是否使用F16精度推理, 半进度提高检测速度
  192. dnn: OpenCV DNN预测
  193. """
  194. parser = argparse.ArgumentParser()
  195. parser.add_argument('--weights', nargs='+',type=str, default=ROOT /'yolov5s.pt',help='model path(s)')
  196. parser.add_argument('--source',type=str, default=ROOT /'data/images',help='file/dir/URL/glob, 0 for webcam')
  197. parser.add_argument('--data',type=str, default=ROOT /'data/coco128.yaml',help='(optional) dataset.yaml path')
  198. parser.add_argument('--imgsz','--img','--img-size', nargs='+',type=int, default=[640],help='inference size h,w')
  199. parser.add_argument('--conf-thres',type=float, default=0.25,help='confidence threshold')
  200. parser.add_argument('--iou-thres',type=float, default=0.45,help='NMS IoU threshold')
  201. parser.add_argument('--max-det',type=int, default=1000,help='maximum detections per image')
  202. parser.add_argument('--device', default='',help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  203. parser.add_argument('--view-img', action='store_true',help='show results')
  204. parser.add_argument('--save-txt', action='store_true',help='save results to *.txt')
  205. parser.add_argument('--save-conf', action='store_true',help='save confidences in --save-txt labels')
  206. parser.add_argument('--save-crop', action='store_true',help='save cropped prediction boxes')
  207. parser.add_argument('--nosave', action='store_true',help='do not save images/videos')
  208. parser.add_argument('--classes', nargs='+',type=int,help='filter by class: --classes 0, or --classes 0 2 3')
  209. parser.add_argument('--agnostic-nms', action='store_true',help='class-agnostic NMS')
  210. parser.add_argument('--augment', action='store_true',help='augmented inference')
  211. parser.add_argument('--visualize', action='store_true',help='visualize features')
  212. parser.add_argument('--update', action='store_true',help='update all models')
  213. parser.add_argument('--project', default=ROOT /'runs/detect',help='save results to project/name')
  214. parser.add_argument('--name', default='exp',help='save results to project/name')
  215. parser.add_argument('--exist-ok', action='store_true',help='existing project/name ok, do not increment')
  216. parser.add_argument('--line-thickness', default=3,type=int,help='bounding box thickness (pixels)')
  217. parser.add_argument('--hide-labels', default=False, action='store_true',help='hide labels')
  218. parser.add_argument('--hide-conf', default=False, action='store_true',help='hide confidences')
  219. parser.add_argument('--half', action='store_true',help='use FP16 half-precision inference')
  220. parser.add_argument('--dnn', action='store_true',help='use OpenCV DNN for ONNX inference')
  221. opt = parser.parse_args()# 扩充维度, 如果是一位就扩充一位
  222. opt.imgsz *=2iflen(opt.imgsz)==1else1# expand# 输出所有参数
  223. print_args(FILE.stem, opt)return opt
  224. defmain(opt):# 检查环境/打印参数,主要是requrement.txt的包是否安装,用彩色显示设置的参数
  225. check_requirements(exclude=('tensorboard','thop'))# 执行run()函数
  226. run(**vars(opt))if __name__ =="__main__":
  227. opt = parse_opt()
  228. main(opt)

5. 使用教程

  1. python detect.py --weights ./weights/yolov5s.pt --source ./data/test_images/--classes 5--save-txt --save-crop

在这里插入图片描述
在这里插入图片描述
crop文件夹下的文件
在这里插入图片描述
labels下面的文件
在这里插入图片描述


本文转载自: https://blog.csdn.net/CharmsLUO/article/details/123422822
版权归原作者 Charms@ 所有, 如有侵权,请联系我们删除。

“yolov5——detect.py代码【注释、详解、使用教程】”的评论:

还没有评论