# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
"""
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.

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

Usage - formats:
    $ python detect.py --weights yolov5s.pt                 # PyTorch
                                 yolov5s.torchscript        # TorchScript
                                 yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                 yolov5s_openvino_model     # 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
                                 yolov5s_paddle_model       # PaddlePaddle
"""

import argparse
import os
import platform
import sys
from pathlib import Path

import torch

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, smart_inference_mode

# 是一个装饰器,它用于自动切换模型的推理模式。如果模型是 FP16 模型,则自动切换为 FP16 推理模式,否则切换为 FP32 推理模式。这样可以避免模型推理时出现类型不匹配的错误。
@smart_inference_mode()
def run(
        weights=ROOT / 'yolov5s.pt',  # model path or triton URL
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(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
        vid_stride=1,  # video frame-rate stride
):
    ################################################# 1. 初始化配置 #####################################################
    source = str(source)
    # 是否保存图片和txt文件
    save_img = not nosave and not 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
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    # .lower()转化成小写 .upper()转化成大写 .title()首字符转化成大写,其余为小写, .startswith('http://')返回True or Flase
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    # .isnumeric()是否是由数字组成,返回True or False
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
    screenshot = source.lower().startswith('screen')
    if is_url and is_file:
        # 返回文件
        source = check_file(source)  # download

    # Directories
    # 预测路径是否存在,不存在新建,按照实验文件以此递增新建
    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 如果device为空,则自动选择设备
    device = select_device(device)
    # 加载模型,DetectMultiBackend()函数用于加载模型,weights为模型路径,device为设备,dnn为是否使用opencv dnn,data为数据集,fp16为是否使用fp16推理
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    # 获取模型的stride,names,pt
    stride, names, pt = model.stride, model.names, model.pt
    # 确保输入图片的尺寸imgsz能整除stride=32 如果不能则调整为能被整除并返回
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Dataloader 加载数据
    # 使用视频流或者页面
    bs = 1  # batch_size  初始化batch_size大小为1
    # 如果source是摄像头,则创建LoadStreams()对象
    if webcam:
        # 是否显示图片,如果view_img为True,则显示图片
        view_img = check_imshow(warn=True)
        # 创建LoadStreams()对象,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备,vid_stride为视频帧率
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
        # batch_size为数据集的长度
        bs = len(dataset)
    # 如果source是截图,则创建LoadScreenshots()对象
    elif screenshot:
        # 创建LoadScreenshots()对象,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
    else:
        # 创建LoadImages()对象,直接加载图片,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备,vid_stride为视频帧率
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
    # 初始化vid_path和vid_writer,vid_path为视频路径,vid_writer为视频写入对象
    vid_path, vid_writer = [None] * bs, [None] * bs
    ################################################# 2. 开始推理 ######################################################
    # Run inference 运行推理
    # warmup 预热 用于提前加载模型,加快推理速度,imgsz为图像大小,如果pt为True或者model.triton为True,则bs=1,否则bs为数据集的长度。3为通道数,*imgsz为图像大小,即(1,3,640,640)
    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmup
    # 初始化seen,windows,dt,seen为已检测的图片数量,windows为空列表,dt为时间统计对象
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
    # 遍历数据集,path为图片路径,im为图片,im0s为原始图片,vid_cap为视频读取对象,s为视频帧率
    for path, im, im0s, vid_cap, s in dataset:
        # 开始计时,读取图片
        with dt[0]:
            # 将图片转换为tensor,并放到模型的设备上,pytorch模型的输入必须是tensor
            im = torch.from_numpy(im).to(model.device)
            # 如果模型使用fp16推理,则将图片转换为fp16,否则转换为fp32
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            # 将图片归一化,将图片像素值从0-255转换为0-1
            im /= 255  # 0 - 255 to 0.0 - 1.0
            # 如果图片的维度为3,则添加batch维度
            if len(im.shape) == 3:
                # 在前面添加batch维度,即将图片的维度从3维转换为4维,即(3,640,640)转换为(1,3,640,640),pytorch模型的输入必须是4维的
                im = im[None]  # expand for batch dim
        # Inference
        # 开始计时,推理时间
        with dt[1]:
            # 如果visualize为True,则创建visualize文件夹,否则为False
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            # 推理,model()函数用于推理,im为输入图片,augment为是否使用数据增强,visualize为是否可视化,输出pred为一个列表,形状为(n,6),n代表预测框的数量,6代表预测框的坐标和置信度,类别
            pred = model(im, augment=augment, visualize=visualize)

        # NMS  非极大值抑制,用于去除重复的预测框
        # 开始计时,推理时间
        with dt[2]:
            # NMS,non_max_suppression()函数用于NMS,pred为输入的预测框,conf_thres为置信度阈值,iou_thres为iou阈值,classes为类别,agnostic_nms为是否使用类别无关的NMS,max_det为最大检测框数量,
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)

        # Second-stage classifier (optional)  第二阶段分类器(可选)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        # Process predictions  处理预测结果
        # per image,遍历每张图片,enumerate()函数将pred转换为索引和值的形式,i为索引,det为对应的元素,即每个物体的预测框
        for i, det in enumerate(pred):  # per image
            # 检测的图片数量加1
            seen += 1
            # 如果是摄像头,则获取视频帧率
            if webcam:  # batch_size >= 1
                # path[i]为路径列表,ims[i].copy()为将输入图像的副本存储在im0变量中,dataset.count为当前输入图像的帧数
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                # 在打印输出中添加当前处理的图像索引号i,方便调试和查看结果。在此处,如果是摄像头模式,i表示当前批次中第i张图像;否则,i始终为0,因为处理的只有一张图像。
                s += f'{i}: '
            else:
                # 如果不是摄像头,frame为0
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            # 将路径转换为Path对象
            p = Path(p)  # to Path
            # 保存图片的路径,save_dir为保存图片的文件夹,p.name为图片名称
            save_path = str(save_dir / p.name)  # im.jpg
            # 保存预测框的路径,save_dir为保存图片的文件夹,p.stem为图片名称,dataset.mode为数据集的模式,如果是image,则为图片,否则为视频
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            # 打印输出,im.shape[2:]为图片的宽和高
            s += '%gx%g ' % im.shape[2:]  # print string
            # 归一化因子,用于将预测框的坐标从归一化坐标转换为原始坐标
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            # 如果save_crop为True,则将im0复制一份,否则为im0
            imc = im0.copy() if save_crop else im0  # for save_crop
            # 创建Annotator对象,用于在图片上绘制预测框和标签,im0为输入图片,line_width为线宽,example为标签
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
            # 如果预测框的数量大于0
            if len(det):
                # 将预测框的坐标从归一化坐标转换为原始坐标,im.shape[2:]为图片的宽和高,det[:, :4]为预测框的坐标,im0.shape为图片的宽和高
                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()  # Rescale boxes from img_size to im0 size

                # Print results  打印输出结果
                # 遍历每个类别,unique()用于获取检测结果中不同类别是数量
                for c in det[:, 5].unique():
                    # n为每个类别的预测框的数量
                    n = (det[:, 5] == c).sum()  # detections per class
                    # s为每个类别的预测框的数量和类别
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results  写入结果
                # 遍历每个预测框,xyxy为预测框的坐标,conf为置信度,cls为类别,reversed()函数用于将列表反转,*是一个扩展语法,*xyxy表示将xyxy中的元素分别赋值给x1,y1,x2,y2
                for *xyxy, conf, cls in reversed(det):
                    # 如果save_txt为True,则将预测框的坐标和类别写入txt文件中
                    if save_txt:  # Write to file
                        # normalized xywh,将预测框的坐标从原始坐标转换为归一化坐标
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        # label format,如果save_conf为True,则将置信度也写入txt文件中
                        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                        with open(f'{txt_path}.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\\n')

                    # 如果save_img为True,则将预测框和标签绘制在图片上
                    if save_img or save_crop or view_img:  # Add bbox to image
                        # 获取类别
                        c = int(cls)  # integer class
                        # 如果hide_labels为True,则不显示标签,否则显示标签,如果hide_conf为True,则不显示置信度,否则显示置信度
                        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))
                    # 如果save_crop为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()
            # 如果view_img为True,则展示图片
            if view_img:
                # 如果系统为Linux,且p不在windows中
                if platform.system() == 'Linux' and p not in windows:
                    # 将p添加到windows中
                    windows.append(p)
                    # 允许窗口调整大小,WINDOW_NORMAL表示用户可以调整窗口大小,WINDOW_KEEPRATIO表示窗口大小不变
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
                    # 调整窗口大小,使其与图片大小一致
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            # 如果save_img为True,则保存图片
            if save_img:
                # 如果数据集模式为image
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                # 如果数据集模式为video或stream
                else:  # 'video' or 'stream'
                    # 如果vid_path[i]不等于save_path
                    if vid_path[i] != save_path:  # new video
                        # 将save_path赋值给vid_path[i]
                        vid_path[i] = save_path
                        # 如果vid_writer[i]是cv2.VideoWriter类型
                        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}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")

    # Print results  打印输出结果
    # 每张图片的速度
    t = tuple(x.t / 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:
        # 如果save_txt为True,则打印保存的标签数量
        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[0])  # update model (to fix SourceChangeWarning)

def parse_opt():
    parser = argparse.ArgumentParser()
    # weights: 训练的权重路径,可以使用自己训练的权重,也可以使用官网提供的权重
    # 默认官网的权重yolov5s.pt(yolov5n.pt/yolov5s.pt/yolov5m.pt/yolov5l.pt/yolov5x.pt/区别在于网络的宽度和深度以此增加)
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')
    # source: 测试数据,可以是图片/视频路径,也可以是'0'(电脑自带摄像头),也可以是rtsp等视频流, 默认data/images
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
    # data: 配置数据文件路径, 包括image/label/classes等信息, 训练自己的文件, 需要作相应更改, 可以不用管
    # 如果设置了只显示个别类别即使用了--classes = 0 或二者1, 2, 3等, 则需要设置该文件,数字和类别相对应才能只检测某一个类
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    # imgsz: 网络输入图片大小, 默认的大小是640
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    # conf-thres: 置信度阈值, 默认为0.25
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    # iou-thres:  做nms的iou阈值, 默认为0.45
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    # max-det: 保留的最大检测框数量, 每张图片中检测目标的个数最多为1000类
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    # device: 设置设备CPU/CUDA, 可以不用设置
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    # view-img: 是否展示预测之后的图片/视频, 默认False, --view-img 电脑界面出现图片或者视频检测结果
    parser.add_argument('--view-img', action='store_true', help='show results')
    # save-txt: 是否将预测的框坐标以txt文件形式保存, 默认False, 使用--save-txt 在路径runs/detect/exp*/labels/*.txt下生成每张图片预测的txt文件
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    # save-conf: 是否将置信度conf也保存到txt中, 默认False
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    # save-crop: 是否保存裁剪预测框图片, 默认为False, 使用--save-crop 在runs/detect/exp*/crop/剪切类别文件夹/ 路径下会保存每个接下来的目标
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    # nosave: 不保存图片、视频, 要保存图片,不设置--nosave 在runs/detect/exp*/会出现预测的结果
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    # classes: 设置只保留某一部分类别, 形如0或者0 2 3, 使用--classes = n, 则在路径runs/detect/exp*/下保存的图片为n所对应的类别, 此时需要设置data
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    # agnostic-nms: 进行NMS去除不同类别之间的框, 默认False
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    # augment: TTA测试时增强/多尺度预测
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    # visualize: 是否可视化网络层输出特征
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    # update: 如果为True,则对所有模型进行strip_optimizer操作,去除pt文件中的优化器等信息,默认为False
    parser.add_argument('--update', action='store_true', help='update all models')
    # project:保存测试日志的文件夹路径      即:本代码全部日志保存在该project文件夹中
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    # name:保存测试日志文件夹的名字, 所以最终是保存在project/name中      即:每一次的日志保存在project/name文件中
    parser.add_argument('--name', default='exp', help='save results to project/name')
    # exist_ok: 是否重新创建日志文件, False时重新创建文件
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    # line-thickness: 画框的线条粗细
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    # hide-labels: 可视化时隐藏预测类别
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    # hide-conf: 可视化时隐藏置信度
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    # half: 是否使用F16精度推理, 半进度提高检测速度
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    # dnn: 用OpenCV DNN预测
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    # vid-stride: 用于指定视频帧率步长。它的默认值为 1,这意味着处理视频时将处理每一帧。如果你将其设置为大于 1 的值,例如 2,则只会处理视频中每两帧中的一帧。这样可以加快处理速度,但可能会降低检测精度。
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(vars(opt))
    return opt

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

if __name__ == '__main__':
    opt = parse_opt()
    main(opt)