Spaces:
Runtime error
Runtime error
add model
Browse files- __pycache__/model.cpython-39.pyc +0 -0
- __pycache__/utils.cpython-39.pyc +0 -0
- app.py +60 -3
- backbone/__pycache__/repvgg.cpython-39.pyc +0 -0
- backbone/__pycache__/se_block.cpython-39.pyc +0 -0
- backbone/repvgg.py +301 -0
- backbone/se_block.py +22 -0
- demo.py +141 -0
- face_down.jpg +0 -0
- face_right.jpg +0 -0
- face_up.jpg +0 -0
- flagged/log.csv +2 -0
- model.py +117 -0
- utils.py +208 -0
- weights_ALFW_A0.pth +3 -0
__pycache__/model.cpython-39.pyc
ADDED
Binary file (3.81 kB). View file
|
|
__pycache__/utils.cpython-39.pyc
ADDED
Binary file (5.59 kB). View file
|
|
app.py
CHANGED
@@ -1,8 +1,65 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
def predict(inp):
|
4 |
-
return "Yaw: 30 \n Pitch: 19\n Direction: Left"
|
5 |
gr.Interface(fn=predict,
|
6 |
inputs=gr.Image(type="pil"),
|
7 |
outputs=gr.Textbox(),
|
8 |
-
examples=["face_left.jpg","face_right.jpg","face_up.jpg","face_down.jpg"]).launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from model import SixDRepNet
|
3 |
+
import os
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
from torchvision import transforms
|
8 |
+
import utils
|
9 |
+
import time
|
10 |
+
|
11 |
+
transformations = transforms.Compose([transforms.Resize(224),
|
12 |
+
transforms.CenterCrop(224),
|
13 |
+
transforms.ToTensor(),
|
14 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
|
15 |
+
|
16 |
+
model = SixDRepNet(backbone_name='RepVGG-A0',
|
17 |
+
backbone_file='',
|
18 |
+
deploy=True,
|
19 |
+
pretrained=False)
|
20 |
+
|
21 |
+
saved_state_dict = torch.load(os.path.join(
|
22 |
+
"weights_ALFW_A0.pth"), map_location='cpu')
|
23 |
+
|
24 |
+
if 'model_state_dict' in saved_state_dict:
|
25 |
+
model.load_state_dict(saved_state_dict['model_state_dict'])
|
26 |
+
else:
|
27 |
+
model.load_state_dict(saved_state_dict)
|
28 |
+
|
29 |
+
# Test the Model
|
30 |
+
model.eval() # Change model to 'eval' mode (BN uses moving mean/var).
|
31 |
+
|
32 |
+
th = 15
|
33 |
+
|
34 |
+
def predict(img):
|
35 |
+
|
36 |
+
img = img.convert('RGB')
|
37 |
+
img = transformations(img).unsqueeze(0)
|
38 |
+
with torch.no_grad():
|
39 |
+
start = time.time()
|
40 |
+
R_pred = model(img)
|
41 |
+
end = time.time()
|
42 |
+
timemilis = (end - start)*1000
|
43 |
+
|
44 |
+
euler = utils.compute_euler_angles_from_rotation_matrices(
|
45 |
+
R_pred,use_gpu=False)*180/np.pi
|
46 |
+
p_pred_deg = euler[:, 0].cpu().item()
|
47 |
+
y_pred_deg = euler[:, 1].cpu().item()
|
48 |
+
direction_str = ""
|
49 |
+
if p_pred_deg > th:
|
50 |
+
direction_str = "UP "
|
51 |
+
elif p_pred_deg < th:
|
52 |
+
direction_str ="DOWN "
|
53 |
+
|
54 |
+
if y_pred_deg > th:
|
55 |
+
direction_str += "LEFT"
|
56 |
+
elif y_pred_deg < th:
|
57 |
+
direction_str += "RIGHT"
|
58 |
+
|
59 |
+
return f"Yaw: {y_pred_deg:0.1f} \n Pitch: {p_pred_deg:0.1f}\n Direction: {direction_str} \n Time: {timemilis:0.2f}ms"
|
60 |
+
|
61 |
|
|
|
|
|
62 |
gr.Interface(fn=predict,
|
63 |
inputs=gr.Image(type="pil"),
|
64 |
outputs=gr.Textbox(),
|
65 |
+
examples=["face_left.jpg","face_right.jpg","face_up.jpg","face_down.jpg"]).launch(share=True)
|
backbone/__pycache__/repvgg.cpython-39.pyc
ADDED
Binary file (9.5 kB). View file
|
|
backbone/__pycache__/se_block.cpython-39.pyc
ADDED
Binary file (1.1 kB). View file
|
|
backbone/repvgg.py
ADDED
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import torch.nn as nn
|
3 |
+
import numpy as np
|
4 |
+
import torch
|
5 |
+
import copy
|
6 |
+
from backbone.se_block import SEBlock
|
7 |
+
|
8 |
+
def conv_bn(in_channels, out_channels, kernel_size, stride, padding, groups=1):
|
9 |
+
result = nn.Sequential()
|
10 |
+
result.add_module('conv', nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
|
11 |
+
kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False))
|
12 |
+
result.add_module('bn', nn.BatchNorm2d(num_features=out_channels))
|
13 |
+
return result
|
14 |
+
|
15 |
+
class RepVGGBlock(nn.Module):
|
16 |
+
|
17 |
+
def __init__(self, in_channels, out_channels, kernel_size,
|
18 |
+
stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', deploy=False, use_se=False):
|
19 |
+
super(RepVGGBlock, self).__init__()
|
20 |
+
self.deploy = deploy
|
21 |
+
self.groups = groups
|
22 |
+
self.in_channels = in_channels
|
23 |
+
|
24 |
+
assert kernel_size == 3
|
25 |
+
assert padding == 1
|
26 |
+
|
27 |
+
padding_11 = padding - kernel_size // 2
|
28 |
+
|
29 |
+
self.nonlinearity = nn.ReLU()
|
30 |
+
|
31 |
+
if use_se:
|
32 |
+
self.se = SEBlock(out_channels, internal_neurons=out_channels // 16)
|
33 |
+
else:
|
34 |
+
self.se = nn.Identity()
|
35 |
+
|
36 |
+
if deploy:
|
37 |
+
self.rbr_reparam = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride,
|
38 |
+
padding=padding, dilation=dilation, groups=groups, bias=True, padding_mode=padding_mode)
|
39 |
+
|
40 |
+
else:
|
41 |
+
self.rbr_identity = nn.BatchNorm2d(num_features=in_channels) if out_channels == in_channels and stride == 1 else None
|
42 |
+
self.rbr_dense = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups)
|
43 |
+
self.rbr_1x1 = conv_bn(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=padding_11, groups=groups)
|
44 |
+
print('RepVGG Block, identity = ', self.rbr_identity)
|
45 |
+
|
46 |
+
|
47 |
+
def forward(self, inputs):
|
48 |
+
if hasattr(self, 'rbr_reparam'):
|
49 |
+
return self.nonlinearity(self.se(self.rbr_reparam(inputs)))
|
50 |
+
|
51 |
+
if self.rbr_identity is None:
|
52 |
+
id_out = 0
|
53 |
+
else:
|
54 |
+
id_out = self.rbr_identity(inputs)
|
55 |
+
|
56 |
+
return self.nonlinearity(self.se(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out))
|
57 |
+
|
58 |
+
|
59 |
+
# Optional. This improves the accuracy and facilitates quantization.
|
60 |
+
# 1. Cancel the original weight decay on rbr_dense.conv.weight and rbr_1x1.conv.weight.
|
61 |
+
# 2. Use like this.
|
62 |
+
# loss = criterion(....)
|
63 |
+
# for every RepVGGBlock blk:
|
64 |
+
# loss += weight_decay_coefficient * 0.5 * blk.get_cust_L2()
|
65 |
+
# optimizer.zero_grad()
|
66 |
+
# loss.backward()
|
67 |
+
def get_custom_L2(self):
|
68 |
+
K3 = self.rbr_dense.conv.weight
|
69 |
+
K1 = self.rbr_1x1.conv.weight
|
70 |
+
t3 = (self.rbr_dense.bn.weight / ((self.rbr_dense.bn.running_var + self.rbr_dense.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
|
71 |
+
t1 = (self.rbr_1x1.bn.weight / ((self.rbr_1x1.bn.running_var + self.rbr_1x1.bn.eps).sqrt())).reshape(-1, 1, 1, 1).detach()
|
72 |
+
|
73 |
+
l2_loss_circle = (K3 ** 2).sum() - (K3[:, :, 1:2, 1:2] ** 2).sum() # The L2 loss of the "circle" of weights in 3x3 kernel. Use regular L2 on them.
|
74 |
+
eq_kernel = K3[:, :, 1:2, 1:2] * t3 + K1 * t1 # The equivalent resultant central point of 3x3 kernel.
|
75 |
+
l2_loss_eq_kernel = (eq_kernel ** 2 / (t3 ** 2 + t1 ** 2)).sum() # Normalize for an L2 coefficient comparable to regular L2.
|
76 |
+
return l2_loss_eq_kernel + l2_loss_circle
|
77 |
+
|
78 |
+
|
79 |
+
|
80 |
+
# This func derives the equivalent kernel and bias in a DIFFERENTIABLE way.
|
81 |
+
# You can get the equivalent kernel and bias at any time and do whatever you want,
|
82 |
+
# for example, apply some penalties or constraints during training, just like you do to the other models.
|
83 |
+
# May be useful for quantization or pruning.
|
84 |
+
def get_equivalent_kernel_bias(self):
|
85 |
+
kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense)
|
86 |
+
kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1)
|
87 |
+
kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity)
|
88 |
+
return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid
|
89 |
+
|
90 |
+
def _pad_1x1_to_3x3_tensor(self, kernel1x1):
|
91 |
+
if kernel1x1 is None:
|
92 |
+
return 0
|
93 |
+
else:
|
94 |
+
return torch.nn.functional.pad(kernel1x1, [1,1,1,1])
|
95 |
+
|
96 |
+
def _fuse_bn_tensor(self, branch):
|
97 |
+
if branch is None:
|
98 |
+
return 0, 0
|
99 |
+
if isinstance(branch, nn.Sequential):
|
100 |
+
kernel = branch.conv.weight
|
101 |
+
running_mean = branch.bn.running_mean
|
102 |
+
running_var = branch.bn.running_var
|
103 |
+
gamma = branch.bn.weight
|
104 |
+
beta = branch.bn.bias
|
105 |
+
eps = branch.bn.eps
|
106 |
+
else:
|
107 |
+
assert isinstance(branch, nn.BatchNorm2d)
|
108 |
+
if not hasattr(self, 'id_tensor'):
|
109 |
+
input_dim = self.in_channels // self.groups
|
110 |
+
kernel_value = np.zeros((self.in_channels, input_dim, 3, 3), dtype=np.float32)
|
111 |
+
for i in range(self.in_channels):
|
112 |
+
kernel_value[i, i % input_dim, 1, 1] = 1
|
113 |
+
self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)
|
114 |
+
kernel = self.id_tensor
|
115 |
+
running_mean = branch.running_mean
|
116 |
+
running_var = branch.running_var
|
117 |
+
gamma = branch.weight
|
118 |
+
beta = branch.bias
|
119 |
+
eps = branch.eps
|
120 |
+
std = (running_var + eps).sqrt()
|
121 |
+
t = (gamma / std).reshape(-1, 1, 1, 1)
|
122 |
+
return kernel * t, beta - running_mean * gamma / std
|
123 |
+
|
124 |
+
def switch_to_deploy(self):
|
125 |
+
if hasattr(self, 'rbr_reparam'):
|
126 |
+
return
|
127 |
+
kernel, bias = self.get_equivalent_kernel_bias()
|
128 |
+
self.rbr_reparam = nn.Conv2d(in_channels=self.rbr_dense.conv.in_channels, out_channels=self.rbr_dense.conv.out_channels,
|
129 |
+
kernel_size=self.rbr_dense.conv.kernel_size, stride=self.rbr_dense.conv.stride,
|
130 |
+
padding=self.rbr_dense.conv.padding, dilation=self.rbr_dense.conv.dilation, groups=self.rbr_dense.conv.groups, bias=True)
|
131 |
+
self.rbr_reparam.weight.data = kernel
|
132 |
+
self.rbr_reparam.bias.data = bias
|
133 |
+
for para in self.parameters():
|
134 |
+
para.detach_()
|
135 |
+
self.__delattr__('rbr_dense')
|
136 |
+
self.__delattr__('rbr_1x1')
|
137 |
+
if hasattr(self, 'rbr_identity'):
|
138 |
+
self.__delattr__('rbr_identity')
|
139 |
+
if hasattr(self, 'id_tensor'):
|
140 |
+
self.__delattr__('id_tensor')
|
141 |
+
self.deploy = True
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
class RepVGG(nn.Module):
|
146 |
+
|
147 |
+
def __init__(self, num_blocks, num_classes=1000, width_multiplier=None, override_groups_map=None, deploy=False, use_se=False):
|
148 |
+
super(RepVGG, self).__init__()
|
149 |
+
|
150 |
+
assert len(width_multiplier) == 4
|
151 |
+
|
152 |
+
self.deploy = deploy
|
153 |
+
self.override_groups_map = override_groups_map or dict()
|
154 |
+
self.use_se = use_se
|
155 |
+
|
156 |
+
assert 0 not in self.override_groups_map
|
157 |
+
|
158 |
+
self.in_planes = min(64, int(64 * width_multiplier[0]))
|
159 |
+
|
160 |
+
self.stage0 = RepVGGBlock(in_channels=3, out_channels=self.in_planes, kernel_size=3, stride=2, padding=1, deploy=self.deploy, use_se=self.use_se)
|
161 |
+
self.cur_layer_idx = 1
|
162 |
+
self.stage1 = self._make_stage(int(64 * width_multiplier[0]), num_blocks[0], stride=2)
|
163 |
+
self.stage2 = self._make_stage(int(128 * width_multiplier[1]), num_blocks[1], stride=2)
|
164 |
+
self.stage3 = self._make_stage(int(256 * width_multiplier[2]), num_blocks[2], stride=2)
|
165 |
+
self.stage4 = self._make_stage(int(512 * width_multiplier[3]), num_blocks[3], stride=2)
|
166 |
+
self.gap = nn.AdaptiveAvgPool2d(output_size=1)
|
167 |
+
self.linear = nn.Linear(int(512 * width_multiplier[3]), num_classes)
|
168 |
+
|
169 |
+
|
170 |
+
def _make_stage(self, planes, num_blocks, stride):
|
171 |
+
strides = [stride] + [1]*(num_blocks-1)
|
172 |
+
blocks = []
|
173 |
+
for stride in strides:
|
174 |
+
cur_groups = self.override_groups_map.get(self.cur_layer_idx, 1)
|
175 |
+
blocks.append(RepVGGBlock(in_channels=self.in_planes, out_channels=planes, kernel_size=3,
|
176 |
+
stride=stride, padding=1, groups=cur_groups, deploy=self.deploy, use_se=self.use_se))
|
177 |
+
self.in_planes = planes
|
178 |
+
self.cur_layer_idx += 1
|
179 |
+
return nn.Sequential(*blocks)
|
180 |
+
|
181 |
+
def forward(self, x):
|
182 |
+
out = self.stage0(x)
|
183 |
+
out = self.stage1(out)
|
184 |
+
out = self.stage2(out)
|
185 |
+
out = self.stage3(out)
|
186 |
+
out = self.stage4(out)
|
187 |
+
out = self.gap(out)
|
188 |
+
out = out.view(out.size(0), -1)
|
189 |
+
out = self.linear(out)
|
190 |
+
return out
|
191 |
+
|
192 |
+
|
193 |
+
optional_groupwise_layers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26]
|
194 |
+
g2_map = {l: 2 for l in optional_groupwise_layers}
|
195 |
+
g4_map = {l: 4 for l in optional_groupwise_layers}
|
196 |
+
|
197 |
+
def create_RepVGG_A0(deploy=False):
|
198 |
+
return RepVGG(num_blocks=[2, 4, 14, 1], num_classes=1000,
|
199 |
+
width_multiplier=[0.75, 0.75, 0.75, 2.5], override_groups_map=None, deploy=deploy)
|
200 |
+
|
201 |
+
def create_RepVGG_A1(deploy=False):
|
202 |
+
return RepVGG(num_blocks=[2, 4, 14, 1], num_classes=1000,
|
203 |
+
width_multiplier=[1, 1, 1, 2.5], override_groups_map=None, deploy=deploy)
|
204 |
+
|
205 |
+
def create_RepVGG_A2(deploy=False):
|
206 |
+
return RepVGG(num_blocks=[2, 4, 14, 1], num_classes=1000,
|
207 |
+
width_multiplier=[1.5, 1.5, 1.5, 2.75], override_groups_map=None, deploy=deploy)
|
208 |
+
|
209 |
+
def create_RepVGG_B0(deploy=False):
|
210 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
211 |
+
width_multiplier=[1, 1, 1, 2.5], override_groups_map=None, deploy=deploy)
|
212 |
+
|
213 |
+
def create_RepVGG_B1(deploy=False):
|
214 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
215 |
+
width_multiplier=[2, 2, 2, 4], override_groups_map=None, deploy=deploy)
|
216 |
+
|
217 |
+
def create_RepVGG_B1g2(deploy=False):
|
218 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
219 |
+
width_multiplier=[2, 2, 2, 4], override_groups_map=g2_map, deploy=deploy)
|
220 |
+
|
221 |
+
def create_RepVGG_B1g4(deploy=False):
|
222 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
223 |
+
width_multiplier=[2, 2, 2, 4], override_groups_map=g4_map, deploy=deploy)
|
224 |
+
|
225 |
+
|
226 |
+
def create_RepVGG_B2(deploy=False):
|
227 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
228 |
+
width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=None, deploy=deploy)
|
229 |
+
|
230 |
+
def create_RepVGG_B2g2(deploy=False):
|
231 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
232 |
+
width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=g2_map, deploy=deploy)
|
233 |
+
|
234 |
+
def create_RepVGG_B2g4(deploy=False):
|
235 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
236 |
+
width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=g4_map, deploy=deploy)
|
237 |
+
|
238 |
+
|
239 |
+
def create_RepVGG_B3(deploy=False):
|
240 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
241 |
+
width_multiplier=[3, 3, 3, 5], override_groups_map=None, deploy=deploy)
|
242 |
+
|
243 |
+
def create_RepVGG_B3g2(deploy=False):
|
244 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
245 |
+
width_multiplier=[3, 3, 3, 5], override_groups_map=g2_map, deploy=deploy)
|
246 |
+
|
247 |
+
def create_RepVGG_B3g4(deploy=False):
|
248 |
+
return RepVGG(num_blocks=[4, 6, 16, 1], num_classes=1000,
|
249 |
+
width_multiplier=[3, 3, 3, 5], override_groups_map=g4_map, deploy=deploy)
|
250 |
+
|
251 |
+
def create_RepVGG_D2se(deploy=False):
|
252 |
+
return RepVGG(num_blocks=[8, 14, 24, 1], num_classes=1000,
|
253 |
+
width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=None, deploy=deploy, use_se=True)
|
254 |
+
|
255 |
+
|
256 |
+
func_dict = {
|
257 |
+
'RepVGG-A0': create_RepVGG_A0,
|
258 |
+
'RepVGG-A1': create_RepVGG_A1,
|
259 |
+
'RepVGG-A2': create_RepVGG_A2,
|
260 |
+
'RepVGG-B0': create_RepVGG_B0,
|
261 |
+
'RepVGG-B1': create_RepVGG_B1,
|
262 |
+
'RepVGG-B1g2': create_RepVGG_B1g2,
|
263 |
+
'RepVGG-B1g4': create_RepVGG_B1g4,
|
264 |
+
'RepVGG-B2': create_RepVGG_B2,
|
265 |
+
'RepVGG-B2g2': create_RepVGG_B2g2,
|
266 |
+
'RepVGG-B2g4': create_RepVGG_B2g4,
|
267 |
+
'RepVGG-B3': create_RepVGG_B3,
|
268 |
+
'RepVGG-B3g2': create_RepVGG_B3g2,
|
269 |
+
'RepVGG-B3g4': create_RepVGG_B3g4,
|
270 |
+
'RepVGG-D2se': create_RepVGG_D2se, # Updated at April 25, 2021. This is not reported in the CVPR paper.
|
271 |
+
}
|
272 |
+
def get_RepVGG_func_by_name(name):
|
273 |
+
return func_dict[name]
|
274 |
+
|
275 |
+
|
276 |
+
|
277 |
+
# Use this for converting a RepVGG model or a bigger model with RepVGG as its component
|
278 |
+
# Use like this
|
279 |
+
# model = create_RepVGG_A0(deploy=False)
|
280 |
+
# train model or load weights
|
281 |
+
# repvgg_model_convert(model, save_path='repvgg_deploy.pth')
|
282 |
+
# If you want to preserve the original model, call with do_copy=True
|
283 |
+
|
284 |
+
# ====================== for using RepVGG as the backbone of a bigger model, e.g., PSPNet, the pseudo code will be like
|
285 |
+
# train_backbone = create_RepVGG_B2(deploy=False)
|
286 |
+
# train_backbone.load_state_dict(torch.load('RepVGG-B2-train.pth'))
|
287 |
+
# train_pspnet = build_pspnet(backbone=train_backbone)
|
288 |
+
# segmentation_train(train_pspnet)
|
289 |
+
# deploy_pspnet = repvgg_model_convert(train_pspnet)
|
290 |
+
# segmentation_test(deploy_pspnet)
|
291 |
+
# ===================== example_pspnet.py shows an example
|
292 |
+
|
293 |
+
def repvgg_model_convert(model:torch.nn.Module, save_path=None, do_copy=True):
|
294 |
+
if do_copy:
|
295 |
+
model = copy.deepcopy(model)
|
296 |
+
for module in model.modules():
|
297 |
+
if hasattr(module, 'switch_to_deploy'):
|
298 |
+
module.switch_to_deploy()
|
299 |
+
if save_path is not None:
|
300 |
+
torch.save(model.state_dict(), save_path)
|
301 |
+
return model
|
backbone/se_block.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
|
5 |
+
# https://openaccess.thecvf.com/content_cvpr_2018/html/Hu_Squeeze-and-Excitation_Networks_CVPR_2018_paper.html
|
6 |
+
|
7 |
+
class SEBlock(nn.Module):
|
8 |
+
|
9 |
+
def __init__(self, input_channels, internal_neurons):
|
10 |
+
super(SEBlock, self).__init__()
|
11 |
+
self.down = nn.Conv2d(in_channels=input_channels, out_channels=internal_neurons, kernel_size=1, stride=1, bias=True)
|
12 |
+
self.up = nn.Conv2d(in_channels=internal_neurons, out_channels=input_channels, kernel_size=1, stride=1, bias=True)
|
13 |
+
self.input_channels = input_channels
|
14 |
+
|
15 |
+
def forward(self, inputs):
|
16 |
+
x = F.avg_pool2d(inputs, kernel_size=inputs.size(3))
|
17 |
+
x = self.down(x)
|
18 |
+
x = F.relu(x)
|
19 |
+
x = self.up(x)
|
20 |
+
x = torch.sigmoid(x)
|
21 |
+
x = x.view(-1, self.input_channels, 1, 1)
|
22 |
+
return inputs * x
|
demo.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from face_detection import RetinaFace
|
2 |
+
from model import SixDRepNet
|
3 |
+
import math
|
4 |
+
import re
|
5 |
+
from matplotlib import pyplot as plt
|
6 |
+
import sys
|
7 |
+
import os
|
8 |
+
import argparse
|
9 |
+
|
10 |
+
import numpy as np
|
11 |
+
import cv2
|
12 |
+
import matplotlib.pyplot as plt
|
13 |
+
from numpy.lib.function_base import _quantile_unchecked
|
14 |
+
|
15 |
+
import torch
|
16 |
+
import torch.nn as nn
|
17 |
+
from torch.utils.data import DataLoader
|
18 |
+
from torchvision import transforms
|
19 |
+
import torch.backends.cudnn as cudnn
|
20 |
+
import torchvision
|
21 |
+
import torch.nn.functional as F
|
22 |
+
import utils
|
23 |
+
import matplotlib
|
24 |
+
from PIL import Image
|
25 |
+
import time
|
26 |
+
matplotlib.use('TkAgg')
|
27 |
+
|
28 |
+
|
29 |
+
def parse_args():
|
30 |
+
"""Parse input arguments."""
|
31 |
+
parser = argparse.ArgumentParser(
|
32 |
+
description='Head pose estimation using the 6DRepNet.')
|
33 |
+
parser.add_argument('--gpu',
|
34 |
+
dest='gpu_id', help='GPU device id to use [0]',
|
35 |
+
default=0, type=int)
|
36 |
+
parser.add_argument('--cam',
|
37 |
+
dest='cam_id', help='Camera device id to use [0]',
|
38 |
+
default=0, type=int)
|
39 |
+
parser.add_argument('--snapshot',
|
40 |
+
dest='snapshot', help='Name of model snapshot.',
|
41 |
+
default='', type=str)
|
42 |
+
parser.add_argument('--save_viz',
|
43 |
+
dest='save_viz', help='Save images with pose cube.',
|
44 |
+
default=False, type=bool)
|
45 |
+
|
46 |
+
args = parser.parse_args()
|
47 |
+
return args
|
48 |
+
|
49 |
+
|
50 |
+
transformations = transforms.Compose([transforms.Resize(224),
|
51 |
+
transforms.CenterCrop(224),
|
52 |
+
transforms.ToTensor(),
|
53 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
|
54 |
+
|
55 |
+
if __name__ == '__main__':
|
56 |
+
args = parse_args()
|
57 |
+
cudnn.enabled = True
|
58 |
+
gpu = args.gpu_id
|
59 |
+
cam = args.cam_id
|
60 |
+
snapshot_path = args.snapshot
|
61 |
+
model = SixDRepNet(backbone_name='RepVGG-A0',
|
62 |
+
backbone_file='',
|
63 |
+
deploy=True,
|
64 |
+
pretrained=False)
|
65 |
+
|
66 |
+
print('Loading data.')
|
67 |
+
|
68 |
+
detector = RetinaFace(gpu_id=gpu)
|
69 |
+
|
70 |
+
# Load snapshot
|
71 |
+
saved_state_dict = torch.load(os.path.join(
|
72 |
+
snapshot_path), map_location='cpu')
|
73 |
+
|
74 |
+
if 'model_state_dict' in saved_state_dict:
|
75 |
+
model.load_state_dict(saved_state_dict['model_state_dict'])
|
76 |
+
else:
|
77 |
+
model.load_state_dict(saved_state_dict)
|
78 |
+
if gpu != -1:
|
79 |
+
model.cuda(gpu)
|
80 |
+
|
81 |
+
# Test the Model
|
82 |
+
model.eval() # Change model to 'eval' mode (BN uses moving mean/var).
|
83 |
+
|
84 |
+
cap = cv2.VideoCapture(cam)
|
85 |
+
|
86 |
+
# Check if the webcam is opened correctly
|
87 |
+
if not cap.isOpened():
|
88 |
+
raise IOError("Cannot open webcam")
|
89 |
+
|
90 |
+
with torch.no_grad():
|
91 |
+
while True:
|
92 |
+
ret, frame = cap.read()
|
93 |
+
|
94 |
+
faces = detector(frame)
|
95 |
+
|
96 |
+
for box, landmarks, score in faces:
|
97 |
+
|
98 |
+
# Print the location of each face in this image
|
99 |
+
if score < .95:
|
100 |
+
continue
|
101 |
+
x_min = int(box[0])
|
102 |
+
y_min = int(box[1])
|
103 |
+
x_max = int(box[2])
|
104 |
+
y_max = int(box[3])
|
105 |
+
bbox_width = abs(x_max - x_min)
|
106 |
+
bbox_height = abs(y_max - y_min)
|
107 |
+
|
108 |
+
x_min = max(0, x_min-int(0.2*bbox_height))
|
109 |
+
y_min = max(0, y_min-int(0.2*bbox_width))
|
110 |
+
x_max = x_max+int(0.2*bbox_height)
|
111 |
+
y_max = y_max+int(0.2*bbox_width)
|
112 |
+
|
113 |
+
img = frame[y_min:y_max, x_min:x_max]
|
114 |
+
img = Image.fromarray(img)
|
115 |
+
img = img.convert('RGB')
|
116 |
+
img = transformations(img)
|
117 |
+
|
118 |
+
img = torch.Tensor(img[None, :])
|
119 |
+
if gpu != -1:
|
120 |
+
img = img.cuda(gpu)
|
121 |
+
|
122 |
+
c = cv2.waitKey(1)
|
123 |
+
if c == 27:
|
124 |
+
break
|
125 |
+
|
126 |
+
start = time.time()
|
127 |
+
R_pred = model(img)
|
128 |
+
end = time.time()
|
129 |
+
print('Head pose estimation: %2f ms' % ((end - start)*1000.))
|
130 |
+
|
131 |
+
euler = utils.compute_euler_angles_from_rotation_matrices(
|
132 |
+
R_pred,use_gpu=False)*180/np.pi
|
133 |
+
p_pred_deg = euler[:, 0].cpu()
|
134 |
+
y_pred_deg = euler[:, 1].cpu()
|
135 |
+
r_pred_deg = euler[:, 2].cpu()
|
136 |
+
|
137 |
+
#utils.draw_axis(frame, y_pred_deg, p_pred_deg, r_pred_deg, left+int(.5*(right-left)), top, size=100)
|
138 |
+
utils.plot_pose_cube(frame, y_pred_deg, p_pred_deg, r_pred_deg, x_min + int(.5*(
|
139 |
+
x_max-x_min)), y_min + int(.5*(y_max-y_min)), size=bbox_width)
|
140 |
+
cv2.imshow("Demo", np.array(frame, dtype = np.uint8))
|
141 |
+
cv2.waitKey(5)
|
face_down.jpg
ADDED
face_right.jpg
ADDED
face_up.jpg
ADDED
flagged/log.csv
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
'img','output','flag','username','timestamp'
|
2 |
+
'','','','','2022-08-17 14:04:57.627952'
|
model.py
ADDED
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
import math
|
5 |
+
from backbone.repvgg import get_RepVGG_func_by_name
|
6 |
+
import utils
|
7 |
+
|
8 |
+
class SixDRepNet(nn.Module):
|
9 |
+
def __init__(self,
|
10 |
+
backbone_name, backbone_file, deploy,
|
11 |
+
bins=(1, 2, 3, 6),
|
12 |
+
droBatchNorm=nn.BatchNorm2d,
|
13 |
+
pretrained=True):
|
14 |
+
super(SixDRepNet, self).__init__()
|
15 |
+
|
16 |
+
repvgg_fn = get_RepVGG_func_by_name(backbone_name)
|
17 |
+
backbone = repvgg_fn(deploy)
|
18 |
+
if pretrained:
|
19 |
+
checkpoint = torch.load(backbone_file)
|
20 |
+
if 'state_dict' in checkpoint:
|
21 |
+
checkpoint = checkpoint['state_dict']
|
22 |
+
ckpt = {k.replace('module.', ''): v for k,
|
23 |
+
v in checkpoint.items()} # strip the names
|
24 |
+
backbone.load_state_dict(ckpt)
|
25 |
+
|
26 |
+
self.layer0, self.layer1, self.layer2, self.layer3, self.layer4 = backbone.stage0, backbone.stage1, backbone.stage2, backbone.stage3, backbone.stage4
|
27 |
+
self.gap = nn.AdaptiveAvgPool2d(output_size=1)
|
28 |
+
|
29 |
+
last_channel = 0
|
30 |
+
for n, m in self.layer4.named_modules():
|
31 |
+
if ('rbr_dense' in n or 'rbr_reparam' in n) and isinstance(m, nn.Conv2d):
|
32 |
+
last_channel = m.out_channels
|
33 |
+
|
34 |
+
fea_dim = last_channel
|
35 |
+
|
36 |
+
self.linear_reg = nn.Linear(fea_dim, 6)
|
37 |
+
|
38 |
+
def forward(self, x):
|
39 |
+
|
40 |
+
x = self.layer0(x)
|
41 |
+
x = self.layer1(x)
|
42 |
+
x = self.layer2(x)
|
43 |
+
x = self.layer3(x)
|
44 |
+
x = self.layer4(x)
|
45 |
+
x= self.gap(x)
|
46 |
+
x = torch.flatten(x, 1)
|
47 |
+
x = self.linear_reg(x)
|
48 |
+
return utils.compute_rotation_matrix_from_ortho6d(x,use_gpu=False)
|
49 |
+
|
50 |
+
|
51 |
+
|
52 |
+
|
53 |
+
class SixDRepNet2(nn.Module):
|
54 |
+
def __init__(self, block, layers, fc_layers=1):
|
55 |
+
self.inplanes = 64
|
56 |
+
super(SixDRepNet2, self).__init__()
|
57 |
+
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
|
58 |
+
bias=False)
|
59 |
+
self.bn1 = nn.BatchNorm2d(64)
|
60 |
+
self.relu = nn.ReLU(inplace=True)
|
61 |
+
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
62 |
+
self.layer1 = self._make_layer(block, 64, layers[0])
|
63 |
+
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
|
64 |
+
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
|
65 |
+
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
|
66 |
+
self.avgpool = nn.AvgPool2d(7)
|
67 |
+
|
68 |
+
self.linear_reg = nn.Linear(512*block.expansion,6)
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
# Vestigial layer from previous experiments
|
73 |
+
self.fc_finetune = nn.Linear(512 * block.expansion + 3, 3)
|
74 |
+
|
75 |
+
for m in self.modules():
|
76 |
+
if isinstance(m, nn.Conv2d):
|
77 |
+
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
|
78 |
+
m.weight.data.normal_(0, math.sqrt(2. / n))
|
79 |
+
elif isinstance(m, nn.BatchNorm2d):
|
80 |
+
m.weight.data.fill_(1)
|
81 |
+
m.bias.data.zero_()
|
82 |
+
|
83 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
84 |
+
downsample = None
|
85 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
86 |
+
downsample = nn.Sequential(
|
87 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
88 |
+
kernel_size=1, stride=stride, bias=False),
|
89 |
+
nn.BatchNorm2d(planes * block.expansion),
|
90 |
+
)
|
91 |
+
|
92 |
+
layers = []
|
93 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
94 |
+
self.inplanes = planes * block.expansion
|
95 |
+
for i in range(1, blocks):
|
96 |
+
layers.append(block(self.inplanes, planes))
|
97 |
+
|
98 |
+
return nn.Sequential(*layers)
|
99 |
+
|
100 |
+
def forward(self, x):
|
101 |
+
x = self.conv1(x)
|
102 |
+
x = self.bn1(x)
|
103 |
+
x = self.relu(x)
|
104 |
+
x = self.maxpool(x)
|
105 |
+
|
106 |
+
x = self.layer1(x)
|
107 |
+
x = self.layer2(x)
|
108 |
+
x = self.layer3(x)
|
109 |
+
x = self.layer4(x)
|
110 |
+
|
111 |
+
x = self.avgpool(x)
|
112 |
+
x = x.view(x.size(0), -1)
|
113 |
+
|
114 |
+
x = self.linear_reg(x)
|
115 |
+
out = utils.compute_rotation_matrix_from_ortho6d(x)
|
116 |
+
|
117 |
+
return out
|
utils.py
ADDED
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
#from torch.utils.serialization import load_lua
|
4 |
+
import os
|
5 |
+
import scipy.io as sio
|
6 |
+
import cv2
|
7 |
+
import math
|
8 |
+
from math import cos, sin
|
9 |
+
|
10 |
+
def plot_pose_cube(img, yaw, pitch, roll, tdx=None, tdy=None, size=150.):
|
11 |
+
# Input is a cv2 image
|
12 |
+
# pose_params: (pitch, yaw, roll, tdx, tdy)
|
13 |
+
# Where (tdx, tdy) is the translation of the face.
|
14 |
+
# For pose we have [pitch yaw roll tdx tdy tdz scale_factor]
|
15 |
+
|
16 |
+
p = pitch * np.pi / 180
|
17 |
+
y = -(yaw * np.pi / 180)
|
18 |
+
r = roll * np.pi / 180
|
19 |
+
if tdx != None and tdy != None:
|
20 |
+
face_x = tdx - 0.50 * size
|
21 |
+
face_y = tdy - 0.50 * size
|
22 |
+
|
23 |
+
else:
|
24 |
+
height, width = img.shape[:2]
|
25 |
+
face_x = width / 2 - 0.5 * size
|
26 |
+
face_y = height / 2 - 0.5 * size
|
27 |
+
|
28 |
+
x1 = size * (cos(y) * cos(r)) + face_x
|
29 |
+
y1 = size * (cos(p) * sin(r) + cos(r) * sin(p) * sin(y)) + face_y
|
30 |
+
x2 = size * (-cos(y) * sin(r)) + face_x
|
31 |
+
y2 = size * (cos(p) * cos(r) - sin(p) * sin(y) * sin(r)) + face_y
|
32 |
+
x3 = size * (sin(y)) + face_x
|
33 |
+
y3 = size * (-cos(y) * sin(p)) + face_y
|
34 |
+
|
35 |
+
|
36 |
+
# Draw base in red
|
37 |
+
cv2.line(img, (int(face_x), int(face_y)), (int(x1),int(y1)),(0,0,255),3)
|
38 |
+
cv2.line(img, (int(face_x), int(face_y)), (int(x2),int(y2)),(0,0,255),3)
|
39 |
+
cv2.line(img, (int(x2), int(y2)), (int(x2+x1-face_x),int(y2+y1-face_y)),(0,0,255),3)
|
40 |
+
cv2.line(img, (int(x1), int(y1)), (int(x1+x2-face_x),int(y1+y2-face_y)),(0,0,255),3)
|
41 |
+
# Draw pillars in blue
|
42 |
+
cv2.line(img, (int(face_x), int(face_y)), (int(x3),int(y3)),(255,0,0),2)
|
43 |
+
cv2.line(img, (int(x1), int(y1)), (int(x1+x3-face_x),int(y1+y3-face_y)),(255,0,0),2)
|
44 |
+
cv2.line(img, (int(x2), int(y2)), (int(x2+x3-face_x),int(y2+y3-face_y)),(255,0,0),2)
|
45 |
+
cv2.line(img, (int(x2+x1-face_x),int(y2+y1-face_y)), (int(x3+x1+x2-2*face_x),int(y3+y2+y1-2*face_y)),(255,0,0),2)
|
46 |
+
# Draw top in green
|
47 |
+
cv2.line(img, (int(x3+x1-face_x),int(y3+y1-face_y)), (int(x3+x1+x2-2*face_x),int(y3+y2+y1-2*face_y)),(0,255,0),2)
|
48 |
+
cv2.line(img, (int(x2+x3-face_x),int(y2+y3-face_y)), (int(x3+x1+x2-2*face_x),int(y3+y2+y1-2*face_y)),(0,255,0),2)
|
49 |
+
cv2.line(img, (int(x3), int(y3)), (int(x3+x1-face_x),int(y3+y1-face_y)),(0,255,0),2)
|
50 |
+
cv2.line(img, (int(x3), int(y3)), (int(x3+x2-face_x),int(y3+y2-face_y)),(0,255,0),2)
|
51 |
+
|
52 |
+
return img
|
53 |
+
|
54 |
+
def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 100):
|
55 |
+
|
56 |
+
pitch = pitch * np.pi / 180
|
57 |
+
yaw = -(yaw * np.pi / 180)
|
58 |
+
roll = roll * np.pi / 180
|
59 |
+
|
60 |
+
if tdx != None and tdy != None:
|
61 |
+
tdx = tdx
|
62 |
+
tdy = tdy
|
63 |
+
else:
|
64 |
+
height, width = img.shape[:2]
|
65 |
+
tdx = width / 2
|
66 |
+
tdy = height / 2
|
67 |
+
|
68 |
+
# X-Axis pointing to right. drawn in red
|
69 |
+
x1 = size * (cos(yaw) * cos(roll)) + tdx
|
70 |
+
y1 = size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy
|
71 |
+
|
72 |
+
# Y-Axis | drawn in green
|
73 |
+
# v
|
74 |
+
x2 = size * (-cos(yaw) * sin(roll)) + tdx
|
75 |
+
y2 = size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy
|
76 |
+
|
77 |
+
# Z-Axis (out of the screen) drawn in blue
|
78 |
+
x3 = size * (sin(yaw)) + tdx
|
79 |
+
y3 = size * (-cos(yaw) * sin(pitch)) + tdy
|
80 |
+
|
81 |
+
cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),4)
|
82 |
+
cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),4)
|
83 |
+
cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),4)
|
84 |
+
|
85 |
+
return img
|
86 |
+
|
87 |
+
|
88 |
+
def get_pose_params_from_mat(mat_path):
|
89 |
+
# This functions gets the pose parameters from the .mat
|
90 |
+
# Annotations that come with the Pose_300W_LP dataset.
|
91 |
+
mat = sio.loadmat(mat_path)
|
92 |
+
# [pitch yaw roll tdx tdy tdz scale_factor]
|
93 |
+
pre_pose_params = mat['Pose_Para'][0]
|
94 |
+
# Get [pitch, yaw, roll, tdx, tdy]
|
95 |
+
pose_params = pre_pose_params[:5]
|
96 |
+
return pose_params
|
97 |
+
|
98 |
+
def get_ypr_from_mat(mat_path):
|
99 |
+
# Get yaw, pitch, roll from .mat annotation.
|
100 |
+
# They are in radians
|
101 |
+
mat = sio.loadmat(mat_path)
|
102 |
+
# [pitch yaw roll tdx tdy tdz scale_factor]
|
103 |
+
pre_pose_params = mat['Pose_Para'][0]
|
104 |
+
# Get [pitch, yaw, roll]
|
105 |
+
pose_params = pre_pose_params[:3]
|
106 |
+
return pose_params
|
107 |
+
|
108 |
+
def get_pt2d_from_mat(mat_path):
|
109 |
+
# Get 2D landmarks
|
110 |
+
mat = sio.loadmat(mat_path)
|
111 |
+
pt2d = mat['pt2d']
|
112 |
+
return pt2d
|
113 |
+
|
114 |
+
# batch*n
|
115 |
+
def normalize_vector( v, use_gpu=True):
|
116 |
+
batch=v.shape[0]
|
117 |
+
v_mag = torch.sqrt(v.pow(2).sum(1))# batch
|
118 |
+
if use_gpu:
|
119 |
+
v_mag = torch.max(v_mag, torch.autograd.Variable(torch.FloatTensor([1e-8]).cuda()))
|
120 |
+
else:
|
121 |
+
v_mag = torch.max(v_mag, torch.autograd.Variable(torch.FloatTensor([1e-8])))
|
122 |
+
v_mag = v_mag.view(batch,1).expand(batch,v.shape[1])
|
123 |
+
v = v/v_mag
|
124 |
+
return v
|
125 |
+
|
126 |
+
# u, v batch*n
|
127 |
+
def cross_product( u, v):
|
128 |
+
batch = u.shape[0]
|
129 |
+
#print (u.shape)
|
130 |
+
#print (v.shape)
|
131 |
+
i = u[:,1]*v[:,2] - u[:,2]*v[:,1]
|
132 |
+
j = u[:,2]*v[:,0] - u[:,0]*v[:,2]
|
133 |
+
k = u[:,0]*v[:,1] - u[:,1]*v[:,0]
|
134 |
+
|
135 |
+
out = torch.cat((i.view(batch,1), j.view(batch,1), k.view(batch,1)),1)#batch*3
|
136 |
+
|
137 |
+
return out
|
138 |
+
|
139 |
+
|
140 |
+
#poses batch*6
|
141 |
+
#poses
|
142 |
+
def compute_rotation_matrix_from_ortho6d(poses, use_gpu=True):
|
143 |
+
x_raw = poses[:,0:3]#batch*3
|
144 |
+
y_raw = poses[:,3:6]#batch*3
|
145 |
+
|
146 |
+
x = normalize_vector(x_raw, use_gpu) #batch*3
|
147 |
+
z = cross_product(x,y_raw) #batch*3
|
148 |
+
z = normalize_vector(z, use_gpu)#batch*3
|
149 |
+
y = cross_product(z,x)#batch*3
|
150 |
+
|
151 |
+
x = x.view(-1,3,1)
|
152 |
+
y = y.view(-1,3,1)
|
153 |
+
z = z.view(-1,3,1)
|
154 |
+
matrix = torch.cat((x,y,z), 2) #batch*3*3
|
155 |
+
return matrix
|
156 |
+
|
157 |
+
|
158 |
+
#input batch*4*4 or batch*3*3
|
159 |
+
#output torch batch*3 x, y, z in radiant
|
160 |
+
#the rotation is in the sequence of x,y,z
|
161 |
+
def compute_euler_angles_from_rotation_matrices(rotation_matrices, use_gpu=True):
|
162 |
+
batch=rotation_matrices.shape[0]
|
163 |
+
R=rotation_matrices
|
164 |
+
sy = torch.sqrt(R[:,0,0]*R[:,0,0]+R[:,1,0]*R[:,1,0])
|
165 |
+
singular= sy<1e-6
|
166 |
+
singular=singular.float()
|
167 |
+
|
168 |
+
x=torch.atan2(R[:,2,1], R[:,2,2])
|
169 |
+
y=torch.atan2(-R[:,2,0], sy)
|
170 |
+
z=torch.atan2(R[:,1,0],R[:,0,0])
|
171 |
+
|
172 |
+
xs=torch.atan2(-R[:,1,2], R[:,1,1])
|
173 |
+
ys=torch.atan2(-R[:,2,0], sy)
|
174 |
+
zs=R[:,1,0]*0
|
175 |
+
|
176 |
+
if use_gpu:
|
177 |
+
out_euler=torch.autograd.Variable(torch.zeros(batch,3).cuda())
|
178 |
+
else:
|
179 |
+
out_euler=torch.autograd.Variable(torch.zeros(batch,3))
|
180 |
+
out_euler[:,0]=x*(1-singular)+xs*singular
|
181 |
+
out_euler[:,1]=y*(1-singular)+ys*singular
|
182 |
+
out_euler[:,2]=z*(1-singular)+zs*singular
|
183 |
+
|
184 |
+
return out_euler
|
185 |
+
|
186 |
+
|
187 |
+
def get_R(x,y,z):
|
188 |
+
''' Get rotation matrix from three rotation angles (radians). right-handed.
|
189 |
+
Args:
|
190 |
+
angles: [3,]. x, y, z angles
|
191 |
+
Returns:
|
192 |
+
R: [3, 3]. rotation matrix.
|
193 |
+
'''
|
194 |
+
# x
|
195 |
+
Rx = np.array([[1, 0, 0],
|
196 |
+
[0, np.cos(x), -np.sin(x)],
|
197 |
+
[0, np.sin(x), np.cos(x)]])
|
198 |
+
# y
|
199 |
+
Ry = np.array([[np.cos(y), 0, np.sin(y)],
|
200 |
+
[0, 1, 0],
|
201 |
+
[-np.sin(y), 0, np.cos(y)]])
|
202 |
+
# z
|
203 |
+
Rz = np.array([[np.cos(z), -np.sin(z), 0],
|
204 |
+
[np.sin(z), np.cos(z), 0],
|
205 |
+
[0, 0, 1]])
|
206 |
+
|
207 |
+
R = Rz.dot(Ry.dot(Rx))
|
208 |
+
return R
|
weights_ALFW_A0.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:46333a6f16f15a95621fbc0db8b00705c7c776172158ef7e671a55f8710ac894
|
3 |
+
size 28161179
|