yolo v5代码解析笔记(detect部分)

安装配置
链接
detect.py代码块

# 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 csv
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 ultralytics.utils.plotting import Annotator, colors, save_one_box

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.torch_utils import select_device, smart_inference_mode


@smart_inference_mode()
def run(
        # 大致分为6个模块
        weights=ROOT / 'yolov5s.pt',  # model path or triton URL
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
        data=ROOT / 'data/road_parameter.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最多检测1000个目标
        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_csv=False,  # save results in CSV format
        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)    #检测框的线条粗细为3个像素大小
        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
):
    source = str(source)  # 对于传入的source参数进行类型转化
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)  # 判断source参数的后缀也就是jpg是否在IMG_FORMATS和VID_FORMATS中,即判断传入文件是否为允许的
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))  #  判断给的source是否为网络流地址,先转化为小写,再判断开头
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)  #  判断给的source是否为数值,比如电脑摄像头的camera 0,1或者txt文本,url网络流并且不是图片文件
    screenshot = source.lower().startswith('screen')    # 判断是否为截图
    if is_url and is_file:
        source = check_file(source)  # 若是网络流地址,则下载对于的视频或图片文件

    # 新建一个保存结果的文件夹
    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # project参数见上面,increment_path是指增量_路径,比如runs/detect/exp  exp后面的数字依次增加
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # 检查save_txt参数,如果定义为true,则会在保存路径也就是exp文件夹下新建labels文件夹,保存txt结果

    # 加载模型的权重
    # Load model
    device = select_device(device)  # 选择加载模型的设备,比如GPU,CPU
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)  # 选择后端框架,比如pytorch,TorchScript等等,传入的参数依次为:yolov5的模型如s,x,m,加载模型的设备,,数据集配置文件
    stride, names, pt = model.stride, model.names, model.pt  # 读取模型中相关参数,如步长,标签名,模型框架是否为pytorch(32,定义的标签名,true)
    imgsz = check_img_size(imgsz, s=stride)  # 检查图片大小,首先Yolov5的神经网络要求输入图片必须为32的倍数,所以图片大小是640*640,32是指步长为32

    # 加载待预测的图片
    # Dataloader
    bs = 1  # batch_size,给模型传入图片时是一个一个传入
    if webcam:  # false根据上述定义判断,由于待预测图片不是网络地址,txt文本什么的,因此定义为false
        view_img = check_imshow(warn=True)
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
        bs = len(dataset)
    elif screenshot:    # 判断是否为截图,一般为否
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
    else:   # 加载图片文件
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
    vid_path, vid_writer = [None] * bs, [None] * bs

    # 推理过程,输入图片输出预测结果,同时画出检测框
    # Run inference
    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmup,热身,先给模型传一张空白图片
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())    # 存储一些结果信息,seen为预测图片总数 ,dt为总耗时
    for path, im, im0s, vid_cap, s in dataset:  # 依次遍历执行 路径,resize后的图片,原图,none,打印信息
        with dt[0]:
            im = torch.from_numpy(im).to(model.device)  # 转成pytorch支持的格式类型
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0   # 对于所有图片除以255进行归一化操作(像素点除以255)
            if len(im.shape) == 3:  # 判断输入图片尺寸,新增batch维度
                im = im[None]  # expand for batch dim

        # Inference预测
        with dt[1]:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)  # visualize为true则保存相关特征图,augment数据增强 torch.size([1, 18900, 85]) 18900:18900个检测框     85:4个坐标信息,1个置信度,80个类别

        # NMS 非极大值抑制
        with dt[2]:
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)     #1,5,6  6表示检测框的左上和右下两个点的X Y值,1个置信度,1个类别

        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        # Define the path for the CSV file
        csv_path = save_dir / 'predictions.csv'

        # Create or append to the CSV file
        def write_to_csv(image_name, prediction, confidence):
            data = {'Image Name': image_name, 'Prediction': prediction, 'Confidence': confidence}
            with open(csv_path, mode='a', newline='') as f:
                writer = csv.DictWriter(f, fieldnames=data.keys())
                if not csv_path.is_file():
                    writer.writeheader()
                writer.writerow(data)

        # 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_boxes(im.shape[2:], det[:, :4], im0.shape).round()   # 坐标映射,由于待检测图片大小和传入网络图片大小不同,因此在原图上画框需要进行坐标映射

                # Print results
                for c in det[:, 5].unique():
                    n = (det[:, 5] == 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):
                    c = int(cls)  # integer class
                    label = names[c] if hide_conf else f'{names[c]}'
                    confidence = float(conf)
                    confidence_str = f'{confidence:.2f}'

                    if save_csv:
                        write_to_csv(p.name, label, confidence_str)

                    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(f'{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:    # view_img为true则显示此图片为窗口
                if platform.system() == 'Linux' and p not in windows:
                    windows.append(p)
                    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)
            if save_img:    # save_img为true则保存此图片,一般来说,save_img和view_img总要有一个为true,不然既不显示也不保存,怎么知道结果呢
                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)
        # 至此,一张图片的相关检测处理已经完成,继续for循环,执行下一张
        # 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 计算时间,seen为总共多少张图片,dt为总耗时
    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[0])  # update model (to fix SourceChangeWarning)


def parse_opt():
    # 整个parse_opt()函数分为三个部分
    # 1.定义传入的参数(default表示默认值),由于使用传入参数时,需要终端,而且需要写入的参数太多,因此在默认值上修改
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='best.pt', help='model path or triton URL')
    parser.add_argument('--source', type=str, default='0.mp4', help='file/dir/URL/glob/screen/0(webcam)')
    parser.add_argument('--data', type=str, default='project_road/road_parameter.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='0', 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-csv', action='store_true', help='save results in CSV format')
    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')
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
    opt = parser.parse_args()
    # 2.对img-size进行修改判断,首先,待检测图像的大小不一,对于YOLOv5网络而言,传入的检测图像resize为640*640,为避免失真,因此需要对传入的图像提前进行修改大小
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    # 3.打印参数信息,opt变量存储相应参数
    print_args(vars(opt))
    return opt


def main(opt):
    # 检查requirements.txt文件中的包是否都安装成功
    check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
    # 后续的图片加载,结果保存等一系列操作
    run(**vars(opt))


if __name__ == '__main__':
    opt = parse_opt()  # 设置传入的参数,也就是调用 parse_opt() 函数
    main(opt)

总体作用解释
dete.py:yolov5的检测代码,运行此代码加载权重文件检测传入的图片或者视频
总体代码大致分为3个部分,main()函数和执行入口,保存参数配置的parse_opt()函数,画框保存等操作的run()函数
非极大值抑制:使用使用网络训练时候会存在多个预测框,然后通过设置置信度会减少预测框的数量;然后再计算预测框和真实框之间IOU,但是可能还是会存在多个交并比的框,此时在使用NMS来进行抑制,这样就会一定程度上减少预测框的个数。

parse_opt():
在开始调用main函数前,需要对parse_opt():函数进行相应的配置
此函数用于定义相关参数,如权重文件,待检测图片/视频,传入网络的图片大小等等,参数较多,不分别说明了。

下面代码对img-size进行修改判断,首先,待检测图像的大小不一,对于YOLOv5网络而言,传入的检测图像resize为640640(或者64032的倍数,此点需要进一步学习,待修改),为避免失真,因此需要对传入的图像提前进行修改大小

    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand

打印参数信息,opt变量存储相应参数

print_args(vars(opt))

开始执行
设置传入的参数,也就是调用 parse_opt() 函数,此函数已在上述介绍

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

main()
在安装yolov5时,会先运行一遍detect.py文件,下面的代码可以先检查相关的安装包,以求正确运行

def main(opt):
    # 检查requirements.txt文件中的包是否都安装成功
    check_requirements(ROOT / 'requirements.txt', exclude=('tensorboard', 'thop'))
    # 后续的图片加载,结果保存等一系列操作
    run(**vars(opt))

run()
整体来讲大致分为这几个模块:
1.相关参数配置(这里指的是传入的参数,部分参数已经定义了默认值)
2.检查传入的source(摄像头,图片,视频,网络地址,其他文件类型)
3.结果保存的路径设置(默认为创建,有心思可以修改)
4.加载模型权重
5.加载待预测图片
6.推理过程,同时画出检测框
7.打印输出信息

source文件类型判断

    source = str(source)  # 对于传入的source参数进行类型转化
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)  # 判断source参数的后缀也就是jpg是否在IMG_FORMATS和VID_FORMATS中,即判断传入文件是否为允许的
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))  #  判断给的source是否为网络流地址,先转化为小写,再判断开头
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)  #  判断给的source是否为数值,比如电脑摄像头的camera 0,1或者txt文本,url网络流并且不是图片文件
    screenshot = source.lower().startswith('screen')    # 判断是否为截图
    if is_url and is_file:
        source = check_file(source)  # 若是网络流地址,则下载对于的视频或图片文件

保存路径

    # 新建一个保存结果的文件夹
    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # project参数见上面,increment_path是指增量_路径,比如runs/detect/exp  exp后面的数字依次增加
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # 检查save_txt参数,如果定义为true,则会在保存路径也就是exp文件夹下新建labels文件夹,保存txt结果

模型加载

    # 加载模型的权重
    # Load model
    device = select_device(device)  # 选择加载模型的设备,比如GPU,CPU
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)  # 选择后端框架,比如pytorch,TorchScript等等,传入的参数依次为:yolov5的模型如s,x,m,加载模型的设备,,数据集配置文件
    stride, names, pt = model.stride, model.names, model.pt  # 读取模型中相关参数,如步长,标签名,模型框架是否为pytorch(32,定义的标签名,true)
    imgsz = check_img_size(imgsz, s=stride)  # 检查图片大小,首先Yolov5的神经网络要求输入图片必须为32的倍数,所以图片大小是640*640,32是指步长为32

待预测图片加载

    # 加载待预测的图片
    # Dataloader
    bs = 1  # batch_size,给模型传入图片时是一个一个传入
    if webcam:  # false根据上述定义判断,由于待预测图片不是网络地址,txt文本什么的,因此定义为false
        view_img = check_imshow(warn=True)
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
        bs = len(dataset)
    elif screenshot:    # 判断是否为截图,一般为否
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
    else:   # 加载图片文件
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
    vid_path, vid_writer = [None] * bs, [None] * bs

预测,以及非极大值抑制


        # Inference预测
        with dt[1]:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)  # visualize为true则保存相关特征图,augment数据增强 torch.size([1, 18900, 85]) 18900:18900个检测框     85:4个坐标信息,1个置信度,80个类别

        # NMS 非极大值抑制
        with dt[2]:
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)     #1,5,6  6表示检测框的左上和右下两个点的X Y值,1个置信度,1个类别

画框以及保存结果(内部定义了一些小功能,比如是否显示置信度,标签名等等)

        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_boxes(im.shape[2:], det[:, :4], im0.shape).round()   # 坐标映射,由于待检测图片大小和传入网络图片大小不同,因此在原图上画框需要进行坐标映射

                # Print results
                for c in det[:, 5].unique():
                    n = (det[:, 5] == 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):
                    c = int(cls)  # integer class
                    label = names[c] if hide_conf else f'{names[c]}'
                    confidence = float(conf)
                    confidence_str = f'{confidence:.2f}'

                    if save_csv:
                        write_to_csv(p.name, label, confidence_str)

                    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(f'{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:    # view_img为true则显示此图片为窗口
                if platform.system() == 'Linux' and p not in windows:
                    windows.append(p)
                    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)
            if save_img:    # save_img为true则保存此图片,一般来说,save_img和view_img总要有一个为true,不然既不显示也不保存,怎么知道结果呢
                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 results
    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image 计算时间,seen为总共多少张图片,dt为总耗时
    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[0])  # update model (to fix SourceChangeWarning)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无奈ieq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值