史上最详细YOLOv5的predict.py逐句讲解

代码为YOLOv5-v7.0


前言

YOLOv5-v7.0将分类脱离出来了。predict.py为分类的推理代码。predict.py主要有run(),parse_opt(),main()三个函数构成。


一、导入模块

这部分导入python模块与YOLO的自定义模块。

##############################################导入相关python模块##############################################
import argparse  # argparse模块的作用是用于解析命令行参数,例如python test.py --port=8080
import os  # os模块提供了非常丰富的方法用来处理文件和目录
import platform # platform模块用于获取操作系统的名称、版本号、位数等信息
import sys  # sys模块提供了对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数,例如sys.exit()函数
from pathlib import Path # pathlib模块提供了一种对象化的路径操作方式,可以用来替代os.path模块,Path能更加方便对字符串路径进行操作

import torch  #pytorch框架
import torch.nn.functional as F  #pytorch框架中的函数库,主要用于激活函数
############################################获取当前文件的绝对路径############################################
FILE = Path(__file__).resolve()   #当前文件(__file__)路径的绝对路径
ROOT = FILE.parents[1]  # YOLOv5 root directory,即当前文件的上两级目录,即项目根目录
if str(ROOT) not in sys.path: # 如果项目根目录不在sys.path中,sys.path为python环境可以运行的路径
    sys.path.append(str(ROOT))  # add ROOT to PATH,将项目根目录添加到sys.path中
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative,将项目根目录转换为相对路径
###########################################加载自定义的模块################################################
from models.common import DetectMultiBackend  # 导入DetectMultiBackend类,用于在各种后端上进行Python推理
from utils.augmentations import classify_transforms  # 导入classify_transforms函数,用于对图片进行预处理
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, print_args, strip_optimizer)  #定义了一些通用函数,用于打印日志、检查文件、图片大小等
from utils.plots import Annotator  # 导入Annotator类,用于在图片上绘制标注框
from utils.torch_utils import select_device, smart_inference_mode  # 导入select_device函数,用于选择设备,smart_inference_mode函数,用于智能推理模式

二、parse_opt()函数

它使用了 argparse 库解析命令行参数。这个函数接收用户给定的命令行参数,并将其转换为 Python 变量的形式,以便在代码中进行进一步的处理。

这个函数使用了 argparse 库中的 ArgumentParser 类来创建一个解析器对象,并使用 add_argument 方法添加命令行参数。

最后,这个函数将解析器对象的结果保存到 opt 变量中,并返回这个变量。Python 脚本的其他部分可以使用 opt 变量的值来控制程序的行为。

def parse_opt():
    """
    weights: 模型路径
    source: 分类源路径,0为摄像头
    data:数据集路径,分类时不需要
    imgsz: 图片大小,通常与训练时的图片大小一致,以便保持模型的一致性
    device: 设备,cpu或者gpu
    view-img: 是否显示结果图片
    save-txt: 是否保存结果文本,结果为图片的概率和类别
    nasave: 是否不保存结果图片
    augment:是否进行推理时数据增强,分类时不需要
    visualize: 是否可视化,分类时不需要
    update: 是否更新模型
    project: 项目路径
    name: 保存结果的文件夹名称
    exist-ok: 是否覆盖已存在的文件夹
    half: 是否使用半精度推理
    dnn: 是否使用dnn加速
    vid-stride: 视频帧间隔
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train-cls/exp12/weights/best.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(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=[224], help='inference size h,w')
    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', default=True,action='store_true', help='save results to *.txt')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    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/predict-cls', 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('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    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 # 返回参数

三、run()函数

定义主函数

@smart_inference_mode()   # 用于自动切换模型的推理模式,如果是FP16模型,则自动切换为FP16推理模式,否则切换为FP32推理模式,这样可以避免模型推理时出现类型不匹配的错误
#############################################定义主函数####################################################
#传入参数,参数可通过命令行传入,也可通过代码传入,parser.add_argument()函数用于添加参数
def run(
        weights=ROOT / 'yolov5s-cls.pt',  # model.pt path(s)
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(224, 224),  # inference size (height, width)
        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
        nosave=False,  # do not save images/videos
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/predict-cls',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        vid_stride=1,  # video frame-rate stride
):
    source = str(source)  # source to string,将source转换为字符串
    save_img = not nosave and not source.endswith('.txt')  # save inference images,如果nasave为False且source不是txt文件,则保存图片
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)  #Path.suffix[1:]返回文件的后缀jpg、jepg等,如果后缀在IMG_FORMATS或VID_FORMATS中,则is_file为True
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) #判断source是否是url,如果是,则is_url为True.lower()将字符串转换为小写,startswith()判断字符串是否以指定的字符串开头
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file) #source.isnumeric()判断source是否是数字,source.endswith('.streams')判断source是否以.streams结尾,(is_url and not is_file)判断source是否是url,且不是文件,上述三个条件有一个为True,则webcam为True。
    screenshot = source.lower().startswith('screen')  #判断source是否是截图,如果是,则screenshot为True
    if is_url and is_file:
        source = check_file(source)  # download,确保输入源为本地文件,如果是url,则下载到本地,check_file()函数用于下载url文件

 创建保存目录

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run,# increment run,增加文件或目录路径,即运行/exp——>运行/exp{sep}2,运行/exp{sep}3,…等。exist_ok为True时,如果文件夹已存在,则不会报错
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir,创建文件夹,如果save_txt为True,则创建labels文件夹,否则创建save_dir文件夹

加载模型

    # Load model
    device = select_device(device)    #选择设备,如果device为空,则自动选择设备,如果device不为空,则选择指定的设备
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)          #加载模型,DetectMultiBackend()函数用于加载模型,weights为模型路径,device为设备,dnn为是否使用opencv dnn,data为数据集,fp16为是否使用fp16推理
    stride, names, pt = model.stride, model.names, model.pt    #获取模型的stride,names,pt,model.stride为模型的stride,model.names为模型的类别,model.pt为模型的类型
    imgsz = check_img_size(imgsz, s=stride)  # check image size,验证图像大小是每个维度的stride=32的倍数

 初始化数据集

    # Dataloader,初始化数据集
    bs = 1  # batch_size,初始化batch_size为1
    if webcam:                                    #如果source是摄像头,则创建LoadStreams()对象
        view_img = check_imshow(warn=True)        #是否显示图片,如果view_img为True,则显示图片
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)        #创建LoadStreams()对象,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备,vid_stride为视频帧率
        bs = len(dataset)                         #batch_size为数据集的长度
    elif screenshot:                              #如果source是截图,则创建LoadScreenshots()对象
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)                          #创建LoadScreenshots()对象,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备
    else:
        dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)       #创建LoadImages()对象,直接加载图片,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备,vid_stride为视频帧率
    vid_path, vid_writer = [None] * bs, [None] * bs               #初始化vid_path和vid_writer,vid_path为视频路径,vid_writer为视频写入对象

 开始推理

################################################################开始推理################################################################
    # Run inference
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup,预热,用于提前加载模型,加快推理速度,imgsz为图像大小,如果pt为True或者model.triton为True,则bs=1,否则bs为数据集的长度。3为通道数,*imgsz为图像大小,即(1,3,224,224)
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) # seen为已推理的图片数量,windows为空列表,dt为时间统计对象
    for path, im, im0s, vid_cap, s in dataset: #遍历数据集,path为图片路径,im为图片,im0s为原始图片,vid_cap为视频读取对象,s为视频帧率
        with dt[0]:                            #开始计时,读取图片时间
            im = torch.Tensor(im).to(model.device)   #将图片转换为tensor,并放到模型的设备上,pytorch模型的输入必须是tensor
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32,如果模型使用fp16推理,则将图片转换为fp16,否则转换为fp32
            if len(im.shape) == 3:              #如果图片维度为3,则添加batch维度
                im = im[None]  # expand for batch dim,在前面添加batch维度,即将图片的维度从3维转换为4维,即(3,640,640)转换为(1,3,224,224),pytorch模型的输入必须是4维的
        # Inference,推理
        with dt[1]:
            results = model(im)   #推理,results为推理结果

        # Post-process
        with dt[2]:
            pred = F.softmax(results, dim=1)  # probabilities,对推理结果进行softmax,得到每个类别的概率

 处理预测结果

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

            p = Path(p)  # to Path                             #将路径转换为Path对象
            save_path = str(save_dir / p.name)  # im.jpg,保存图片的路径,save_dir为保存图片的文件夹,p.name为图片名称
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt,保存预测框的路径,save_dir为保存图片的文件夹,p.stem为图片名称,dataset.mode为数据集的模式,如果是image,则为图片,否则为视频

            s += '%gx%g ' % im.shape[2:]  # print string,打印输出,im.shape[2:]为图片的大小,即(1,3,224,224)中的(224,224)
            annotator = Annotator(im0, example=str(names), pil=True) # Annotator()对象,用于在图片上绘制分类结果,im0为原始图片,example为类别名称,pil为是否使用PIL绘制

            # Print results
            top5i = prob.argsort(0, descending=True)[:5].tolist()  # top 5 indices,对概率进行排序,取前5个,top5i为前5个类别的索引
            s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "   #打印输出,names[j]为类别名称,prob[j]为概率
            # Write results
            text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)     #将类别名称和概率拼接成字符串,用于保存到txt文件中
            if save_img or view_img:  # Add bbox to image,如果保存图片或者显示图片,则在图片上绘制预测框
                annotator.text((32, 32), text, txt_color=(255, 255, 255)) #将预测结果绘制在图片上
            if save_txt:  # Write to file,如果保存txt文件,则将预测结果保存到txt文件中
                with open(f'{txt_path}.txt', 'a') as f:     #以追加的方式打开txt文件
                    f.write(text + '\n')                    #将预测结果写入txt文件中

 保存结果

            # Stream results,如果是摄像头,则显示图片
            im0 = annotator.result()     #获取绘制预测结果和标签的图片
            if view_img:                                                    #如果view_img为True,则展示图片
                if platform.system() == 'Linux' and p not in windows:          #如果系统为Linux,且p不在windows中
                    windows.append(p)                                           #将p添加到windows中
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux),允许窗口调整大小,WINDOW_NORMAL表示用户可以调整窗口大小,WINDOW_KEEPRATIO表示窗口大小不变
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])             #调整窗口大小,使其与图片大小一致
                cv2.imshow(str(p), im0)                                               #显示图片
                cv2.waitKey(1)  # 1 millisecond                                        #等待1毫秒

            # Save results (image with detections)
            if save_img:                                                                   #如果save_img为True,则保存图片
                if dataset.mode == 'image':                                                 #如果数据集模式为image
                    cv2.imwrite(save_path, im0)                                            #保存图片
                else:  # 'video' or 'stream',如果数据集模式为video或stream
                    if vid_path[i] != save_path:  # new video,如果vid_path[i]不等于save_path
                        vid_path[i] = save_path    #将save_path赋值给vid_path[i]
                        if isinstance(vid_writer[i], cv2.VideoWriter):                #如果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 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:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''     #如果save_txt为True,则打印保存的标签数量
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")                                                 #打印保存的路径
    if update:
        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)                                      #更新模型

四、main()函数

def main(opt):   # 主函数
    check_requirements(exclude=('tensorboard', 'thop'))   # check_requirements()函数检查是否安装了必要的库,exclude参数用于排除不需要的库
    run(**vars(opt)) # run()函数用于执行推理任务,vars()函数用于将对象转换为字典

五、完整的代码

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

Usage - sources:
    $ python classify/predict.py --weights yolov5s-cls.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 classify/predict.py --weights yolov5s-cls.pt                 # PyTorch
                                           yolov5s-cls.torchscript        # TorchScript
                                           yolov5s-cls.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                           yolov5s-cls_openvino_model     # OpenVINO
                                           yolov5s-cls.engine             # TensorRT
                                           yolov5s-cls.mlmodel            # CoreML (macOS-only)
                                           yolov5s-cls_saved_model        # TensorFlow SavedModel
                                           yolov5s-cls.pb                 # TensorFlow GraphDef
                                           yolov5s-cls.tflite             # TensorFlow Lite
                                           yolov5s-cls_edgetpu.tflite     # TensorFlow Edge TPU
                                           yolov5s-cls_paddle_model       # PaddlePaddle
"""
##############################################导入相关python模块##############################################
import argparse  # argparse模块的作用是用于解析命令行参数,例如python test.py --port=8080
import os  # os模块提供了非常丰富的方法用来处理文件和目录
import platform # platform模块用于获取操作系统的名称、版本号、位数等信息
import sys  # sys模块提供了对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数,例如sys.exit()函数
from pathlib import Path # pathlib模块提供了一种对象化的路径操作方式,可以用来替代os.path模块,Path能更加方便对字符串路径进行操作

import torch  #pytorch框架
import torch.nn.functional as F  #pytorch框架中的函数库,主要用于激活函数
############################################获取当前文件的绝对路径############################################
FILE = Path(__file__).resolve()   #当前文件(__file__)路径的绝对路径
ROOT = FILE.parents[1]  # YOLOv5 root directory,即当前文件的上两级目录,即项目根目录
if str(ROOT) not in sys.path: # 如果项目根目录不在sys.path中,sys.path为python环境可以运行的路径
    sys.path.append(str(ROOT))  # add ROOT to PATH,将项目根目录添加到sys.path中
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative,将项目根目录转换为相对路径
###########################################加载自定义的模块################################################
from models.common import DetectMultiBackend  # 导入DetectMultiBackend类,用于在各种后端上进行Python推理
from utils.augmentations import classify_transforms  # 导入classify_transforms函数,用于对图片进行预处理
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, print_args, strip_optimizer)  #定义了一些通用函数,用于打印日志、检查文件、图片大小等
from utils.plots import Annotator  # 导入Annotator类,用于在图片上绘制标注框
from utils.torch_utils import select_device, smart_inference_mode  # 导入select_device函数,用于选择设备,smart_inference_mode函数,用于智能推理模式


@smart_inference_mode()   # 用于自动切换模型的推理模式,如果是FP16模型,则自动切换为FP16推理模式,否则切换为FP32推理模式,这样可以避免模型推理时出现类型不匹配的错误
#############################################定义主函数####################################################
#传入参数,参数可通过命令行传入,也可通过代码传入,parser.add_argument()函数用于添加参数
def run(
        weights=ROOT / 'yolov5s-cls.pt',  # model.pt path(s)
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(224, 224),  # inference size (height, width)
        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
        nosave=False,  # do not save images/videos
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/predict-cls',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        vid_stride=1,  # video frame-rate stride
):
    source = str(source)  # source to string,将source转换为字符串
    save_img = not nosave and not source.endswith('.txt')  # save inference images,如果nasave为False且source不是txt文件,则保存图片
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)  #Path.suffix[1:]返回文件的后缀jpg、jepg等,如果后缀在IMG_FORMATS或VID_FORMATS中,则is_file为True
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')) #判断source是否是url,如果是,则is_url为True.lower()将字符串转换为小写,startswith()判断字符串是否以指定的字符串开头
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file) #source.isnumeric()判断source是否是数字,source.endswith('.streams')判断source是否以.streams结尾,(is_url and not is_file)判断source是否是url,且不是文件,上述三个条件有一个为True,则webcam为True。
    screenshot = source.lower().startswith('screen')  #判断source是否是截图,如果是,则screenshot为True
    if is_url and is_file:
        source = check_file(source)  # download,确保输入源为本地文件,如果是url,则下载到本地,check_file()函数用于下载url文件

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run,# increment run,增加文件或目录路径,即运行/exp——>运行/exp{sep}2,运行/exp{sep}3,…等。exist_ok为True时,如果文件夹已存在,则不会报错
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir,创建文件夹,如果save_txt为True,则创建labels文件夹,否则创建save_dir文件夹

    # Load model
    device = select_device(device)    #选择设备,如果device为空,则自动选择设备,如果device不为空,则选择指定的设备
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)          #加载模型,DetectMultiBackend()函数用于加载模型,weights为模型路径,device为设备,dnn为是否使用opencv dnn,data为数据集,fp16为是否使用fp16推理
    stride, names, pt = model.stride, model.names, model.pt    #获取模型的stride,names,pt,model.stride为模型的stride,model.names为模型的类别,model.pt为模型的类型
    imgsz = check_img_size(imgsz, s=stride)  # check image size,验证图像大小是每个维度的stride=32的倍数

    # Dataloader,初始化数据集
    bs = 1  # batch_size,初始化batch_size为1
    if webcam:                                    #如果source是摄像头,则创建LoadStreams()对象
        view_img = check_imshow(warn=True)        #是否显示图片,如果view_img为True,则显示图片
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)        #创建LoadStreams()对象,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备,vid_stride为视频帧率
        bs = len(dataset)                         #batch_size为数据集的长度
    elif screenshot:                              #如果source是截图,则创建LoadScreenshots()对象
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)                          #创建LoadScreenshots()对象,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备
    else:
        dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)       #创建LoadImages()对象,直接加载图片,source为输入源,img_size为图像大小,stride为模型的stride,auto为是否自动选择设备,vid_stride为视频帧率
    vid_path, vid_writer = [None] * bs, [None] * bs               #初始化vid_path和vid_writer,vid_path为视频路径,vid_writer为视频写入对象

################################################################开始推理################################################################
    # Run inference
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup,预热,用于提前加载模型,加快推理速度,imgsz为图像大小,如果pt为True或者model.triton为True,则bs=1,否则bs为数据集的长度。3为通道数,*imgsz为图像大小,即(1,3,224,224)
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile()) # seen为已推理的图片数量,windows为空列表,dt为时间统计对象
    for path, im, im0s, vid_cap, s in dataset: #遍历数据集,path为图片路径,im为图片,im0s为原始图片,vid_cap为视频读取对象,s为视频帧率
        with dt[0]:                            #开始计时,读取图片时间
            im = torch.Tensor(im).to(model.device)   #将图片转换为tensor,并放到模型的设备上,pytorch模型的输入必须是tensor
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32,如果模型使用fp16推理,则将图片转换为fp16,否则转换为fp32
            if len(im.shape) == 3:              #如果图片维度为3,则添加batch维度
                im = im[None]  # expand for batch dim,在前面添加batch维度,即将图片的维度从3维转换为4维,即(3,640,640)转换为(1,3,224,224),pytorch模型的输入必须是4维的
        # Inference,推理
        with dt[1]:
            results = model(im)   #推理,results为推理结果

        # Post-process
        with dt[2]:
            pred = F.softmax(results, dim=1)  # probabilities,对推理结果进行softmax,得到每个类别的概率


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

            p = Path(p)  # to Path                             #将路径转换为Path对象
            save_path = str(save_dir / p.name)  # im.jpg,保存图片的路径,save_dir为保存图片的文件夹,p.name为图片名称
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt,保存预测框的路径,save_dir为保存图片的文件夹,p.stem为图片名称,dataset.mode为数据集的模式,如果是image,则为图片,否则为视频

            s += '%gx%g ' % im.shape[2:]  # print string,打印输出,im.shape[2:]为图片的大小,即(1,3,224,224)中的(224,224)
            annotator = Annotator(im0, example=str(names), pil=True) # Annotator()对象,用于在图片上绘制分类结果,im0为原始图片,example为类别名称,pil为是否使用PIL绘制

            # Print results
            top5i = prob.argsort(0, descending=True)[:5].tolist()  # top 5 indices,对概率进行排序,取前5个,top5i为前5个类别的索引
            s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "   #打印输出,names[j]为类别名称,prob[j]为概率
            # Write results
            text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)     #将类别名称和概率拼接成字符串,用于保存到txt文件中
            if save_img or view_img:  # Add bbox to image,如果保存图片或者显示图片,则在图片上绘制预测框
                annotator.text((32, 32), text, txt_color=(255, 255, 255)) #将预测结果绘制在图片上
            if save_txt:  # Write to file,如果保存txt文件,则将预测结果保存到txt文件中
                with open(f'{txt_path}.txt', 'a') as f:     #以追加的方式打开txt文件
                    f.write(text + '\n')                    #将预测结果写入txt文件中

            # Stream results,如果是摄像头,则显示图片
            im0 = annotator.result()     #获取绘制预测结果和标签的图片
            if view_img:                                                    #如果view_img为True,则展示图片
                if platform.system() == 'Linux' and p not in windows:          #如果系统为Linux,且p不在windows中
                    windows.append(p)                                           #将p添加到windows中
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux),允许窗口调整大小,WINDOW_NORMAL表示用户可以调整窗口大小,WINDOW_KEEPRATIO表示窗口大小不变
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])             #调整窗口大小,使其与图片大小一致
                cv2.imshow(str(p), im0)                                               #显示图片
                cv2.waitKey(1)  # 1 millisecond                                        #等待1毫秒

            # Save results (image with detections)
            if save_img:                                                                   #如果save_img为True,则保存图片
                if dataset.mode == 'image':                                                 #如果数据集模式为image
                    cv2.imwrite(save_path, im0)                                            #保存图片
                else:  # 'video' or 'stream',如果数据集模式为video或stream
                    if vid_path[i] != save_path:  # new video,如果vid_path[i]不等于save_path
                        vid_path[i] = save_path    #将save_path赋值给vid_path[i]
                        if isinstance(vid_writer[i], cv2.VideoWriter):                #如果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}{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:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''     #如果save_txt为True,则打印保存的标签数量
        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():
    """
    weights: 模型路径
    source: 分类源路径,0为摄像头
    data:数据集路径,分类时不需要
    imgsz: 图片大小,通常与训练时的图片大小一致,以便保持模型的一致性
    device: 设备,cpu或者gpu
    view-img: 是否显示结果图片
    save-txt: 是否保存结果文本,结果为图片的概率和类别
    nasave: 是否不保存结果图片
    augment:是否进行推理时数据增强,分类时不需要
    visualize: 是否可视化,分类时不需要
    update: 是否更新模型
    project: 项目路径
    name: 保存结果的文件夹名称
    exist-ok: 是否覆盖已存在的文件夹
    half: 是否使用半精度推理
    dnn: 是否使用dnn加速
    vid-stride: 视频帧间隔
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'runs/train-cls/exp12/weights/best.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(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=[224], help='inference size h,w')
    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', default=True,action='store_true', help='save results to *.txt')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    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/predict-cls', 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('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    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):   # 主函数
    check_requirements(exclude=('tensorboard', 'thop'))   # check_requirements()函数检查是否安装了必要的库,exclude参数用于排除不需要的库
    run(**vars(opt)) # run()函数用于执行推理任务,vars()函数用于将对象转换为字典


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

  • 21
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
根据引用中提到的错误信息,当运行yolov8predict.py时可能会出现TypeError: meshgrid() got an unexpected keyword argument ‘indexing‘的错误。解决这个问题的方法是: - 检查代码中是否有使用了错误的参数,如indexing。 - 确保你使用的是正确版本的YOLOv5模型和相应的依赖库。 - 如果问题仍然存在,可以尝试重新安装YOLOv5模型或者更新相应的依赖库来解决这个问题。 引用提供了有关predict.py的一些信息。它是YOLOv5-v7.0中用于分类的推理代码。它由run()、parse_opt()和main()三个函数构成。 引用中提到了加载模型的过程。首先,选择设备并加载模型。然后获取模型的stride、names和pt。最后,检查图像大小是否符合要求。 综上所述,如果yolov8predict.py报错,你可以按照上述步骤检查代码是否有错误的参数,确保使用正确的YOLOv5模型和相应的依赖库,尝试重新安装或更新依赖库。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [yolov5 7.0运行segment/predict.py时出现TypeError: meshgrid() got an unexpected keyword argument ...](https://blog.csdn.net/python_plus/article/details/128063147)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [史上详细YOLOv5predict.py逐句讲解](https://blog.csdn.net/qq_51511878/article/details/130183294)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值