pose3d_metro.py 3.9 KB
Newer Older
Z
zhiboniu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. 
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and 
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from ppdet.core.workspace import register, create
from .meta_arch import BaseArch
from .. import layers as L

__all__ = ['METRO_Body']


def orthographic_projection(X, camera):
    """Perform orthographic projection of 3D points X using the camera parameters
    Args:
        X: size = [B, N, 3]
        camera: size = [B, 3]
    Returns:
        Projected 2D points -- size = [B, N, 2]
    """
    camera = camera.reshape((-1, 1, 3))
    X_trans = X[:, :, :2] + camera[:, :, 1:]
    shape = paddle.shape(X_trans)
    X_2d = (camera[:, :, 0] * X_trans.reshape((shape[0], -1))).reshape(shape)
    return X_2d


@register
class METRO_Body(BaseArch):
    __category__ = 'architecture'
    __inject__ = ['loss']

    def __init__(
            self,
            num_joints,
            backbone='HRNet',
            trans_encoder='',
            loss='Pose3DLoss', ):
        """
Z
zhiboniu 已提交
56
        Modified from METRO network, see https://arxiv.org/abs/2012.09760
Z
zhiboniu 已提交
57 58 59 60 61 62 63 64 65 66 67

        Args:
            backbone (nn.Layer): backbone instance
        """
        super(METRO_Body, self).__init__()
        self.num_joints = num_joints
        self.backbone = backbone
        self.loss = loss
        self.deploy = False

        self.trans_encoder = trans_encoder
Z
zhiboniu 已提交
68
        self.conv_learn_tokens = paddle.nn.Conv1D(49, num_joints + 10, 1)
Z
zhiboniu 已提交
69
        self.cam_param_fc = paddle.nn.Linear(3, 2)
Z
zhiboniu 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

    @classmethod
    def from_config(cls, cfg, *args, **kwargs):
        # backbone
        backbone = create(cfg['backbone'])
        trans_encoder = create(cfg['trans_encoder'])

        return {'backbone': backbone, 'trans_encoder': trans_encoder}

    def _forward(self):
        batch_size = self.inputs['image'].shape[0]

        image_feat = self.backbone(self.inputs)
        image_feat_flatten = image_feat.reshape((batch_size, 2048, 49))
        image_feat_flatten = image_feat_flatten.transpose(perm=(0, 2, 1))
        # and apply a conv layer to learn image token for each 3d joint/vertex position
Z
zhiboniu 已提交
86
        features = self.conv_learn_tokens(image_feat_flatten)  # (B, J, C)
Z
zhiboniu 已提交
87 88 89 90 91 92 93 94 95 96

        if self.training:
            # apply mask vertex/joint modeling
            # meta_masks is a tensor of all the masks, randomly generated in dataloader
            # we pre-define a [MASK] token, which is a floating-value vector with 0.01s
            meta_masks = self.inputs['mjm_mask'].expand((-1, -1, 2048))
            constant_tensor = paddle.ones_like(features) * 0.01
            features = features * meta_masks + constant_tensor * (1 - meta_masks
                                                                  )
        pred_out = self.trans_encoder(features)
Z
zhiboniu 已提交
97

Z
zhiboniu 已提交
98 99 100 101
        pred_3d_joints = pred_out[:, :self.num_joints, :]
        cam_features = pred_out[:, self.num_joints:, :]

        # learn camera parameters
Z
zhiboniu 已提交
102
        pred_2d_joints = self.cam_param_fc(cam_features)
Z
zhiboniu 已提交
103 104 105 106 107 108 109 110 111 112 113 114
        return pred_3d_joints, pred_2d_joints

    def get_loss(self):
        preds_3d, preds_2d = self._forward()
        loss = self.loss(preds_3d, preds_2d, self.inputs)
        output = {'loss': loss}
        return output

    def get_pred(self):
        preds_3d, preds_2d = self._forward()
        outputs = {'pose3d': preds_3d, 'pose2d': preds_2d}
        return outputs