yolov5-detect.py-注释

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
        ):
    source = str(source)
    #endwith判断字符串是否以指定字符或子字符串结尾
    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://'))
    #isnumeric检测字符串是否只由数字组成,如果字符串中只包括数字,就返回Ture,否则返回False
    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
    #创建结果保存的文件夹
    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
    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
    #开启半精度。直接可以加快运行速度、减少GPU占用,并且只有不明显的accuracy损失。
    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
    if webcam:#需要下载
        # Check if environment supports image displays
        view_img = check_imshow()
        #设置这个 flag 可以让内置的 cuDNN 的 auto-tuner 自动寻找最适合当前配置的高效算法,来达到优化运行效率的问题。
        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
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    #模型预热
    model.warmup(imgsz=(1 if pt else bs, 3, *imgsz), half=half)  # warmup
    dt, seen = [0.0, 0.0, 0.0], 0
    for path, im, im0s, vid_cap, s in dataset:
        t1 = time_sync()#时间同步
        im = torch.from_numpy(im).to(device)
        #转换为haf半字
        im = im.half() if half 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
        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)
        t3 = time_sync()
        dt[1] += t3 - t2

        # NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        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
            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
    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)


def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default="/home/litinglong/~Pycode/yolov5-master/runs/train/exp/weights/best.pt", help='model path(s)')
    parser.add_argument('--source', type=str, default="/home/litinglong/~Pycode/yolov5-master/data/images/", 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')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(FILE.stem, opt)
    return opt


def main(opt):
    #检查虚拟环境符合requirement
    check_requirements(exclude=('tensorboard', 'thop'))
    #实例化参数
    run(**vars(opt))


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

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将yolov5 detect.py封装可以使用Python的模块化编程思想,将detect.py中的函数封装成一个模块,方便其他程序调用。具体步骤如下: 1. 创建一个新的Python文件,例如yolov5_detect.py。 2. 将detect.py中的函数封装成一个模块,可以使用Python的import语句将detect.py中的函数导入到yolov5_detect.py中。 3. 在yolov5_detect.py中定义一个名为detect的函数,该函数调用detect.py中的函数进行目标检测。 4. 将yolov5_detect.py文件打包成一个Python模块,可以使用Python的setuptools库进行打包。 5. 将打包好的模块安装到Python环境中,可以使用Python的pip命令进行安装。 6. 在其他程序中使用import语句导入yolov5_detect模块,并调用detect函数进行目标检测。 通过封装yolov5 detect.py,可以方便地将目标检测功能集成到其他程序中,提高程序的可复用性和可维护性。 ### 回答2: 将yolov5 detect.py封装,可以使得该模型更加易于使用和适用,方便用户快速完成目标检测任务。下面我将从模块化设计、封装函数、调用方式等方面进行阐述。 1. 模块化设计 在设计封装后的yolov5 detect.py之前,我们需要将原模型代码进行模块化设计,将大的功能模块拆分为若干个小模块,这样可以便于分工协作、代码管理。可以将原模型的代码拆分为以下模块:模型加载、图像处理、目标检测、结果输出。通过模块化的设计,可以使得代码更加清晰明了,易于理解和维护。 2. 封装函数 将各功能模块封装成函数,通过函数的方式调用,可以使得代码更加简洁明了。在封装函数的时候,需要考虑各个函数之间的依赖关系,如何将参数传递给下一个函数等。可以将每个功能模块封装为一个函数,例如加载模型的函数load_model()、图像处理的函数process_image()、目标检测的函数detect()、结果输出函数output_result()。 3. 调用方式 最后,需要定义一个主函数main()来调用各个功能模块。主函数主要包含以下几个步骤: 1)加载模型,通过调用load_model()函数加载yolov5模型,获取检测所需参数。 2)处理图像,通过调用process_image()函数,将待检测的图像进行处理,包括缩放、裁剪等操作。 3)目标检测,调用detect()函数,对图像进行目标检测,并得到检测结果。 4)输出结果,调用output_result()函数,将检测结果输出,可以输出到控制台或者保存到文件中。 通过以上步骤,即可完成封装后的yolov5 detect.py的调用过程,使得该模型变得更加易用和适用。 ### 回答3: YOLOv5是一种先进的目标检测算法,其detect.py是该算法的核心代码。为了方便使用和扩展,有时候需要将detect.py封装成一个更易于使用的库或者类供其他程序调用。下面介绍如何进行封装: 1. 将detect.py中的函数或类进行逻辑分组。例如,可以将相关的函数放在一个文件夹内,或者定义一个大的类,其中包含各个小的功能函数。 2. 对于代码中重复的部分,应该封装成可重用的函数或类。这些函数或类可供其他模块调用。 3. 对于板块与板块之间重复的代码,可以封装成单独的文件,避免重复编写代码。 4. 采用适合场景的命名和注释。 5.剔除不必要的代码,代码逻辑尽可能清晰。 随着代码的封装,在使用中不仅提高了代码的易读性和可扩展性,还方便代码的维护和更新。例如,将封装的代码发布到使用的用户,他们可以方便的调用进行目标检测。封装的函数或类可以运用到任何需要目标检测的场景中,减少了重复劳动,提高了工作效率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值