Ejemplo n.º 1
0
 def __init__(self, phase, size, Basenet, Neck, Head, cfg):
     super(SSD, self).__init__()
     self.phase = phase
     self.cfg = cfg
     self.priorbox = PriorBox(self.cfg)
     self.priors = self.priorbox.forward()
     self.size = size
     # SSD network
     self.basenet = Basenet
     self.neck = Neck
     self.head = Head
     self.num_classes = cfg['num_classes']
     self.softmax = nn.Softmax(dim=-1)
     self.detect = Detect(self.num_classes, 0, 200, 0.01, 0.45,
                          variance=cfg['variance'], nms_kind=cfg['nms_kind'], beta1=cfg['beta1'])
Ejemplo n.º 2
0
    def __init__(self):
        super().__init__()

        self.backbone = darknet53
        # Compute mask_dim here and add it back to the config. Make sure Yolact's constructor is called early!
        self.num_grids = 0
        self.proto_src = 0

        in_channels = 256
        in_channels += self.num_grids

        mask_proto_net = [(256, 3, {
            'padding': 1
        }), (256, 3, {
            'padding': 1
        }), (256, 3, {
            'padding': 1
        }), (None, -2, {}), (256, 3, {
            'padding': 1
        }), (32, 1, {})]
        # The include_last_relu=false here is because we might want to change it to another function
        self.proto_net, mask_dim = make_net(in_channels,
                                            mask_proto_net,
                                            include_last_relu=False)

        self.selected_layers = [2, 3, 4]
        src_channels = self.backbone.channels

        # Some hacky rewiring to accomodate the FPN
        self.fpn = FPN([src_channels[i] for i in self.selected_layers])

        self.selected_layers = list(range(len(self.selected_layers) + 2))
        src_channels = [256] * len(self.selected_layers)

        self.prediction_layers = nn.ModuleList()

        pred_aspect_ratios = [[[1, 1 / 2, 2]]] * 5
        pred_scales = [[24], [48], [96], [192], [384]]
        for idx, layer_idx in enumerate(self.selected_layers):
            # If we're sharing prediction module weights, have every module's parent be the first one
            parent = None
            if idx > 0: parent = self.prediction_layers[0]

            pred = PredictionModule(src_channels[layer_idx],
                                    src_channels[layer_idx],
                                    aspect_ratios=pred_aspect_ratios[idx],
                                    scales=pred_scales[idx],
                                    parent=parent)
            self.prediction_layers.append(pred)

        self.semantic_seg_conv = nn.Conv2d(src_channels[0], 80, kernel_size=1)
        self.detect = Detect(81,
                             bkg_label=0,
                             top_k=200,
                             conf_thresh=0.05,
                             nms_thresh=0.5)
Ejemplo n.º 3
0
Archivo: ssd.py Proyecto: zhangts20/SSD
    def __init__(self, phase, size, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase  # 'train'或'test'
        self.size = size  # 输入尺寸=300
        self.num_classes = num_classes  # 类别数
        self.cfg = VOC  # 配置信息
        self.priorbox = PriorBox(self.cfg)  # 产生先验框
        with torch.no_grad():  # 不使用梯度
            self.priors = self.priorbox.forward()
        self.vgg = nn.ModuleList(base)  # 根据'base'建立nn.ModuleList对象
        self.L2Norm = L2Norm(512, 20)  # conv4_3后使用L2正则化
        self.extras = nn.ModuleList(extras)  # VGG-16后额外添加的四层

        self.loc = nn.ModuleList(head[0])  # 位置预测
        self.conf = nn.ModuleList(head[1])  # 置信度预测

        if phase == 'test':  # 测试阶段需要不同处理
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect(num_classes, 200, 0.01, 0.45)
Ejemplo n.º 4
0
class SSD(nn.Module):
    """Single Shot Multibox Architecture
    The network is composed of a base VGG network followed by the
    added multibox conv layers.  Each multibox layer branches into
        1) conv2d for class conf scores
        2) conv2d for localization predictions
        3) associated priorbox layer to produce default bounding
           boxes specific to the layer's feature map size.
    See: https://arxiv.org/pdf/1512.02325.pdf for more details.

    Args:
        phase: (string) Can be "test" or "train"
        size: input image size
        base: VGG16 layers for input, size of either 300 or 500
        extras: extra layers that feed to multibox loc and conf layers
        head: "multibox head" consists of loc and conf conv layers
    """

    def __init__(self, phase, size, Basenet, Neck, Head, cfg):
        super(SSD, self).__init__()
        self.phase = phase
        self.cfg = cfg
        self.priorbox = PriorBox(self.cfg)
        self.priors = self.priorbox.forward()
        self.size = size
        # SSD network
        self.basenet = Basenet
        self.neck = Neck
        self.head = Head
        self.num_classes = cfg['num_classes']
        self.softmax = nn.Softmax(dim=-1)
        self.detect = Detect(self.num_classes, 0, 200, 0.01, 0.45,
                             variance=cfg['variance'], nms_kind=cfg['nms_kind'], beta1=cfg['beta1'])

    def forward(self, x, phase):
        """Applies network layers and ops on input image(s) x.

        Args:
            x: input image or batch of images. Shape: [batch,3,300,300].

        Return:
            Depending on phase:
            test:
                Variable(tensor) of output class label predictions,
                confidence score, and corresponding location predictions for
                each object detected. Shape: [batch,topk,7]

            train:
                list of concat outputs from:
                    1: confidence layers, Shape: [batch*num_priors,num_classes]
                    2: localization layers, Shape: [batch,num_priors*4]
                    3: priorbox layers, Shape: [2,num_priors*4]
        """

        x = self.basenet(x)
        if self.neck is not None:
            x = self.neck(x)

        conf, loc = self.head(x)

        loc = torch.cat([o.view(o.size(0), -1) for o in loc], 1)
        conf = torch.cat([o.view(o.size(0), -1) for o in conf], 1)
        if phase == "test":
            output = self.detect.trans(
                loc.view(loc.size(0), -1, 4),                   # loc preds
                self.softmax(conf.view(conf.size(0), -1,
                                       self.num_classes)),                # conf preds
                #self.priors.type(type(x.data))                  # default boxes
                self.priors
            )
        else:
            output = (
                loc.view(loc.size(0), -1, 4),
                conf.view(conf.size(0), -1, self.num_classes),
                self.priors
            )
        return output

    def load_weights(self, base_file):
        other, ext = os.path.splitext(base_file)
        if ext == '.pkl' or '.pth':
            print('Loading weights into state dict...')
            self.load_state_dict(torch.load(base_file,
                                            map_location=lambda storage, loc: storage))
            print('Finished!')
        else:
            print('Sorry only .pth and .pkl files supported.')
Ejemplo n.º 5
0
                print('Epoch {}, iter {}, lr {:.6f}, loss {:.2f}, time {:.2f}s, eta {:.2f}h'.format(
                    epoch,
                    iteration,
                    optimizer.param_groups[0]['lr'],
                    loss.item(),
                    load_time,
                    load_time * (max_iter - iteration) / 3600,
                    ))
                timer.clear()
        save_weights(model)
    
    print('Start Evaluation...')
    thresh=0.005
    max_per_image=300
    model.eval()
    detector = Detect(num_classes)
    transform = BaseTransform(args.size)
    num_images = len(testset)
    all_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)]
    rgbs = dict()
    os.makedirs("draw/", exist_ok=True)
    os.makedirs("draw/{}/".format(args.dataset), exist_ok=True)
    _t = {'im_detect': Timer(), 'im_nms': Timer()}
    for i in range(num_images):
        img = testset.pull_image(i)
        scale = torch.Tensor([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
        with torch.no_grad():
            x = transform(img).unsqueeze(0)
            (x, scale) = (x.cuda(), scale.cuda())

            _t['im_detect'].tic()
Ejemplo n.º 6
0
def eval_model(
    model,
    num_classes,
    testset,
    priors,
    thresh=0.005,
    max_per_image=300,
):

    # Testing after training

    print('Start Evaluation...')
    model.eval()
    detector = Detect(num_classes)
    transform = BaseTransform(args.size, (104, 117, 123), (2, 0, 1))
    num_images = len(testset)
    all_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)]
    rgbs = dict()
    _t = {'im_detect': Timer(), 'im_nms': Timer()}
    for i in range(num_images):
        img = testset.pull_image(i)
        scale = torch.Tensor(
            [img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
        with torch.no_grad():
            x = transform(img).unsqueeze(0)
            (x, scale) = (x.cuda(), scale.cuda())

            _t['im_detect'].tic()
            out = model(x)  # forward pass
            (boxes, scores) = detector.forward(out, priors)
            detect_time = _t['im_detect'].toc()

        boxes *= scale  # scale each detection back up to the image
        boxes = boxes.cpu().numpy()
        scores = scores.cpu().numpy()

        _t['im_nms'].tic()
        for j in range(1, num_classes):
            inds = np.where(scores[:, j - 1] > thresh)[0]
            if len(inds) == 0:
                all_boxes[j][i] = np.empty([0, 5], dtype=np.float32)
                continue
            c_bboxes = boxes[inds]
            c_scores = scores[inds, j - 1]
            c_dets = np.hstack(
                (c_bboxes, c_scores[:, np.newaxis])).astype(np.float32,
                                                            copy=False)
            keep = nms(c_dets,
                       thresh=args.nms_thresh)  # non maximum suppression
            c_dets = c_dets[keep, :]
            all_boxes[j][i] = c_dets
        if max_per_image > 0:
            image_scores = np.hstack(
                [all_boxes[j][i][:, -1] for j in range(1, num_classes)])
            if len(image_scores) > max_per_image:
                image_thresh = np.sort(image_scores)[-max_per_image]
                for j in range(1, num_classes):
                    keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]
                    all_boxes[j][i] = all_boxes[j][i][keep, :]
        nms_time = _t['im_nms'].toc()

        if i == 10:
            _t['im_detect'].clear()
            _t['im_nms'].clear()
        if i % math.floor(num_images / 10) == 0 and i > 0:
            print('[{}/{}]Time results: detect={:.2f}ms,nms={:.2f}ms,'.format(
                i, num_images, detect_time * 1000, nms_time * 1000))
    testset.evaluate_detections(all_boxes, 'eval/{}/'.format(args.dataset))
    model.train()