コード例 #1
0
    def __init__(self, phase, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        # TODO: implement __call__ in PriorBox
        self.priorbox = PriorBox(v2)
        # PyTorch 1.5.1
        # self.priors = Variable(self.priorbox.forward(), volatile=True)
        self.priors = self.priorbox.forward()
        self.size = 300

        # SSD network
        self.vgg = nn.ModuleList(base)
        # Layer learns to scale the l2 normalized features from conv4_3
        self.L2Norm = L2Norm(512, 20)
        self.extras = nn.ModuleList(extras)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        if phase == 'test':
            # PyTorch 1.5.1
            # self.softmax = nn.Softmax()
            # self.detect = Detect(num_classes, 0, 200, 0.01, 0.45)
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect()
コード例 #2
0
ファイル: ssd.py プロジェクト: wenliangsun/GraduationProject
    def __init__(self, phase, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        # TODO: implement __call__ in PriorBox
        self.priorbox = PriorBox(v2)

        self.priors = Variable(self.priorbox.forward(), volatile=True)
        self.size = 512

        # SSD network
        self.vgg = nn.ModuleList(base)
        # Layer learns to scale the l2 normalized features from conv4_3
        self.L2Norm = L2Norm(512, 20)
        self.extras = nn.ModuleList(extras)

        # fused conv4_3 and conv5_3
        self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 1)
        self.conv4_3 = nn.Conv2d(512, 512, 3, 1, 1)
        self.deconv = nn.ConvTranspose2d(512, 512, 2, 2)
        self.deconv2 = nn.ConvTranspose2d(512, 256, 2, 2)
        self.conv5_3 = nn.Conv2d(512, 512, 3, 1, 1)
        self.L2Norm5_3 = L2Norm(512, 10)
        self.L2Norm3_3 = L2Norm(256, 20)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        if self.phase == 'test':
            self.softmax = nn.Softmax()
            self.detect = Detect(num_classes, 0, 300, 0.01, 0.45)
コード例 #3
0
    def __init__(self, phase, size, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        self.cfg = {
            'num_classes': 21,
            'lr_steps': (80000, 100000, 120000),
            'max_iter': 120000,
            'feature_maps': [38, 19, 10, 5, 3, 1],
            'min_dim': 300,
            'steps': [8, 16, 32, 64, 100, 300],
            'min_sizes': [30, 60, 111, 162, 213, 264],
            'max_sizes': [60, 111, 162, 213, 264, 315],
            'aspect_ratios': [[2], [2, 3], [2, 3], [2, 3], [2], [2]],
            'variance': [0.1, 0.2],
            'clip': True,
            'name': 'VOC',
        }
        self.priorbox = PriorBox(self.cfg)

        with torch.no_grad():
            self.priors = Variable(self.priorbox.forward())
        self.size = size

        # SSD network
        self.vgg = nn.ModuleList(base)
        self.L2Norm = L2Norm(512, 20)
        self.extras = nn.ModuleList(extras)

        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, 0, 200, 0.01, 0.45)
コード例 #4
0
ファイル: msc.py プロジェクト: wenliangsun/GraduationProject
    def __init__(self, phase, base, head, num_classes):
        super(MSC, self).__init__()
        self.phase = phase
        self.num_classes = num_classes

        self.priorbox = PriorBox(v2)
        self.priors = Variable(self.priorbox.forward(), volatile=True)
        self.size = 512
        self.vgg = nn.ModuleList(base)

        self.L2Norm4_3 = L2Norm(512, 20)
        self.L2Norm5_3 = L2Norm(512, 10)

        self.deconv7 = nn.ConvTranspose2d(2048, 2048, 2, 2)
        self.deconv6 = nn.ConvTranspose2d(2048, 512, 2, 2)
        self.deconv5 = nn.ConvTranspose2d(512, 512, 2, 2)
        self.conv_fc6 = nn.Conv2d(2048, 2048, 3, 1, 1)
        self.conv5_3 = nn.Conv2d(512, 512, 3, 1, 1)
        self.conv4_3 = nn.Conv2d(512, 512, 3, 1, 1)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        if self.phase == 'test':
            self.softmax = nn.Softmax()
            self.detect = Detect(num_classes, 0, 300, 0.01, 0.45)
コード例 #5
0
    def __init__(self, phase, basenet, head, num_classes):
        super(TibNet, self).__init__()
        self.phase = phase
        self.num_classes = num_classes

        self.sa = mobilefacenet.SpatialAttention()
        self.base = nn.ModuleList(basenet)
        self.upfeat = []
        for it in range(5):
            self.upfeat.append(upsample(in_channels=64, out_channels=64))
        self.upfeat = nn.ModuleList(self.upfeat)
        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])
        if self.phase == 'test':
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect(cfg)
コード例 #6
0
    def __init__(self, phase, base, head, num_classes):
        super(STDN, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        self.size = 512  # 没有用

        self.priorbox = PriorBox(v2)
        self.priors = Variable(self.priorbox.forward(), volatile=True)

        self.basenet = nn.ModuleList(base)
        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        self.out1 = nn.AvgPool2d(9, 9)
        self.out2 = nn.AvgPool2d(3, 3)
        self.out3 = nn.AvgPool2d(2, 2)

        if self.phase == 'test':
            self.softmax = nn.Softmax()
            self.detect = Detect(num_classes, 0, 300, 0.01, 0.45)
コード例 #7
0
ファイル: EXTD_48.py プロジェクト: zzmcdc/EXTD_Pytorch
    def __init__(self, phase, base, head, num_classes):
        super(EXTD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes

        # SSD network
        self.base = nn.ModuleList(base)

        self.upfeat = []

        for it in range(5):
            self.upfeat.append(upsample(in_channels=48, out_channels=48))

        self.upfeat = nn.ModuleList(self.upfeat)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        if self.phase == 'test':
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect(cfg)
コード例 #8
0
    def __init__(self, phase, base, head, num_classes):
        super(EXTD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        '''
        self.priorbox = PriorBox(size,cfg)
        self.priors = Variable(self.priorbox.forward(), volatile=True)
        '''
        # SSD network
        self.base = nn.ModuleList(base)

        self.upfeat = []

        for it in range(5):
            self.upfeat.append(upsample(in_channels=32, out_channels=32))

        self.upfeat = nn.ModuleList(self.upfeat)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        if self.phase == 'test':
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect(cfg)
コード例 #9
0
    def __init__(self, phase, size, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        self.cfg = voc  # (coco, voc)[num_classes == 21]
        self.priorbox = PriorBox(self.cfg)
        self.priors = self.priorbox.forward(
        )  # Generate default boxes (anchors)
        self.size = size

        # SSD network
        self.vgg = nn.ModuleList(base)

        # Layer learns to scale the l2 normalized features from conv4_3
        self.L2Norm = L2Norm(512, 20)

        self.extras = nn.ModuleList(extras)

        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, 0, 200, 0.01, 0.45)
コード例 #10
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"
        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, base, extras, head, num_classes):
        super(SSD, self).__init__()
        self.phase = phase
        self.num_classes = num_classes
        # TODO: implement __call__ in PriorBox
        self.priorbox = PriorBox(v2)
        # PyTorch 1.5.1
        # self.priors = Variable(self.priorbox.forward(), volatile=True)
        self.priors = self.priorbox.forward()
        self.size = 300

        # SSD network
        self.vgg = nn.ModuleList(base)
        # Layer learns to scale the l2 normalized features from conv4_3
        self.L2Norm = L2Norm(512, 20)
        self.extras = nn.ModuleList(extras)

        self.loc = nn.ModuleList(head[0])
        self.conf = nn.ModuleList(head[1])

        if phase == 'test':
            # PyTorch 1.5.1
            # self.softmax = nn.Softmax()
            # self.detect = Detect(num_classes, 0, 200, 0.01, 0.45)
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect()

    def forward(self, x):
        """Applies network layers and ops on input image(s) x.
 
        Args:
            x: input image or batch of images. Shape: [batch,3*batch,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]
        """
        sources = list()
        loc = list()
        conf = list()

        # apply vgg up to conv4_3 relu
        for k in range(23):
            x = self.vgg[k](x)

        s = self.L2Norm(x)
        sources.append(s)

        # apply vgg up to fc7
        for k in range(23, len(self.vgg)):
            x = self.vgg[k](x)
        sources.append(x)

        # apply extra layers and cache source layer outputs
        for k, v in enumerate(self.extras):
            x = F.relu(v(x), inplace=True)
            if k % 2 == 1:
                sources.append(x)

        # apply multibox head to source layers
        for (x, l, c) in zip(sources, self.loc, self.conf):
            loc.append(l(x).permute(0, 2, 3, 1).contiguous())
            conf.append(c(x).permute(0, 2, 3, 1).contiguous())

        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 self.phase == "test":
            # PyTorch 1.5.1
            # output = self.detect(
            #     loc.view(loc.size(0), -1, 4),                   # loc preds
            #     self.softmax(conf.view(-1, self.num_classes)),  # conf preds
            #     self.priors.type(type(x.data))                  # default boxes
            # )
            output = self.detect.apply(
                self.num_classes,
                0,
                200,
                0.01,
                0.45,
                loc.view(loc.size(0), -1, 4),  # loc preds
                self.softmax(conf.view(-1, self.num_classes)),  # conf preds
                self.priors.type(type(x.data))  # default boxes
            )
        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.')
コード例 #11
0
    def __init__(self, phase, num_classes):
        super(BlazeFace, self).__init__()

        self.firstconv = nn.Sequential(
            nn.Conv2d(in_channels=2,
                      out_channels=16,
                      kernel_size=3,
                      stride=2,
                      padding=1),
            nn.BatchNorm2d(16),
            nn.ReLU(inplace=True),
        )

        self.blazeBlock = nn.Sequential(
            BlazeBlock(in_channels=16, out_channels=16),
            # BlazeBlock(in_channels=24, out_channels=24),
            BlazeBlock(in_channels=16, out_channels=32, stride=2),
            # BlazeBlock(in_channels=48, out_channels=48),
            BlazeBlock(in_channels=32, out_channels=32),
        )

        self.doubleBlazeBlock = nn.Sequential(
            DoubleBlazeBlock(in_channels=32,
                             out_channels=64,
                             mid_channels=16,
                             stride=2),
            # DoubleBlazeBlock(in_channels=96, out_channels=96, mid_channels=24),
            DoubleBlazeBlock(in_channels=64, out_channels=64, mid_channels=16),
        )

        self.conv2d_8x8_classificators = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=6, kernel_size=1, stride=1),
            nn.BatchNorm2d(6),
        )

        self.conv2d_16x16_classificators = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=2, kernel_size=1, stride=1),
            nn.BatchNorm2d(2),
        )

        self.conv2d_8x8_regressors = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=64, kernel_size=1,
                      stride=1),
            nn.BatchNorm2d(64),
        )

        self.conv2d_16x16_regressors = nn.Sequential(
            nn.Conv2d(in_channels=64, out_channels=32, kernel_size=1,
                      stride=1),
            nn.BatchNorm2d(32),
        )

        self.phase = phase
        self.cfg = celeba
        self.priorbox = PriorBox(self.cfg)
        self.num_classes = num_classes
        # self.priors = Variable(self.priorbox.forward(), volatile=True)

        if phase == 'test':
            self.softmax = nn.Softmax(dim=-1)
            self.detect = Detect(self.num_classes, 0, 200, 0.01, 0.45)

        with torch.no_grad():
            self.priors = self.priorbox.forward()

        print(self.priors.shape)
        self.initialize()
コード例 #12
0
def main(input_path, output_path, detection_model_path='weights/WIDERFace_DSFD_RES152.pt'):
    cuda = True
    torch.set_grad_enabled(False)
    device = torch.device('cuda:{}'.format(0))
    if cuda and torch.cuda.is_available():
        torch.set_default_tensor_type('torch.cuda.FloatTensor')
    else:
        torch.set_default_tensor_type('torch.FloatTensor')

    # Initialize detection model
    # cfg = widerface_640
    # thresh = cfg['conf_thresh']
    # net = build_ssd('test', cfg['min_dim'], cfg['num_classes'])  # initialize SSD
    # net.load_state_dict(torch.load(detection_model_path))
    # net = net.cuda()
    # net.eval()

    cfg = widerface_640
    thresh = cfg['conf_thresh']
    net = torch.jit.load(detection_model_path, map_location=device)
    net.eval()
    print('Finished loading detection model!')

    transform = TestBaseTransform((104, 117, 123))
    detect = Detect(cfg['num_classes'], 0, cfg['num_thresh'], cfg['conf_thresh'], cfg['nms_thresh'])

    # Open target video file
    cap = cv2.VideoCapture(input_path)
    if not cap.isOpened():
        raise RuntimeError('Failed to read video: ' + input_path)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    target_vid_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    target_vid_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # Calculate priors
    image_size = (target_vid_height, target_vid_width)
    featuremap_size = [(math.ceil(image_size[0] / (2 ** (2 + i))), math.ceil(image_size[1] / (2 ** (2 + i))))
                       for i in range(6)]
    priors = get_prior_boxes(cfg, featuremap_size, image_size).to(device)

    # Initialize output video file
    if output_path is not None:
        if os.path.isdir(output_path):
            output_filename = os.path.splitext(os.path.basename(input_path))[0] + '.mp4'
            output_path = os.path.join(output_path, output_filename)
        fourcc = cv2.VideoWriter_fourcc(*'x264')
        out_vid = cv2.VideoWriter(output_path, fourcc, fps, (target_vid_width, target_vid_height))
    else:
        out_vid = None

    #
    max_im_shrink = ((2000.0 * 2000.0) / (target_vid_height * target_vid_width)) ** 0.5
    shrink = max_im_shrink if max_im_shrink < 1 else 1

    # For each frame in the video
    for i in tqdm(range(total_frames)):
        ret, frame = cap.read()
        if frame is None:
            continue

        # Process
        frame_tensor = torch.from_numpy(transform(frame)[0]).permute(2, 0, 1).unsqueeze(0).to(device)
        # image_size = frame_tensor.shape[2:]
        # featuremap_size = [(math.ceil(image_size[0] / (2 ** (2 + i))), math.ceil(image_size[1] / (2 ** (2 + i))))
        #                    for i in range(6)]
        # priors = get_prior_boxes(cfg, featuremap_size, image_size).to(device)

        pred = net(frame_tensor)
        detections = detect(pred[:, :, :4], pred[:, :, 4:], priors)

        det = []
        shrink = 1.0
        scale = torch.Tensor([image_size[1] / shrink, image_size[0] / shrink,
                              image_size[1] / shrink, image_size[0] / shrink])
        for i in range(detections.size(1)):
            j = 0
            while detections[0, i, j, 0] >= thresh:
                curr_det = detections[0, i, j, [1, 2, 3, 4, 0]].cpu().numpy()
                curr_det[:4] *= scale.cpu().numpy()
                det.append(curr_det)
                j += 1

                # curr_det[:4] *= scale
                # score = detections[0, i, j, 0]
                # # label_name = labelmap[i-1]
                # pt = (detections[0, i, j, 1:] * scale).cpu().numpy()
                # coords = (pt[0], pt[1], pt[2], pt[3])
                # det.append([pt[0], pt[1], pt[2], pt[3], score])
                # j += 1

        det = np.row_stack((det))
        # if det.shape[0] > 1:
        #     det = bbox_vote(det.astype(float))
        det = np.round(det[det[:, 4] > 0.5, :4]).astype(int)

        # # Render
        render_img = frame
        for rect in det:
            # cv2.rectangle(render_img, tuple(rect[:2]), tuple(rect[:2] + rect[2:]), (0, 0, 255), 1)
            cv2.rectangle(render_img, tuple(rect[:2]), tuple(rect[2:]), (0, 0, 255), 1)
        if out_vid is not None:
            out_vid.write(render_img)
        cv2.imshow('render_img', render_img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break