YOLO系列 — YOLOV7算法(二):YOLO V7算法detect.py代码解析

YOLO系列 — YOLOV7算法(二):YOLO V7算法detect.py代码解析

    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default='yolov7.pt', help='model.pt path(s)') #测试所使用的权重文件
    parser.add_argument('--source', type=str, default='inference/images', help='source')  # 测试的图片/图片文件夹/摄像头接口
    parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)') #测试图片大小
    parser.add_argument('--conf-thres', type=float, default=0.25, help='object confidence threshold') #测试过程中所需的阈值
    parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS') #测试过程中nms所需的阈值
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') #使用cpu还是gpu进行测试
    parser.add_argument('--view-img', action='store_true', help='display results') #是否将测试结果展示
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt') #是否保存测试之后的txt标签文件
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels') #在txt中是否保存测试置信度结果大小
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos') #是否保存测试图片
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 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('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default='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('--no-trace', action='store_true', help='don`t trace model') 
    opt = parser.parse_args()

    source, weights, view_img, save_txt, imgsz, trace = opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size, not opt.no_trace
    save_img = not opt.nosave and not source.endswith('.txt')  # save inference images
    webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
        ('rtsp://', 'rtmp://', 'http://', 'https://'))

获取相应的参数和测试流(判断测试是本地图片还是网络图片流)


    # Directories
    save_dir = Path(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

创建保存训练结果的文件夹


    # Initialize
    set_logging()
    device = select_device(opt.device)
    half = device.type != 'cpu'  # half precision only supported on CUDA

选择使用cpu还是cuda进行测试


    # Load model
    model = attempt_load(weights, map_location=device)  # load FP32 model
    stride = int(model.stride.max())  # model stride
    imgsz = check_img_size(imgsz, s=stride)  # check img_size
    if trace:
        model = TracedModel(model, device, opt.img_size)

    if half:
        model.half()  # to FP16

加载权重文件(如果没有上传自己的权重文件,会自动下载预训练好的模型权重文件),同时检测图片大小,如果测试图片大小不是32的倍数,那么就自动调整为32的倍数(是调用make_divisible函数)。同时判断是否进行libtorch转换和参数half操作。
这里,我们进入attempt_load函数,稍微讲下pytorch调用模型。
首先,要知道pytorch一般加载模型的两种方式:

  • 第一种是保存模型的state_dict(),只是保存模型的参数。那么加载时需要先创建一个模型的实例model,之后通过torch.load()将保存的模型参数加载进来,得到dict,再通过model.load_state_dict(dict)将模型的参数更新。
  • 另一种是将整个模型保存下来,之后加载的时候只需要通过torch.load()将模型加载,即可返回一个加载好的模型。
  • ckpt = torch.load(w, map_location=map_location)
    

    同时,这里加载模型的时候后接了一个参数map_location,这个参数的作用是用于重定向,即比如训练的时候是使用GPU进行训练,然后测试的时候换cpu进行测试,那么后面就接“cpu”作为参数传入。


        # Second-stage classifier
        classify = False
        if classify:
            modelc = load_classifier(name='resnet101', n=2)  # initialize
            modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']).to(device).eval()
    

    用户是否选择用一个分类网络来对定位框里面的内容进行分类。一些用户喜欢使用第二阶段过滤第一阶段检测以减少 FP 的选项。如果你有一个在相同类上训练的分类器,你可以在那里指定它。这里可以使用任何分类器(EfficientNet、Resnet 等),唯一的要求是分类和检测模型在相同的类上训练。其实,一般都不会进这个分支的~


        # Set Dataloader
        vid_path, vid_writer = None, None
        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)
        else:
            dataset = LoadImages(source, img_size=imgsz, stride=stride)
    

    这里是判断测试流输入是什么格式文件,然后返回一个可迭代对象,便于后面对其进行遍历预测。我们进LoadImages函数里面看看如何进行数据加载的(这里传入三个参数,分别是待预测图片路径,网络支持的预测图片大小,网络的最大步长)。进入函数之后,会发现函数定义了两个内置函数__iter____next__,一般来说,只要在类中定义了这两个函数就表示该类返回的是可迭代对象,其中__iter__的作用是用来计数用的,而__next__是用于后续循环获取数据的。

        def __next__(self):
            if self.count == self.nf:
                raise StopIteration
            path = self.files[self.count]
    

    首先,self.count表示当前预测图片在总预测集中的索引号,self.nf表示的是总预测集的数量,先判断当前预测图片是不是最后一张,如果不是的话,就会在所有的预测列表中获取到相对应索引号的预测图片。

            if self.video_flag[self.count]:
                # Read video
                self.mode = 'video'
                ret_val, img0 = self.cap.read()
                if not ret_val:
                    self.count += 1
                    self.cap.release()
                    if self.count == self.nf:  # last video
                        raise StopIteration
                    else:
                        path = self.files[self.count]
                        self.new_video(path)
                        ret_val, img0 = self.cap.read()
    
                self.frame += 1
                print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='')
    
            else:
                # Read image
                self.count += 1
                img0 = cv2.imread(path)  # BGR
                assert img0 is not None, 'Image Not Found ' + path
                #print(f'image {self.count}/{self.nf} {path}: ', end='')
    

    然后判断当前预测的是视频还是图片,这里我们直接进入到图片的预测模块中进行图片读取。

    img = letterbox(img0, self.img_size, stride=self.stride)[0]
    

    上述这行代码是进行矩阵训练,其实就是将原始图片进行一个有规则的缩放。我们直接进去看看~

    def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
        # Resize and pad image while meeting stride-multiple constraints
        shape = img.shape[:2]  # current shape [height, width] 首先获取原始图片的长宽大小
        if isinstance(new_shape, int):
            new_shape = (new_shape, new_shape) #判断new_shape的类型是不是int型,这里我们传入的是元祖,所以不用管
    
        # Scale ratio (new / old)
        r = min(new_shape[0] / shape[0], new_shape[1] / shape[1]) #这句话其实就是在寻找原始图片长宽中最长边相对缩放尺寸的比例
        if not scaleup:  # only scale down, do not scale up (for better test mAP)
            r = min(r, 1.0)
    
        # Compute padding
        ratio = r, r  # width, height ratios 赋值
        new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r)) #基于上述获取的缩放比例,计算出经过resize之后的尺寸大小
        dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding 获取针对原始图片需要扩充的大小
        if auto:  # minimum rectangle 默认是True
            dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding 取模操作
        elif scaleFill:  # stretch
            dw, dh = 0.0, 0.0
            new_unpad = (new_shape[1], new_shape[0])
            ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios
    
        dw /= 2  # divide padding into 2 sides 除以2即最终每边填充的像素
        dh /= 2
    
        if shape[::-1] != new_unpad:  # resize
            img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR) #进行resize操作
        top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
        left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
        img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # 添加灰边
        return img, ratio, (dw, dh)
    

    总结下,其实yolov7这个操作跟yolov5一样的,虽然测试输入图片的shape设置为(640,640),但是实际上并不会是刚好resize到这个尺度的。举个栗子,比如说进来一个测试图片长宽是(480,1280),最终会resize到(480,640),并不会强制到(640,640),这样会加快推理速度。

            img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
            img = np.ascontiguousarray(img)
    
            return path, img, img0, self.cap
    

    最后BGR to RGB,np.ascontiguousarray这个函数的作用是将一个内存不连续存储的数组转换为内存连续存储的数组,使得运行速度更快。最后返回path是一个包含所有待预测图片的列表,img是一个包含所有原始图片的列表,img0是一个包含经过resize之后图片的列表,最后self.cap表示的是待预测对象是视频还是图片。


        # Get names and colors
        names = model.module.names if hasattr(model, 'module') else model.names
        colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]
    

    对待预测所有类别进行颜色分配


        # Run inference
        if device.type != 'cpu':
            model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # run once
        t0 = time.time()
        for path, img, im0s, vid_cap in dataset:
            img = torch.from_numpy(img).to(device)
            img = img.half() if half else img.float()  # uint8 to fp16/32
            img /= 255.0  # 0 - 255 to 0.0 - 1.0
            if img.ndimension() == 3:
                img = img.unsqueeze(0)
    

    对上述生成的数据迭代对象进行遍历,对图片进行归一化操作。同时判断一下如果图片的channels维度是等于3,那么就在图片的第一维度添加一个batch_size的维度,变成四维。这里,img.ndimension()的作用是返回tensor对象的维度,img.unsqueeze()函数是在指定维度上添加一个维度。


            # Inference
            t1 = time_synchronized()
            pred = model(img, augment=opt.augment)[0]
    

    将测试图片喂入网络中,得到预测结果。这里,由模型推理所得到的预测结果的shape是(1,16380,6),可见预测出来了很多候选框,需要后续通过nms进行筛选。当然了!这里16380是基于该图出的预测框,每张图出的结果都不一样。


            # Apply NMS
            pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=opt.classes, agnostic=opt.agnostic_nms)
            t2 = time_synchronized()
    
    

    对预测结果进行nms操作,去除多余的框。通过nms操作,最终pred变成了(25,6),即最后只剩下25个预选框。同时,输出每个预选框的x1y1x2y2,置信度,类别数共六个值。


            # Process detections
            for i, det in enumerate(pred):  # detections per image
                if webcam:  # batch_size >= 1
                    p, s, im0, frame = path[i], '%g: ' % i, im0s[i].copy(), dataset.count
                else:
                    p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)
    
                p = Path(p)  # to Path
                save_path = str(save_dir / p.name)  # img.jpg
                txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # img.txt
                s += '%gx%g ' % img.shape[2:]  # print string
                gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
    

    针对每一张待预测图片,遍历输出结果,创建相对于的保存路径,gn表示的是经过resize之后的长宽,这里为(416,640,416,640),是为了后面xyxy2xywh操作用的。


    if len(det):
       # Rescale boxes from img_size to im0 size
       det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
    

    这里scale_coords函数的作用是将预测所得到的结果进行转换。因为我们是基于resize之后的图片进行预测的,所以最开始得到的预测结果不是最终原图所对应的,该函数就是把相对应的标签进行转换为原图尺寸上。通过该函数,会将上述得到的(300,6)的tensor中每个预选框前四个位置信息值转换为原图尺寸。我们进入scale_coords函数来看下~

    def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
    	#先说下每个参数的含义:
    	#1.img1_shape:经过resize之后的长宽大小
    	#2.coords:基于resize之后的图片经过预测所得到的所有预测框的位置信息x1y1x2y2(左上角坐标和右下角坐标)
    	#3.img0_shape:原图的shape
        # Rescale coords (xyxy) from img1_shape to img0_shape
        if ratio_pad is None:  # calculate from img0_shape
            gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new 计算原始图片与resize之后的图片的最小比例
            pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding #进行填充
        else:
            gain = ratio_pad[0][0]
            pad = ratio_pad[1]
    
        coords[:, [0, 2]] -= pad[0]  # x padding 长填充
        coords[:, [1, 3]] -= pad[1]  # y padding 宽填充
        coords[:, :4] /= gain #进行resize
        clip_coords(coords, img0_shape) #进行截断操作
        return coords
    

    clip_coords函数中采用了clamp_操作,这个的作用是进行截断操作,但是pytorch中还有一个clamp,带下划线的表示是直接对原始tensor进行截断,不必重新创建新的tensor进行截断。


                    # 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
    

    这里,det[:, -1]表示的是该待预测图片所得到的300个预测框的类别,unique()的作用是查看这300个框一共会有哪些类别,然后统计属于每个类别的预测框数量。


                    # 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 opt.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 view_img:  # Add bbox to image
                            label = f'{names[int(cls)]} {conf:.2f}'
                            plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3
                            
    

    reversed函数是python内置的一个函数,作用是将一个可迭代的对象进行数据反转。这里其实就是将300个预测框的反向遍历,即最先遍历300个预测框最后一个。然后判断是否进行txt保存操作和保存图片或者可视化预测结果图片操作。在保存txt模块里面,首先用view(1, 4)函数将tensor的shape调整为(1,4),该函数的作用其实跟resize一样的,然后直接除以gn,上述gn的形式是(长,宽,长,宽),这里就起到作用了。然后喂入xyxy2xywh函数转换为xywh格式。


    以上就是yolo v7算法detect.py的主要内容了~中间要是有一些不对的地方,还请提出。栓Q…

    物联沃分享整理
    物联沃-IOTWORD物联网 » YOLO系列 — YOLOV7算法(二):YOLO V7算法detect.py代码解析

    发表评论