yolov5-6.1版本detect.py文件部分解释

# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Run inference on images, videos, directories, streams, etc.

Usage - sources:
    $ python path/to/detect.py --weights yolov5s.pt --source 0              # webcam
                                                             img.jpg        # image
                                                             vid.mp4        # video
                                                             path/          # directory
                                                             path/*.jpg     # glob
                                                             'https://youtu.be/Zgi9g1ksQHc'  # YouTube
                                                             'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream

Usage - formats:
    $ python path/to/detect.py --weights yolov5s.pt                 # PyTorch
                                         yolov5s.torchscript        # TorchScript
                                         yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                         yolov5s.xml                # OpenVINO
                                         yolov5s.engine             # TensorRT
                                         yolov5s.mlmodel            # CoreML (MacOS-only)
                                         yolov5s_saved_model        # TensorFlow SavedModel
                                         yolov5s.pb                 # TensorFlow GraphDef
                                         yolov5s.tflite             # TensorFlow Lite
                                         yolov5s_edgetpu.tflite     # TensorFlow Edge TPU
"""
# 执行第一步:
# 导入下载好的模块
import argparse
import os
import sys
from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn

# __file__:当前执行文件的路径,.resolve():获取绝对路径:D:\DeepLearning\jieshi\yolov5-6.1\delect.py
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # .parents():路径的父目录;D:\DeepLearning\jieshi\yolov5-6.1
if str(ROOT) not in sys.path:  # sys.path是python的搜索模块的路径集,是一个列表list
    sys.path.append(str(ROOT))  # sys.path.append():添加相关路径,但在退出python环境后自己添加的路径就会消失
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # 将绝对路径转变为相对目录,后面会用到
'''
 先要确保模块的查询路径在sys.path中,这样下面的如models.common在导入的时候才会根据这个路径列表去导包
 否则models.common不知道从哪里导入
'''
from models.common import DetectMultiBackend
from utils.datasets import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync


@torch.no_grad()
def run(weights=ROOT / 'yolov5s.pt',  # model.pt path(s)
        source=ROOT / 'data/images',  # file/dir/URL/glob, 0 for webcam
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=False,  # save results to *.txt
        save_conf=False,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        ):
    # --------------------run--第1步:对传入的source参数进行一个判断--------------------------------
    '''
    就是对传入的source参数进行解析:
    第一行: 解析命令行执行python delect.py --source data\\images\\bus.jpg时所传入的参数,
           就是获取图片路径啦,路径要始终是字符串类型,所以str()强制转换;
    第二行:判断是否要保存预测后图片
          not nosave=not flase=true(nosave是上面传入进来的参数,nosave=False)
          not source.endswith('.txt')=flase 传入的参数是否是txt格式,传入的是.jpg格式,显然不是
          所以图片是否保存标志位:save_img=true
    第三行:判断传入的图片格式是否是文件,例如jpg文件  is_file=true
           Path(source).suffix[1:] 判断路径的后缀(jpg)
    第四行:判断传入的地址是不是网络流,是不是一个网络地址
           先转换为小写,再判断开头是否以rtsp://', 'rtmp://', 'http://', 'https://开头
    第五行:webcam =flase
           source.isnumeric() 地址是不是数字 如果是--source 0,后面是0,表示打开电脑摄像头
    第六行:如果是网络流地址 或者是文件 就去相应的地址下载图片
    '''
    source = str(source)
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
    if is_url and is_file:  # 如果是网络流地址 或者是文件 就去相应的地址下载图片
        source = check_file(source)  # download

    # Directories
    # ----------------------run--第2步:新建一个保存结果的文件夹-----------------------------
    '''
    第一行:project=ROOT / 'runs/detect'为传入的参数,name=exp为传入的参数 将两个拼接起来作为保存的地址
           其中父目录:ROOT=D:\DeepLearning\jieshi\yolov5-6.1,在一开始我们就指定好了
           所以完整的路径: D:\DeepLearning\jieshi\yolov5-6.1   +  \ runs\detect    +\exp
           increment_path为增量式路径,简单来说,第一次运行的预测结果保存在exp中,第二次运行结果保存在exp2中,以此类推
    '''
    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
    # -------------------------run--第3步:加载模型的权重----------------------------------
    '''
    第一行;选择运行的设备 GPU or cpu
    第二行;选择学习框架,例如:PyTorch TorchScript TensorRT等,可以按住Ctrl单击函数进入查看 
        传入weights训练权重为yolov5s.pt,设备,
    第三行:读取模型属性:步长stride=32  类型名names=80 模型类型pt=true,表示是PyTorch类型
    第四行:核实图片的尺寸大小是否是步长32的倍数,这里是640*640,所以imgsz =640,不用修改,否则会给一个合适的值
    '''
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data)
    stride, names, pt, jit, onnx, engine = model.stride, model.names, model.pt, model.jit, model.onnx, model.engine
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Half
    half &= (pt or jit or onnx or engine) and device.type != 'cpu'  # FP16 supported on limited backends with CUDA
    if pt or jit:
        model.model.half() if half else model.model.float()

    # Dataloader
    # ----------------------------run--第4步:加载待预测的图片-----------------------
    if webcam:   # webcam =flase 不执行
        view_img = check_imshow()
        cudnn.benchmark = True  # set True to speed up constant image size inference
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
        bs = len(dataset)  # batch_size
    else:  # 直接执行这里
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)  # 该函数主要负责的是图片或者视频的处理
        bs = 1  # batch_size=1 表示每次输入一张图片
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    # -----------------------------run--第5步:预测推理部分---------------------------
    # warmup:GPU热身环节,随便给一张图片,先跑一遍
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz), half=half)  # warmup
    dt, seen = [0.0, 0.0, 0.0], 0  # dt用于保存运行时间
    ''' 
    # path要预测的图片的路径
    im表示resize后的图片[3,640,480]
    im0s表示原图[3,1080,810]
    vid_cap=none
    s为打印信息,运行时候输出第几张图片,一共有几张,图片路径 时间
    '''
    for path, im, im0s, vid_cap, s in dataset:  # path要预测的图片的路径
        t1 = time_sync()   # 获取系统当前时间
        # 对图片进行预处理
        im = torch.from_numpy(im).to(device)  # im resize后的图片,[3,640,480] 转成PyTorch支持的格式,然后to转到GPU上
        im = im.half() if half else im.float()  # uint8 to fp16/32 判断模型有没有用到半精度
        im /= 255  # 0 - 255 to 0.0 - 1.0  所有像素点/255,归一化操作
        if len(im.shape) == 3: #扩增张量为 [1,3,640,480]
            im = im[None]  # expand for batch dim
        t2 = time_sync()   # 获取系统当前时间
        dt[0] += t2 - t1   # 上面这个部分耗时保存

        # Inference
        '''
        第一行:visualize默认Flase,如果是True,则在模型推断的过程中将特征图保存下来、
        第二行:augment,表示是否要进行数据增强,增强会耗时
               这两个参数传入到模型中去
                然后得到 pred,其大小为torch.size=[1,18900,85] 
                18900表示预测框的个数,85表示(x1,y1,x2,y2,c,80个类别的概率) 对应左上角以及右下角坐标
        '''
        visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
        pred = model(im, augment=augment, visualize=visualize) # 模型预测出来的所有检测框,torch.size=[1,18900,85]
        t3 = time_sync()
        dt[1] += t3 - t2

        # NMS
        '''
        根据conf_thres置信度,iou_thres阈值过滤之前得到的18900个预测框,其中,
        # Apply NMS  进行NMS
        # conf_thres: 置信度阈值
        # iou_thres: iou阈值
        # classes: 是否只保留特定的类别 默认为None
        # agnostic_nms: 进行nms是否也去除不同类别之间的框
        # max_det: 每张图片的最大目标个数 默认1000
        '''
        # pred是一个,每个图像(n,6)的一个张量:[x,y,x,y, conf, cls]   n=5个预测框
        # pred[0:4]为box坐标,pred[4]为置信度,pred[5:5 + cls]为每类任务得分
        # 5 表示预测框从18900降低到5个预测框
        # pred得到5个检测框,每个检测框有6个信息,分别是(左上角x,左上角y,右下角x,右下角y,置信度,类别)
        # 举例:
        # [6.72000e+0.2,3.59000e+0.2,8.17000e+0.2,8.78000e+0.2,8.96172e-0.1,0.00000e+0.0]
        #   左上角x         左上角y          右下角x       右下角y         置信度        类别
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        dt[2] += time_sync() - t3

        # Process predictions
        for i, det in enumerate(pred):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # im.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == 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
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))
                        if save_crop:
                            save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # Stream results
            im0 = annotator.result()
            if view_img:
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path[i] != save_path:  # new video
                        vid_path[i] = save_path
                        if isinstance(vid_writer[i], cv2.VideoWriter):
                            vid_writer[i].release()  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer[i].write(im0)

        # Print time (inference-only)
        LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')

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


'''
我们常常可以把argparse的使用简化成下面四个步骤
1:import argparse 
2:parser = argparse.ArgumentParser()
3:parser.add_argument()
4:parser.parse_args()
上面四个步骤解释如下:
首先导入该模块;
然后创建一个解析对象;我感觉相当于java 中的实例
然后向该对象中添加你要关注的命令行参数和选项,每一个add_argument方法对应一个你要关注的参数或选项;
最后调用parse_args()方法进行解析;解析成功之后即可使用。
'''


def parse_opt():
    parser = argparse.ArgumentParser()  # 建立解析对象,实例化一个对象parser
    #  增加属性:给parser实例对象增加n个属性,如下都是属性(参数)
    # --这两个横杠表示可选参数  后面包括指定参数类型  默认值
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default='1', help='file/dir/URL/glob, 0 for webcam')
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    # 将属性给args实例: 把parser中设置的所有"add_argument"给返回到opt子类实例当中,
    # 那么parser中增加的属性内容都会在opt实例中,使用即可
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # 这里不是很理解,大概就是对输入的图片大小进行判断
    print_args(FILE.stem, opt)  # 打印所有的参数信息
    return opt  # opt保存所有的参数的一个变量,


# 执行的第三步:主程序入口
def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))  # 判断环境所依赖的包,就是requirements.txt中的依赖项目
    run(**vars(opt))  # 将参数又传给run,run函数包含程序加载预测保存等功能,下一步我们去看run,往上翻


# 执行的第二步:
if __name__ == "__main__":
    # opt = parse_opt():解析终端命令行的参数,例如;python delect.py --source data\\images\\bus.jpg
    # 如果命令行没有写明的参数,会执行def parse_opt():中的默认参数,就是上面绿色字体的那部分
    opt = parse_opt()  # 返回值:所有的参数
    main(opt)  # 将参数又传给主函数 main

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值