yolov5源码详解(一)

详解yolov5源码之detect.py

27~46行,导入库和自定义模块

import argparse
import os
import sys
from pathlib import Path

import torch
import torch.backends.cudnn as cudnn

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, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           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

代码主体

def run(
        weights=ROOT / 'yolov5s.pt',  # model.pt path(s) 事先训练完成的权重文件
        # source=ROOT / 'data/images',  # file/dir/URL/glob, 0 for webcam
        source=ROOT / 'data/videos',  # file/dir/URL/glob, 0 for webcam 预测时的输入数据,可以是文件/路径/URL/glob, 输入是0的话调用摄像头作为输入
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path 数据集文件
        imgsz=(640, 640),  # inference size (height, width) 预测时的放缩后图片大小(因为YOLO算法需要预先放缩图片), 两个值分别是height, widt
        conf_thres=0.25,  # confidence threshold 置信度,高于此值的bounding_box才会被保留
        iou_thres=0.45,  # NMS IOU threshold IOU阈值,高于此值的bounding_box才会被保留
        max_det=1000,  # maximum detections per image一张图最大检测目标个数
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu 所使用的GPU编号,如果使用CPU就写cpu
        view_img=False,  # show results 是否在推理时预览图片
        save_txt=False,  # save results to *.txt 是否将结果保存在txt文件中
        save_conf=False,  # save confidences in --save-txt labels 是否将结果中的置信度保存在txt文件中
        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 如为True,则为class-agnostic. 否则为class-specific
        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 True: 推理结果覆盖之前的结果 False: 推理结果新建文件夹保存,文件夹名递增
        line_thickness=3,  # bounding box thickness (pixels)  绘制Bounding_box的线宽度
        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
):
    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)#判断是不是调用摄像头,txt文件,网络流地址且不是文件
    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增量保存runs/detect/exp文件
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir根据save_txt判断exp文件中是否增加labels

    # Load model
    device = select_device(device)#判断加载CPU还是GPU
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)#选择模型框架,例如pytorch,加载模型
    stride, names, pt = model.stride, model.names, model.pt#读取模型能检测的步长,类别名,是否为pytorch
    imgsz = check_img_size(imgsz, s=stride)  # check image size imgsz是640*640,满足32倍数

    # Dataloader
    if webcam:
        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
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz))  # warmup
    seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
    for path, im, im0s, vid_cap, s in dataset:#im是resize后图片,im0s是原图
        t1 = time_sync()
        im = torch.from_numpy(im).to(device)#转成tensor给GPU torch.Size[3,640,480]
        im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
        im /= 255  # 0 - 255 to 0.0 - 1.0 归一化
        if len(im.shape) == 3:
            im = im[None]  # expand for batch dim 扩增 torch.Size[1,3,640,480]
        t2 = time_sync()
        dt[0] += t2 - t1

        # Inference
        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] visualize表示是否保持推断中间特征图,augment表示是否数据增强
        t3 = time_sync()
        dt[1] += t3 - t2

        # NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)#torch.Size[1,5,6]
        dt[2] += time_sync() - t3

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

        # Process predictions
        for i, det in enumerate(pred):  # per image torch.Size[5,6]
            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 图片尺寸640*480
            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()#将预测图片640*480中的框映射回原图

                # 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 是否结果保存到txt
                        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:#是否展示图片
                if 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:#是否保存图片
                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
    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:#如果保存了图片或txt
        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)

其余parse_opt()代码中各种参数的含义与之前一致

你可能感兴趣的:(深度学习,计算机视觉,目标检测)