-
Notifications
You must be signed in to change notification settings - Fork 30
/
mysixdrepnet.py
1393 lines (1096 loc) · 46.8 KB
/
mysixdrepnet.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import numpy as np
import cv2
import pandas as pd
from PIL import Image, ImageFilter
import torch
from torch.utils.data import Dataset
from torchvision import transforms
import torch.nn as nn
import torch
#matrices batch*3*3
#both matrix are orthogonal rotation matrices
#out theta between 0 to 180 degree batch
class GeodesicLoss(nn.Module):
def __init__(self, eps=1e-7):
super().__init__()
self.eps = eps
def forward(self, m1, m2):
m = torch.bmm(m1, m2.transpose(1,2)) #batch*3*3
cos = ( m[:,0,0] + m[:,1,1] + m[:,2,2] - 1 )/2
theta = torch.acos(torch.clamp(cos, -1+self.eps, 1-self.eps))
return torch.mean(theta)
class MySixDRepNet(nn.Module):
def __init__(self,
backbone_name, backbone_file, deploy,
pretrained=True):
super(MySixDRepNet, self).__init__()
repvgg_fn = get_RepVGG_func_by_name(backbone_name)
backbone = repvgg_fn(deploy) # Call the function to create an instance
if pretrained:
checkpoint = torch.load(backbone_file)
if 'state_dict' in checkpoint:
checkpoint = checkpoint['state_dict']
ckpt = {k.replace('module.', ''): v for k,
v in checkpoint.items()} # strip the names
backbone.load_state_dict(ckpt)
self.layer0, self.layer1, self.layer2, self.layer3, self.layer4 = backbone.stage0, backbone.stage1, backbone.stage2, backbone.stage3, backbone.stage4
self.gap = nn.AdaptiveAvgPool2d(output_size=1)
last_channel = 0
for n, m in self.layer4.named_modules():
if ('rbr_dense' in n or 'rbr_reparam' in n) and isinstance(m, nn.Conv2d):
last_channel = m.out_channels
fea_dim = last_channel
self.linear_reg = nn.Linear(fea_dim, 6)
def forward(self, x):
x = self.layer0(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.gap(x)
x = torch.flatten(x, 1)
x = self.linear_reg(x)
rotation_6d = x[:, :6]
translation = x[:, 6:]
rotation_matrix = compute_rotation_matrix_from_ortho6d(rotation_6d)
return rotation_matrix, translation
class SixDRepNet2(nn.Module):
def __init__(self, block, layers, fc_layers=1):
self.inplanes = 64
super(SixDRepNet2, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7)
self.linear_reg = nn.Linear(512*block.expansion,6)
# Vestigial layer from previous experiments
self.fc_finetune = nn.Linear(512 * block.expansion + 3, 3)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.linear_reg(x)
out = compute_rotation_matrix_from_ortho6d(x)
return out
def plot_pose_cube(img, yaw, pitch, roll, tdx=None, tdy=None, size=150.):
# Input is a cv2 image
# pose_params: (pitch, yaw, roll, tdx, tdy)
# Where (tdx, tdy) is the translation of the face.
# For pose we have [pitch yaw roll tdx tdy tdz scale_factor]
p = pitch * np.pi / 180
y = -(yaw * np.pi / 180)
r = roll * np.pi / 180
if tdx != None and tdy != None:
face_x = tdx - 0.50 * size
face_y = tdy - 0.50 * size
else:
height, width = img.shape[:2]
face_x = width / 2 - 0.5 * size
face_y = height / 2 - 0.5 * size
x1 = size * (cos(y) * cos(r)) + face_x
y1 = size * (cos(p) * sin(r) + cos(r) * sin(p) * sin(y)) + face_y
x2 = size * (-cos(y) * sin(r)) + face_x
y2 = size * (cos(p) * cos(r) - sin(p) * sin(y) * sin(r)) + face_y
x3 = size * (sin(y)) + face_x
y3 = size * (-cos(y) * sin(p)) + face_y
# Draw base in red
cv2.line(img, (int(face_x), int(face_y)), (int(x1),int(y1)),(0,0,255),3)
cv2.line(img, (int(face_x), int(face_y)), (int(x2),int(y2)),(0,0,255),3)
cv2.line(img, (int(x2), int(y2)), (int(x2+x1-face_x),int(y2+y1-face_y)),(0,0,255),3)
cv2.line(img, (int(x1), int(y1)), (int(x1+x2-face_x),int(y1+y2-face_y)),(0,0,255),3)
# Draw pillars in blue
cv2.line(img, (int(face_x), int(face_y)), (int(x3),int(y3)),(255,0,0),2)
cv2.line(img, (int(x1), int(y1)), (int(x1+x3-face_x),int(y1+y3-face_y)),(255,0,0),2)
cv2.line(img, (int(x2), int(y2)), (int(x2+x3-face_x),int(y2+y3-face_y)),(255,0,0),2)
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)
# Draw top in green
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)
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)
cv2.line(img, (int(x3), int(y3)), (int(x3+x1-face_x),int(y3+y1-face_y)),(0,255,0),2)
cv2.line(img, (int(x3), int(y3)), (int(x3+x2-face_x),int(y3+y2-face_y)),(0,255,0),2)
return img
def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size = 100):
pitch = pitch * np.pi / 180
yaw = -(yaw * np.pi / 180)
roll = roll * np.pi / 180
if tdx != None and tdy != None:
tdx = tdx
tdy = tdy
else:
height, width = img.shape[:2]
tdx = width / 2
tdy = height / 2
# X-Axis pointing to right. drawn in red
x1 = size * (cos(yaw) * cos(roll)) + tdx
y1 = size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy
# Y-Axis | drawn in green
# v
x2 = size * (-cos(yaw) * sin(roll)) + tdx
y2 = size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy
# Z-Axis (out of the screen) drawn in blue
x3 = size * (sin(yaw)) + tdx
y3 = size * (-cos(yaw) * sin(pitch)) + tdy
cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),4)
cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),4)
cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),4)
return img
def get_pose_params_from_mat(mat_path):
# This functions gets the pose parameters from the .mat
# Annotations that come with the Pose_300W_LP dataset.
mat = sio.loadmat(mat_path)
# [pitch yaw roll tdx tdy tdz scale_factor]
pre_pose_params = mat['Pose_Para'][0]
# Get [pitch, yaw, roll, tdx, tdy]
pose_params = pre_pose_params[:5]
return pose_params
def get_ypr_from_mat(mat_path):
# Get yaw, pitch, roll from .mat annotation.
# They are in radians
mat = sio.loadmat(mat_path)
# [pitch yaw roll tdx tdy tdz scale_factor]
pre_pose_params = mat['Pose_Para'][0]
# Get [pitch, yaw, roll]
pose_params = pre_pose_params[:3]
return pose_params
def get_pt2d_from_mat(mat_path):
# Get 2D landmarks
mat = sio.loadmat(mat_path)
pt2d = mat['pt2d']
return pt2d
# batch*n
def normalize_vector(v):
batch = v.shape[0]
v_mag = torch.sqrt(v.pow(2).sum(1))# batch
gpu = v_mag.get_device()
if gpu < 0:
eps = torch.autograd.Variable(torch.FloatTensor([1e-8])).to(torch.device('cpu'))
else:
eps = torch.autograd.Variable(torch.FloatTensor([1e-8])).to(torch.device('cuda:%d' % gpu))
v_mag = torch.max(v_mag, eps)
v_mag = v_mag.view(batch,1).expand(batch,v.shape[1])
v = v/v_mag
return v
# u, v batch*n
def cross_product(u, v):
batch = u.shape[0]
#print (u.shape)
#print (v.shape)
i = u[:,1]*v[:,2] - u[:,2]*v[:,1]
j = u[:,2]*v[:,0] - u[:,0]*v[:,2]
k = u[:,0]*v[:,1] - u[:,1]*v[:,0]
out = torch.cat((i.view(batch,1), j.view(batch,1), k.view(batch,1)),1) #batch*3
return out
#poses batch*6
#poses
def compute_rotation_matrix_from_ortho6d(poses):
x_raw = poses[:,0:3] #batch*3
y_raw = poses[:,3:6] #batch*3
x = normalize_vector(x_raw) #batch*3
z = cross_product(x,y_raw) #batch*3
z = normalize_vector(z) #batch*3
y = cross_product(z,x) #batch*3
x = x.view(-1,3,1)
y = y.view(-1,3,1)
z = z.view(-1,3,1)
matrix = torch.cat((x,y,z), 2) #batch*3*3
return matrix
#input batch*4*4 or batch*3*3
#output torch batch*3 x, y, z in radiant
#the rotation is in the sequence of x,y,z
def compute_euler_angles_from_rotation_matrices(rotation_matrices):
batch = rotation_matrices.shape[0]
R = rotation_matrices
sy = torch.sqrt(R[:,0,0]*R[:,0,0]+R[:,1,0]*R[:,1,0])
singular = sy<1e-6
singular = singular.float()
x = torch.atan2(R[:,2,1], R[:,2,2])
y = torch.atan2(-R[:,2,0], sy)
z = torch.atan2(R[:,1,0],R[:,0,0])
xs = torch.atan2(-R[:,1,2], R[:,1,1])
ys = torch.atan2(-R[:,2,0], sy)
zs = R[:,1,0]*0
gpu = rotation_matrices.get_device()
if gpu < 0:
out_euler = torch.autograd.Variable(torch.zeros(batch,3)).to(torch.device('cpu'))
else:
out_euler = torch.autograd.Variable(torch.zeros(batch,3)).to(torch.device('cuda:%d' % gpu))
out_euler[:,0] = x*(1-singular)+xs*singular
out_euler[:,1] = y*(1-singular)+ys*singular
out_euler[:,2] = z*(1-singular)+zs*singular
return out_euler
def get_R(x,y,z):
''' Get rotation matrix from three rotation angles (radians). right-handed.
Args:
angles: [3,]. x, y, z angles
Returns:
R: [3, 3]. rotation matrix.
'''
# x
Rx = np.array([[1, 0, 0],
[0, np.cos(x), -np.sin(x)],
[0, np.sin(x), np.cos(x)]])
# y
Ry = np.array([[np.cos(y), 0, np.sin(y)],
[0, 1, 0],
[-np.sin(y), 0, np.cos(y)]])
# z
Rz = np.array([[np.cos(z), -np.sin(z), 0],
[np.sin(z), np.cos(z), 0],
[0, 0, 1]])
R = Rz.dot(Ry.dot(Rx))
return R
def get_list_from_filenames(file_path):
# input: relative path to .txt file with file names
# output: list of relative path names
print(file_path)
with open(file_path) as f:
lines = f.read().splitlines()
return lines
class AFLW2000(Dataset):
def __init__(self, data_dir, filename_path, transform, img_ext='.jpg', annot_ext='.mat', image_mode='RGB'):
self.data_dir = data_dir
self.transform = transform
self.img_ext = img_ext
self.annot_ext = annot_ext
filename_list = get_list_from_filenames(filename_path)
self.X_train = filename_list
self.y_train = filename_list
self.image_mode = image_mode
self.length = len(filename_list)
def __getitem__(self, index):
img = Image.open(os.path.join(self.data_dir, self.X_train[index] + self.img_ext))
img = img.convert(self.image_mode)
mat_path = os.path.join(self.data_dir, self.y_train[index] + self.annot_ext)
# Crop the face loosely
pt2d = get_pt2d_from_mat(mat_path)
x_min = min(pt2d[0,:])
y_min = min(pt2d[1,:])
x_max = max(pt2d[0,:])
y_max = max(pt2d[1,:])
k = 0.20
x_min -= 2 * k * abs(x_max - x_min)
y_min -= 2 * k * abs(y_max - y_min)
x_max += 2 * k * abs(x_max - x_min)
y_max += 0.6 * k * abs(y_max - y_min)
img = img.crop((int(x_min), int(y_min), int(x_max), int(y_max)))
# We get the pose in radians
pose = get_ypr_from_mat(mat_path)
# And convert to degrees.
pitch = pose[0]# * 180 / np.pi
yaw = pose[1] #* 180 / np.pi
roll = pose[2]# * 180 / np.pi
R = get_R(pitch, yaw, roll)
labels = torch.FloatTensor([yaw, pitch, roll])
if self.transform is not None:
img = self.transform(img)
return img, torch.FloatTensor(R), labels, self.X_train[index]
def __len__(self):
# 2,000
return self.length
class AFLW(Dataset):
def __init__(self, data_dir, filename_path, transform, img_ext='.jpg', annot_ext='.txt', image_mode='RGB'):
self.data_dir = data_dir
self.transform = transform
self.img_ext = img_ext
self.annot_ext = annot_ext
filename_list = get_list_from_filenames(filename_path)
self.X_train = filename_list
self.y_train = filename_list
self.image_mode = image_mode
self.length = len(filename_list)
def __getitem__(self, index):
img = Image.open(os.path.join(self.data_dir, self.X_train[index] + self.img_ext))
img = img.convert(self.image_mode)
txt_path = os.path.join(self.data_dir, self.y_train[index] + self.annot_ext)
# We get the pose in radians
annot = open(txt_path, 'r')
line = annot.readline().split(' ')
pose = [float(line[1]), float(line[2]), float(line[3])]
# And convert to degrees.
yaw = pose[0] * 180 / np.pi
pitch = pose[1] * 180 / np.pi
roll = pose[2] * 180 / np.pi
# Fix the roll in AFLW
roll *= -1
# Bin values
bins = np.array(range(-99, 102, 3))
labels = torch.LongTensor(np.digitize([yaw, pitch, roll], bins) - 1)
cont_labels = torch.FloatTensor([yaw, pitch, roll])
if self.transform is not None:
img = self.transform(img)
return img, labels, cont_labels, self.X_train[index]
def __len__(self):
# train: 18,863
# test: 1,966
return self.length
class AFW(Dataset):
def __init__(self, data_dir, filename_path, transform, img_ext='.jpg', annot_ext='.txt', image_mode='RGB'):
self.data_dir = data_dir
self.transform = transform
self.img_ext = img_ext
self.annot_ext = annot_ext
filename_list = get_list_from_filenames(filename_path)
self.X_train = filename_list
self.y_train = filename_list
self.image_mode = image_mode
self.length = len(filename_list)
def __getitem__(self, index):
txt_path = os.path.join(self.data_dir, self.y_train[index] + self.annot_ext)
img_name = self.X_train[index].split('_')[0]
img = Image.open(os.path.join(self.data_dir, img_name + self.img_ext))
img = img.convert(self.image_mode)
txt_path = os.path.join(self.data_dir, self.y_train[index] + self.annot_ext)
# We get the pose in degrees
annot = open(txt_path, 'r')
line = annot.readline().split(' ')
yaw, pitch, roll = [float(line[1]), float(line[2]), float(line[3])]
# Crop the face loosely
k = 0.32
x1 = float(line[4])
y1 = float(line[5])
x2 = float(line[6])
y2 = float(line[7])
x1 -= 0.8 * k * abs(x2 - x1)
y1 -= 2 * k * abs(y2 - y1)
x2 += 0.8 * k * abs(x2 - x1)
y2 += 1 * k * abs(y2 - y1)
img = img.crop((int(x1), int(y1), int(x2), int(y2)))
# Bin values
bins = np.array(range(-99, 102, 3))
labels = torch.LongTensor(np.digitize([yaw, pitch, roll], bins) - 1)
cont_labels = torch.FloatTensor([yaw, pitch, roll])
if self.transform is not None:
img = self.transform(img)
return img, labels, cont_labels, self.X_train[index]
def __len__(self):
# Around 200
return self.length
class BIWI(Dataset):
def __init__(self, data_dir, filename_path, transform, image_mode='RGB', train_mode=True):
self.data_dir = data_dir
self.transform = transform
d = np.load(filename_path)
x_data = d['image']
y_data = d['pose']
self.X_train = x_data
self.y_train = y_data
self.image_mode = image_mode
self.train_mode = train_mode
self.length = len(x_data)
def __getitem__(self, index):
img = Image.fromarray(np.uint8(self.X_train[index]))
img = img.convert(self.image_mode)
roll = self.y_train[index][2]/180*np.pi
yaw = self.y_train[index][0]/180*np.pi
pitch = self.y_train[index][1]/180*np.pi
cont_labels = torch.FloatTensor([yaw, pitch, roll])
if self.train_mode:
# Flip?
rnd = np.random.random_sample()
if rnd < 0.5:
yaw = -yaw
roll = -roll
img = img.transpose(Image.FLIP_LEFT_RIGHT)
# Blur?
rnd = np.random.random_sample()
if rnd < 0.05:
img = img.filter(ImageFilter.BLUR)
R = get_R(pitch, yaw, roll)
labels = torch.FloatTensor([yaw, pitch, roll])
if self.transform is not None:
img = self.transform(img)
# Get target tensors
cont_labels = torch.FloatTensor([yaw, pitch, roll])
return img, torch.FloatTensor(R), cont_labels, self.X_train[index]
def __len__(self):
# 15,667
return self.length
class Pose_300W_LP(Dataset):
# Head pose from 300W-LP dataset
def __init__(self, data_dir, filename_path, transform, img_ext='.jpg', annot_ext='.mat', image_mode='RGB'):
self.data_dir = data_dir
self.transform = transform
self.img_ext = img_ext
self.annot_ext = annot_ext
filename_list = get_list_from_filenames(filename_path)
self.X_train = filename_list
self.y_train = filename_list
self.image_mode = image_mode
self.length = len(filename_list)
def __getitem__(self, index):
img = Image.open(os.path.join(
self.data_dir, self.X_train[index] + self.img_ext))
img = img.convert(self.image_mode)
mat_path = os.path.join(
self.data_dir, self.y_train[index] + self.annot_ext)
# Crop the face loosely
pt2d = get_pt2d_from_mat(mat_path)
x_min = min(pt2d[0, :])
y_min = min(pt2d[1, :])
x_max = max(pt2d[0, :])
y_max = max(pt2d[1, :])
# k = 0.2 to 0.40
k = np.random.random_sample() * 0.2 + 0.2
x_min -= 0.6 * k * abs(x_max - x_min)
y_min -= 2 * k * abs(y_max - y_min)
x_max += 0.6 * k * abs(x_max - x_min)
y_max += 0.6 * k * abs(y_max - y_min)
img = img.crop((int(x_min), int(y_min), int(x_max), int(y_max)))
# We get the pose in radians
pose = get_ypr_from_mat(mat_path)
# And convert to degrees.
pitch = pose[0] # * 180 / np.pi
yaw = pose[1] #* 180 / np.pi
roll = pose[2] # * 180 / np.pi
# Gray images
# Flip?
rnd = np.random.random_sample()
if rnd < 0.5:
yaw = -yaw
roll = -roll
img = img.transpose(Image.FLIP_LEFT_RIGHT)
# Blur?
rnd = np.random.random_sample()
if rnd < 0.05:
img = img.filter(ImageFilter.BLUR)
# Add gaussian noise to label
#mu, sigma = 0, 0.01
#noise = np.random.normal(mu, sigma, [3,3])
#print(noise)
# Get target tensors
R = get_R(pitch, yaw, roll)#+ noise
#labels = torch.FloatTensor([temp_l_vec, temp_b_vec, temp_f_vec])
if self.transform is not None:
img = self.transform(img)
return img, torch.FloatTensor(R),[], self.X_train[index]
def __len__(self):
# 122,450
return self.length
def getDataset(dataset, data_dir, filename_list, transformations, train_mode = True):
if dataset == 'Pose_300W_LP':
pose_dataset = Pose_300W_LP(
data_dir, filename_list, transformations)
elif dataset == 'AFLW2000':
pose_dataset = AFLW2000(
data_dir, filename_list, transformations)
elif dataset == 'BIWI':
pose_dataset = BIWI(
data_dir, filename_list, transformations, train_mode= train_mode)
elif dataset == 'AFLW':
pose_dataset = AFLW(
data_dir, filename_list, transformations)
elif dataset == 'AFW':
pose_dataset = AFW(
data_dir, filename_list, transformations)
else:
raise NameError('Error: not a valid dataset name')
return pose_dataset
import time
import math
import re
import sys
import os
import argparse
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
import math
import torch
from torch import nn
import os
import math
from math import cos, sin
import numpy as np
import torch
#from torch.serialization import load_lua
import scipy.io as sio
import cv2
## Amir Shahroudy
# https://github.com/shahroudy
import os
import sys
import argparse
import numpy as np
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(
description='Create filenames list txt file from datasets root dir.'
' For head pose analysis.')
parser.add_argument('--root_dir = ',
dest='root_dir',
help='root directory of the datasets files',
default='./datasets/300W_LP',
type=str)
parser.add_argument('--filename',
dest='filename',
help='Output filename.',
default='files.txt',
type=str)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
os.chdir(args.root_dir)
file_counter = 0
rej_counter = 0
outfile = open(args.filename, 'w')
for root, dirs, files in os.walk('.'):
for f in files:
if f[-4:] == '.jpg':
mat_path = os.path.join(root, f.replace('.jpg', '.mat'))
# We get the pose in radians
pose = get_ypr_from_mat(mat_path)
# And convert to degrees.
pitch = pose[0] * 180 / np.pi
yaw = pose[1] * 180 / np.pi
roll = pose[2] * 180 / np.pi
if abs(pitch) <= 99 and abs(yaw) <= 99 and abs(roll) <= 99:
if file_counter > 0:
outfile.write('\n')
outfile.write(root + '/' + f[:-4])
file_counter += 1
else:
rej_counter += 1
outfile.close()
print(f'{file_counter} files listed! {rej_counter} files had out-of-range'
f' values and kept out of the list!')
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__)))
"""
6DRepNet.
Accurate and unconstrained head pose estimation.
"""
__version__ = "0.1.6"
__author__ = 'Thorsten Hempel'
from math import cos, sin
import torch
from torch.hub import load_state_dict_from_url
from torchvision import transforms
import cv2
from PIL import Image
import numpy as np
class SixDRepNet_Detector():
def __init__(self, gpu_id : int=0, dict_path: str=''):
"""
Constructs the SixDRepNet instance with all necessary attributes.
Parameters
----------
gpu:id : int
gpu identifier, for selecting cpu set -1
dict_path : str
Path for local weight file. Leaving it empty will automatically download a finetuned weight file.
"""
self.gpu = gpu_id
self.model = MySixDRepNet(backbone_name='RepVGG-B1g2',
backbone_file='',
deploy=True,
pretrained=False)
# Load snapshot
if dict_path=='':
saved_state_dict = load_state_dict_from_url("https://cloud.ovgu.de/s/Q67RnLDy6JKLRWm/download/6DRepNet_300W_LP_AFLW2000.pth")
else:
saved_state_dict = torch.load(dict_path)
self.model.eval()
self.model.load_state_dict(saved_state_dict)
if self.gpu != -1:
self.model.cuda(self.gpu)
self.transformations = transforms.Compose([transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
def predict(self, img):
"""
Predicts the persons head pose and returning it in euler angles.
Parameters
----------
img : array
Face crop to be predicted
Returns
-------
pitch, yaw, roll
"""
if self.gpu != -1:
img = img.cuda(self.gpu)
rotations,translations = self.model(img)
euler = compute_euler_angles_from_rotation_matrices(rotations)*180/np.pi
# p = euler[:, 0].cpu().detach().numpy()
# y = euler[:, 1].cpu().detach().numpy()
# r = euler[:, 2].cpu().detach().numpy()
return euler,translations
def draw_axis(self, img, yaw, pitch, roll, tdx=None, tdy=None, size = 100):
"""
Prints the person's name and age.
If the argument 'additional' is passed, then it is appended after the main info.
Parameters
----------
img : array
Target image to be drawn on
yaw : int
yaw rotation
pitch: int
pitch rotation
roll: int
roll rotation
tdx : int , optional
shift on x axis
tdy : int , optional
shift on y axis
Returns
-------
img : array
"""
pitch = pitch * np.pi / 180
yaw = -(yaw * np.pi / 180)
roll = roll * np.pi / 180
if tdx != None and tdy != None:
tdx = tdx
tdy = tdy
else:
height, width = img.shape[:2]
tdx = width / 2
tdy = height / 2
# X-Axis pointing to right. drawn in red
x1 = size * (cos(yaw) * cos(roll)) + tdx
y1 = size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy
# Y-Axis | drawn in green
# v
x2 = size * (-cos(yaw) * sin(roll)) + tdx
y2 = size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy
# Z-Axis (out of the screen) drawn in blue
x3 = size * (sin(yaw)) + tdx
y3 = size * (-cos(yaw) * sin(pitch)) + tdy
cv2.line(img, (int(tdx), int(tdy)), (int(x1),int(y1)),(0,0,255),4)
cv2.line(img, (int(tdx), int(tdy)), (int(x2),int(y2)),(0,255,0),4)
cv2.line(img, (int(tdx), int(tdy)), (int(x3),int(y3)),(255,0,0),4)
return img
import time
import math
import re
import sys
import os
import argparse
import numpy as np
from numpy.lib.function_base import _quantile_unchecked
import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.backends import cudnn
from torch.utils import model_zoo
import torchvision
from torchvision import transforms
# import matplotlib
# from matplotlib import pyplot as plt
from PIL import Image
# matplotlib.use('TkAgg')
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(
description='Head pose estimation using the 6DRepNet.')
parser.add_argument(
'--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument(
'--num_epochs', dest='num_epochs',
help='Maximum number of training epochs.',
default=80, type=int)
parser.add_argument(
'--batch_size', dest='batch_size', help='Batch size.',
default=80, type=int)
parser.add_argument(
'--lr', dest='lr', help='Base learning rate.',
default=0.0001, type=float)
parser.add_argument('--scheduler', default=False, type=lambda x: (str(x).lower() == 'true'))
parser.add_argument(
'--dataset', dest='dataset', help='Dataset type.',
default='Pose_300W_LP', type=str) #Pose_300W_LP
parser.add_argument(
'--data_dir', dest='data_dir', help='Directory path for data.',
default='datasets/300W_LP', type=str)#BIWI_70_30_train.npz
parser.add_argument(
'--filename_list', dest='filename_list',
help='Path to text file containing relative paths for every example.',
default='datasets/300W_LP/files.txt', type=str) #BIWI_70_30_train.npz #300W_LP/files.txt
parser.add_argument(
'--output_string', dest='output_string',
help='String appended to output snapshots.', default='', type=str)
parser.add_argument(
'--snapshot', dest='snapshot', help='Path of model snapshot.',
default='', type=str)
args = parser.parse_args()
return args
def load_filtered_state_dict(model, snapshot):
# By user apaszke from discuss.pytorch.org
model_dict = model.state_dict()
snapshot = {k: v for k, v in snapshot.items() if k in model_dict}
model_dict.update(snapshot)
model.load_state_dict(model_dict)
if __name__ == '__main__':
args = parse_args()
cudnn.enabled = True
num_epochs = args.num_epochs
batch_size = args.batch_size
gpu = args.gpu_id
b_scheduler = args.scheduler
if not os.path.exists('output/snapshots'):
os.makedirs('output/snapshots')
summary_name = '{}_{}_bs{}'.format(
'SixDRepNet', int(time.time()), args.batch_size)
if not os.path.exists('output/snapshots/{}'.format(summary_name)):
os.makedirs('output/snapshots/{}'.format(summary_name))
model = MySixDRepNet(backbone_name='RepVGG-B1g2',
backbone_file='RepVGG-B1g2-train.pth',
deploy=False,
pretrained=True)
if not args.snapshot == '':
saved_state_dict = torch.load(args.snapshot)
model.load_state_dict(saved_state_dict['model_state_dict'])
print('Loading data.')
normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])