-
Notifications
You must be signed in to change notification settings - Fork 1
/
uti_tool.py
1251 lines (994 loc) · 37.5 KB
/
uti_tool.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
# @Time : 06/05/2021
# @Author : Wei Chen
# @Project : Pycharm
import numpy as np
import torch
import cv2
import math
import struct
import os
import random
import matplotlib.pyplot as plt
import chamfer3D.dist_chamfer_3D
# from pyTorchChamferDistance.chamfer_distance import ChamferDistance
def get_rotation(x_,y_,z_):
# print(math.cos(math.pi/2))
x=float(x_/180)*math.pi
y=float(y_/180)*math.pi
z=float(z_/180)*math.pi
R_x=np.array([[1, 0, 0 ],
[0, math.cos(x), -math.sin(x)],
[0, math.sin(x), math.cos(x)]])
R_y=np.array([[math.cos(y), 0, math.sin(y)],
[0, 1, 0],
[-math.sin(y), 0, math.cos(y)]])
R_z=np.array([[math.cos(z), -math.sin(z), 0 ],
[math.sin(z), math.cos(z), 0],
[0, 0, 1]])
return np.dot(R_z,np.dot(R_y,R_x))
def trans_3d(pc,Rt,Tt):
Tt=np.reshape(Tt,(3,1))
pcc=np.zeros((4,pc.shape[0]),dtype=np.float32)
pcc[0:3,:]=pc.T
pcc[3,:]=1
TT=np.zeros((3,4),dtype=np.float32)
TT[:,0:3]=Rt
TT[:,3]=Tt[:,0]
trans=np.dot(TT,pcc)
return trans
def rotMat_2_Euler(R):
sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])
singular = sy < 1e-6
if not singular:
x = math.atan2(R[2, 1], R[2, 2])
y = math.atan2(-R[2, 0], sy)
z = math.atan2(R[1, 0], R[0, 0])
else:
x = math.atan2(-R[1, 2], R[1, 1])
y = math.atan2(-R[2, 0], sy)
z = 0
return np.array([x/np.pi*180, y/np.pi*180, z/np.pi*180])
def data_augment(points, Rs, Ts, num_c, target_seg, log, aug_for_rot=0, aug=False, ax=5, ay=5, az=25, a=15):
centers = np.zeros((points.shape[0], 3))
corners = np.zeros((points.shape[0], 3 * num_c))
pts_recon= torch.zeros(points.shape[0], 1000, 3)
pts_noTs = points.copy()
pts0 = points.copy()
for ii in range(points.shape[0]):
# idx = idxs[ii].item()
Rt = Rs[ii].numpy().reshape(3,3)
Tt = Ts[ii].numpy().reshape(1,3)
Rt_eu=rotMat_2_Euler(Rt)
# res = np.mean(points[ii], 0)
res = np.mean(points[ii], 0)
points[ii, :, 0:3] = points[ii, :, 0:3] - np.array([res[0], res[1], res[2]])
points[ii, :, 0:3] = cv2.ppf_match_3d.addNoisePC(np.float32(points[ii, :, 0:3]), 0.1)
dx = np.random.randint(-ax, ax)
dy = np.random.randint(-ay, ay)
dz = np.random.randint(-az, az)
if aug:
points[ii, :, 0] = points[ii, :, 0] + dx
points[ii, :, 1] = points[ii, :, 1] + dy
points[ii, :, 2] = points[ii, :, 2] + dz
# Rm = get_rotation(np.random.uniform(-a, a), np.random.uniform(-a, a), np.random.uniform(-a, a))
if aug:
Rm = aug_for_rot[ii]
else:
Rm = get_rotation(0,0,0)
ang = rotMat_2_Euler(Rm)*5
print(Rt_eu,ang)
log.write('[%f,%f,%f],[%f,%f,%f]\n'%(Rt_eu[0],Rt_eu[1],Rt_eu[2],ang[0],ang[1],ang[2]))
Rm = get_rotation(ang[0],ang[1],ang[2])
points[ii, :, 0:3] = np.dot(Rm, points[ii, :, 0:3].T).T
if target_seg[0].sum().item()<1:
print('target_seg.numpy()[ii, :] == 1)[0].sum()',(target_seg.numpy()[ii, :] ==1)[0].sum())
pts_seg = pts0[ii, np.where(target_seg.numpy()[ii, :] == 1)[0], 0:3]
centers[ii,:]=Tt-np.mean(pts_seg,0)
Tt_c = np.array([0, 0, 0]).T
corners_ = np.array([[0,0,0],[0,200, 0],[200, 0, 0]])
pts_rec = pts_seg - Tt
choice = np.random.choice(len(pts_rec), 1000, replace=True)
pts_rec = pts_rec[choice, :]
pts_recon[ii, :] = torch.Tensor(np.dot(Rm, pts_rec.T).T)
pts_nT = pts_noTs[ii, :] - Tt
pts_noTs[ii, :] = np.dot(Rm, pts_nT.T).T
# corners_=kps2
corners[ii, :] = (trans_3d(corners_, np.dot(Rm, Rt), Tt_c).T).flatten()
return points,corners, centers, pts_recon
def load_ply(path):
"""
Loads a 3D mesh model from a PLY file.
:param path: A path to a PLY file.
:return: The loaded model given by a dictionary with items:
'pts' (nx3 ndarray), 'normals' (nx3 ndarray), 'colors' (nx3 ndarray),
'faces' (mx3 ndarray) - the latter three are optional.
"""
f = open(path, 'r')
n_pts = 0
n_faces = 0
face_n_corners = 3 # Only triangular faces are supported
pt_props = []
face_props = []
text_props = []
is_binary = False
header_vertex_section = False
header_face_section = False
# Read header
while True:
line = f.readline().rstrip('\n').rstrip('\r') # Strip the newline character(s)
if line.startswith('element vertex'):
n_pts = int(line.split(' ')[-1])
header_vertex_section = True
header_face_section = False
elif line.startswith('element face'):
n_faces = int(line.split(' ')[-1])
header_vertex_section = False
header_face_section = True
elif line.startswith('element'): # Some other element
header_vertex_section = False
header_face_section = False
elif line.startswith('property') and header_vertex_section:
# (name of the property, data type)
pt_props.append((line.split(' ')[-1], line.split(' ')[-2]))
elif line.startswith('property list') and header_face_section:
elems = line.split(' ')
# (name of the property, data type)
if elems[-1] == 'vertex_indices' or elems[-1] == 'vertex_index':
# (name of the property, data type)
face_props.append(('n_corners', elems[2]))
for i in range(face_n_corners):
face_props.append(('ind_' + str(i), elems[3]))
elif elems[-1] == 'texcoord':
# (name of the property, data type)
face_props.append(('texcoord', elems[2]))
for i in range(face_n_corners * 2):
face_props.append(('texcoord_ind_' + str(i), elems[3]))
elif line.startswith('property2 list') and header_face_section:
elems = line.split(' ')
# (name of the property, data type)
text_props.append(('n_corners', elems[2]))
for i in range(3):
text_props.append(('ind_' + str(i), elems[3]))
elif line.startswith('format'):
if 'binary' in line:
is_binary = True
elif line.startswith('end_header'):
break
# Prepare data structures
model = {}
model['pts'] = np.zeros((n_pts, 3), np.float)
if n_faces > 0:
model['faces'] = np.zeros((n_faces, face_n_corners), np.float)
pt_props_names = [p[0] for p in pt_props]
is_normal = False
if {'nx', 'ny', 'nz'}.issubset(set(pt_props_names)):
is_normal = True
model['normals'] = np.zeros((n_pts, 3), np.float)
is_color = False
if {'red', 'green', 'blue'}.issubset(set(pt_props_names)):
is_color = True
model['colors'] = np.zeros((n_pts, 3), np.float)
formats = { # For binary format
'float': ('f', 4),
'double': ('d', 8),
'int': ('i', 4),
'uchar': ('B', 1)
}
# Load vertices
for pt_id in range(n_pts):
prop_vals = {}
load_props = ['x', 'y', 'z', 'nx', 'ny', 'nz', 'red', 'green', 'blue']
if is_binary:
for prop in pt_props:
format = formats[prop[1]]
val = struct.unpack(format[0], f.read(format[1]))[0]
if prop[0] in load_props:
prop_vals[prop[0]] = val
else:
elems = f.readline().rstrip('\n').rstrip('\r').split(' ')
for prop_id, prop in enumerate(pt_props):
if prop[0] in load_props:
prop_vals[prop[0]] = elems[prop_id]
model['pts'][pt_id, 0] = float(prop_vals['x'])
model['pts'][pt_id, 1] = float(prop_vals['y'])
model['pts'][pt_id, 2] = float(prop_vals['z'])
if is_normal:
model['normals'][pt_id, 0] = float(prop_vals['nx'])
model['normals'][pt_id, 1] = float(prop_vals['ny'])
model['normals'][pt_id, 2] = float(prop_vals['nz'])
if is_color:
model['colors'][pt_id, 0] = float(prop_vals['red'])
model['colors'][pt_id, 1] = float(prop_vals['green'])
model['colors'][pt_id, 2] = float(prop_vals['blue'])
# Load faces
for face_id in range(n_faces):
prop_vals = {}
if is_binary:
for prop in face_props:
format = formats[prop[1]]
val = struct.unpack(format[0], f.read(format[1]))[0]
if prop[0] == 'n_corners':
if val != face_n_corners:
print ('Error: Only triangular faces are supported.')
print ('Number of face corners:', val)
exit(-1)
else:
prop_vals[prop[0]] = val
else:
elems = f.readline().rstrip('\n').rstrip('\r').split(' ')
for prop_id, prop in enumerate(face_props):
if prop[0] == 'n_corners':
if int(elems[prop_id]) != face_n_corners:
print ('Error: Only triangular faces are supported.')
print ('Number of face corners:', int(elems[prop_id]))
exit(-1)
else:
prop_vals[prop[0]] = elems[prop_id]
#print(prop_vals.keys())
model['faces'][face_id, 0] = int(prop_vals['ind_0'])
model['faces'][face_id, 1] = int(prop_vals['ind_1'])
model['faces'][face_id, 2] = int(prop_vals['ind_2'])
f.close()
return model
def get_3d_bbox(size, shift=0):
"""
Args:
size: [3] or scalar
shift: [3] or scalar
Returns:
bbox_3d: [3, N]
"""
bbox_3d = np.array([[+size[0] / 2, +size[1] / 2, +size[2] / 2],
[+size[0] / 2, +size[1] / 2, -size[2] / 2],
[-size[0] / 2, +size[1] / 2, +size[2] / 2],
[-size[0] / 2, +size[1] / 2, -size[2] / 2],
[+size[0] / 2, -size[1] / 2, +size[2] / 2],
[+size[0] / 2, -size[1] / 2, -size[2] / 2],
[-size[0] / 2, -size[1] / 2, +size[2] / 2],
[-size[0] / 2, -size[1] / 2, -size[2] / 2]]) + shift
bbox_3d = bbox_3d.transpose()
return bbox_3d
def transform_coordinates_3d(coordinates, sRT):
"""
Args:
coordinates: [3, N]
sRT: [4, 4]
Returns:
new_coordinates: [3, N]
"""
assert coordinates.shape[0] == 3
coordinates = np.vstack([coordinates, np.ones((1, coordinates.shape[1]), dtype=np.float32)])
new_coordinates = sRT @ coordinates
new_coordinates = new_coordinates[:3, :] / new_coordinates[3, :]
return new_coordinates
def compute_3d_IoU(sRT_1, sRT_2, size_1, size_2, class_name_1, class_name_2, handle_visibility):
'''
Args:
sRT_1: 4x4
sRT_2: 4x4
size_1: 3x8
size_2: 3
class_name_1: str
class_name_2: str
handle_visibility: bool
Returns:
'''
""" Computes IoU overlaps between two 3D bboxes. """
def asymmetric_3d_iou(sRT_1, sRT_2, size_1, size_2):
noc_cube_1 = get_3d_bbox(size_1, 0)
bbox_3d_1 = transform_coordinates_3d(noc_cube_1, sRT_1)
noc_cube_2 = get_3d_bbox(size_2, 0)
bbox_3d_2 = transform_coordinates_3d(noc_cube_2, sRT_2)
bbox_1_max = np.amax(bbox_3d_1, axis=0)
bbox_1_min = np.amin(bbox_3d_1, axis=0)
bbox_2_max = np.amax(bbox_3d_2, axis=0)
bbox_2_min = np.amin(bbox_3d_2, axis=0)
overlap_min = np.maximum(bbox_1_min, bbox_2_min)
overlap_max = np.minimum(bbox_1_max, bbox_2_max)
# intersections and union
if np.amin(overlap_max - overlap_min) < 0:
intersections = 0
else:
intersections = np.prod(overlap_max - overlap_min)
union = np.prod(bbox_1_max - bbox_1_min) + np.prod(bbox_2_max - bbox_2_min) - intersections
overlaps = intersections / union
return overlaps
if sRT_1 is None or sRT_2 is None:
return -1
if (class_name_1 in ['bottle', 'bowl', 'can'] and class_name_1 == class_name_2) or (class_name_1 == 'mug' and class_name_1 == class_name_2 and handle_visibility==0):
def y_rotation_matrix(theta):
return np.array([[ np.cos(theta), 0, np.sin(theta), 0],
[ 0, 1, 0, 0],
[-np.sin(theta), 0, np.cos(theta), 0],
[ 0, 0, 0, 1]])
n = 20
max_iou = 0
for i in range(n):
rotated_RT_1 = sRT_1 @ y_rotation_matrix(2 * math.pi * i / float(n))
max_iou = max(max_iou, asymmetric_3d_iou(rotated_RT_1, sRT_2, size_1, size_2))
else:
max_iou = asymmetric_3d_iou(sRT_1, sRT_2, size_1, size_2)
return max_iou
def get_change_3D(x_r,y_r,z_r):
ext1=np.array([0,x_r,y_r,z_r])
or1=np.array([-ext1[1]/2,-ext1[2]/2,ext1[3]/2])
or2=np.array([ext1[1]/2,-ext1[2]/2,ext1[3]/2])
or3=np.array([ext1[1]/2,ext1[2]/2,ext1[3]/2])
or4=np.array([-ext1[1]/2,ext1[2]/2,ext1[3]/2])
or5=np.array([-ext1[1]/2,-ext1[2]/2,-ext1[3]/2])
or6=np.array([ext1[1]/2,-ext1[2]/2,-ext1[3]/2])
or7=np.array([ext1[1]/2,ext1[2]/2,-ext1[3]/2])
or8=np.array([-ext1[1]/2,ext1[2]/2,-ext1[3]/2])
OR=np.array([or1,or2,or3,or4,or5,or6,or7,or8])
return OR
def get_3D_corner(pc):
# pc=move_2_C(pc)
x_r=max(pc[:,0])-min(pc[:,0])
y_r=max(pc[:,1])-min(pc[:,1])
z_r=max(pc[:,2])-min(pc[:,2])
# print(max(pc[:,0]))
# pdb.set_trace()
ext1=np.array([0,x_r,y_r,z_r])
or1=np.array([-ext1[1]/2,-ext1[2]/2,ext1[3]/2])
or2=np.array([ext1[1]/2,-ext1[2]/2,ext1[3]/2])
or3=np.array([ext1[1]/2,ext1[2]/2,ext1[3]/2])
or4=np.array([-ext1[1]/2,ext1[2]/2,ext1[3]/2])
or5=np.array([-ext1[1]/2,-ext1[2]/2,-ext1[3]/2])
or6=np.array([ext1[1]/2,-ext1[2]/2,-ext1[3]/2])
or7=np.array([ext1[1]/2,ext1[2]/2,-ext1[3]/2])
or8=np.array([-ext1[1]/2,ext1[2]/2,-ext1[3]/2])
OR=np.array([or1,or2,or3,or4,or5,or6,or7,or8])
return OR, x_r,y_r,z_r
def draw_cors_withsize(img_,K,R_,T_,color,xr,yr,zr, lindwidth=2):
T_=T_.reshape((3,1))
img=np.zeros(img_.shape)
np.copyto(img,img_)
R=R_
OR=get_change_3D(xr,yr,zr)
OR_temp=OR
OR[:,0]=OR_temp[:,0]
OR[:,1]=OR_temp[:,1]
OR[:,2]=OR_temp[:,2]
pcc=np.zeros((4,len(OR)),dtype='float32')
pcc[0:3,:]=OR.T
pcc[3,:]=1
TT=np.zeros((3,4),dtype='float32')
TT[:,0:3]=R
TT[:,3]=T_[:,0]
camMat=K
pc_t = np.dot(TT, pcc) # 3xN
pc_tt = np.dot(camMat, pc_t)
pc_t=np.transpose(pc_tt)
x=pc_t[:,0]/pc_t[:,2]
y=pc_t[:,1]/pc_t[:,2]
cv2.line(img, (np.int(x[0]),np.int(y[0])), (np.int(x[1]), np.int(y[1])), color, lindwidth)
cv2.line(img, (np.int(x[1]),np.int(y[1])), (np.int(x[2]), np.int(y[2])), color, lindwidth)
cv2.line(img, (np.int(x[2]),np.int(y[2])), (np.int(x[3]), np.int(y[3])), color, lindwidth)
cv2.line(img, (np.int(x[3]),np.int(y[3])), (np.int(x[0]), np.int(y[0])), color, lindwidth)
cv2.line(img, (np.int(x[0]),np.int(y[0])), (np.int(x[4]), np.int(y[4])), color, lindwidth)
cv2.line(img, (np.int(x[1]),np.int(y[1])), (np.int(x[5]), np.int(y[5])), color, lindwidth)
cv2.line(img, (np.int(x[2]),np.int(y[2])), (np.int(x[6]), np.int(y[6])), color, lindwidth)
cv2.line(img, (np.int(x[3]),np.int(y[3])), (np.int(x[7]), np.int(y[7])), color, lindwidth)
cv2.line(img, (np.int(x[4]),np.int(y[4])), (np.int(x[5]), np.int(y[5])), color, lindwidth)
cv2.line(img, (np.int(x[5]),np.int(y[5])), (np.int(x[6]), np.int(y[6])), color, lindwidth)
cv2.line(img, (np.int(x[6]),np.int(y[6])), (np.int(x[7]), np.int(y[7])), color, lindwidth)
cv2.line(img, (np.int(x[7]),np.int(y[7])), (np.int(x[4]), np.int(y[4])), color, lindwidth)
return img
def move_2_C(pc):
x_c=(max(pc[:,0])+min(pc[:,0]))/2
y_c=(max(pc[:,1])+min(pc[:,1]))/2
z_c=(max(pc[:,2])+min(pc[:,2]))/2
pc_t=pc
pc[:,0]=pc_t[:,0]-x_c
pc[:,1]=pc_t[:,1]-y_c
pc[:,2]=pc_t[:,2]-z_c
return pc
def draw_cors(img_,pc,K,R_,T_,color, lindwidth=2):
pc = move_2_C(pc)
T_=T_.reshape((3,1))
img=np.zeros(img_.shape)
np.copyto(img,img_)
R=R_
# R_m=get_rotation(0,0,-90)
R_m=get_rotation(0,0,0)
# print(R_m)
R=np.dot(R,R_m)
# pc_temp=pc
# pc[:,0]=pc_temp[:,0]
# pc[:,1]=pc_temp[:,1]
#print(pc.shape)
OR1,xr,yr,zr=get_3D_corner(pc)
# xr, yr, zr = xr*1.2,yr*0.8,zr*0.8 # deform
#print(xr,yr,zr)
#dfd
OR=get_change_3D(xr,yr,zr)
OR_temp=OR
OR[:,0]=OR_temp[:,0]
OR[:,1]=OR_temp[:,1]
OR[:,2]=OR_temp[:,2]
# OR[:,0]=OR_temp[:,0]
# OR[:,1]=OR_temp[:,1]
# OR[:,2]=OR_temp[:,2]
pcc=np.zeros((4,len(OR)),dtype='float32')
pcc[0:3,:]=OR.T
pcc[3,:]=1
TT=np.zeros((3,4),dtype='float32')
TT[:,0:3]=R
TT[:,3]=T_[:,0]
#print('s: ',TT)
# etrs
#aa=TT*pcc
#print(aa.shape)
camMat=K
#pdb.set_trace()
pc_tt=np.dot(camMat,np.dot(TT,pcc))
pc_t=np.transpose(pc_tt)
x=pc_t[:,0]/pc_t[:,2]
y=pc_t[:,1]/pc_t[:,2]
cv2.line(img, (np.int(x[0]),np.int(y[0])), (np.int(x[1]), np.int(y[1])), color, lindwidth)
cv2.line(img, (np.int(x[1]),np.int(y[1])), (np.int(x[2]), np.int(y[2])), color, lindwidth)
cv2.line(img, (np.int(x[2]),np.int(y[2])), (np.int(x[3]), np.int(y[3])), color, lindwidth)
cv2.line(img, (np.int(x[3]),np.int(y[3])), (np.int(x[0]), np.int(y[0])), color, lindwidth)
cv2.line(img, (np.int(x[0]),np.int(y[0])), (np.int(x[4]), np.int(y[4])), color, lindwidth)
cv2.line(img, (np.int(x[1]),np.int(y[1])), (np.int(x[5]), np.int(y[5])), color, lindwidth)
cv2.line(img, (np.int(x[2]),np.int(y[2])), (np.int(x[6]), np.int(y[6])), color, lindwidth)
cv2.line(img, (np.int(x[3]),np.int(y[3])), (np.int(x[7]), np.int(y[7])), color, lindwidth)
cv2.line(img, (np.int(x[4]),np.int(y[4])), (np.int(x[5]), np.int(y[5])), color, lindwidth)
cv2.line(img, (np.int(x[5]),np.int(y[5])), (np.int(x[6]), np.int(y[6])), color, lindwidth)
cv2.line(img, (np.int(x[6]),np.int(y[6])), (np.int(x[7]), np.int(y[7])), color, lindwidth)
cv2.line(img, (np.int(x[7]),np.int(y[7])), (np.int(x[4]), np.int(y[4])), color, lindwidth)
# plt.imshow(img)
# plt.plot([x[0],x[1]],[y[0],y[1]],marker = 'o',color='red')
# plt.plot([x[1],x[2]],[y[1],y[2]],marker = 'o',color='red')
# plt.plot([x[2],x[3]],[y[2],y[3]],marker = 'o',color='red')
# plt.plot([x[3],x[0]],[y[3],y[0]],marker = 'o',color='red')
#
# plt.plot([x[0],x[4]],[y[0],y[4]],marker = 'o',color='red')
# plt.plot([x[1],x[5]],[y[1],y[5]],marker = 'o',color='red')
# plt.plot([x[2],x[6]],[y[2],y[6]],marker = 'o',color='red')
# plt.plot([x[3],x[7]],[y[3],y[7]],marker = 'o',color='red')
#
# plt.plot([x[4],x[5]],[y[4],y[5]],marker = 'o',color='red')
# plt.plot([x[5],x[6]],[y[5],y[6]],marker = 'o',color='red')
# plt.plot([x[6],x[7]],[y[6],y[7]],marker = 'o',color='red')
# plt.plot([x[7],x[4]],[y[7],y[4]],marker = 'o',color='red')
return img
def kabsch(P, Q):
"""
Using the Kabsch algorithm with two sets of paired point P and Q, centered
around the centroid. Each vector set is represented as an NxD
matrix, where D is the the dimension of the space.
The algorithm works in three steps:
- a centroid translation of P and Q (assumed done before this function
call)
- the computation of a covariance matrix C
- computation of the optimal rotation matrix U
For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm
Parameters
----------
P : array
(N,D) matrix, where N is points and D is dimension.
Q : array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
U : matrix
Rotation matrix (D,D)
"""
# Computation of the covariance matrix
#print(P.shape,Q.shape)
# print(np.mean(P,0))
# P= P-np.mean(P,0)
# Q =Q - np.mean(Q, 0)
# print(P)
# tests
C = np.dot(P.T, Q)
# Computation of the optimal rotation matrix
# This can be done using singular value decomposition (SVD)
# Getting the sign of the det(V)*(W) to decide
# whether we need to correct our rotation matrix to ensure a
# right-handed coordinate system.
# And finally calculating the optimal rotation matrix U
# see http://en.wikipedia.org/wiki/Kabsch_algorithm
U, S, V = np.linalg.svd(C)
#S=np.diag(S)
#print(C)
# print(S)
#print(np.dot(U,np.dot(S,V)))
d = (np.linalg.det(V.T) * np.linalg.det(U.T)) <0.0
# d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0
# E = np.diag(np.array([1, 1, 1]))
# if d:
# S[-1] = -S[-1]
# V[:, -1] = -V[:, -1]
E = np.diag(np.array([1, 1, (np.linalg.det(V.T) * np.linalg.det(U.T))]))
# print(E)
# Create Rotation matrix U
#print(V)
#print(U)
R = np.dot(V.T ,np.dot(E,U.T))
return R
def gettrans(kps,h):
# print(kps.shape) ##N*3
# print(h.shape)##N,100,3
# tess
hss=[]
# print(h)
# print(kps.shape) ##3*N
# kps
# print(kps.shape)
# tess
kps=kps.reshape(-1,3)
for i in range(h.shape[1]):
# print(i)
# print(h[:,i,:].shape #N*3
# tss
P = kps.T - kps.T.mean(1).reshape((3, 1))
#
Q= h[:,i,:].T - h[:,i,:].T.mean(1).reshape((3,1))
# print(P.shape,Q.shape)
# print(kps,h[:,i,:])
# tess
# print(P.T,Q.T)
R=kabsch(P.T,Q.T) ##N*3, N*3
T=h[:,i,:]-np.dot(R,kps.T).T
# print(np.mean(T,0))
# tess
# print(T.shape)
hh = np.zeros((3, 4), dtype=np.float32)
hh[0:3,0:3]=R
hh[0:3,3]=np.mean(T,0)
# print(R)
hss.append(hh)
# print(hh)
# if i==3:
# tess
# print(hss)
return hss
def compute_RT_degree_cm_symmetry(RT_1, RT_2, class_id,hv=0):
R1 = RT_1
R2 = RT_2
# try:
# assert np.abs(np.linalg.det(R1) - 1) < 0.01
# assert np.abs(np.linalg.det(R2) - 1) < 0.01
# except AssertionError:
# print(np.linalg.det(R1), np.linalg.det(R2))
if class_id in ['bottle', 'can', 'bowl']: ## symmetric when rotating around y-axis
y = np.array([0, 1, 0])
y1 = R1 @ y
y2 = R2 @ y
theta = np.arccos(y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2)))
elif class_id == 'mug' and hv==0: ## symmetric when rotating around y-axis
y = np.array([0, 1, 0])
y1 = R1 @ y
y2 = R2 @ y
theta = np.arccos(y1.dot(y2) / (np.linalg.norm(y1) * np.linalg.norm(y2)))
elif class_id in ['phone', 'eggbox', 'glue']:
y_180_RT = np.diag([-1.0, 1.0, -1.0])
R = R1 @ R2.transpose()
R_rot = R1 @ y_180_RT @ R2.transpose()
theta = min(np.arccos((np.trace(R) - 1) / 2),
np.arccos((np.trace(R_rot) - 1) / 2))
else:
R = R1 @ R2.transpose()
theta = np.arccos((np.trace(R) - 1) / 2)
theta *= 180 / np.pi
# shift = np.linalg.norm(T1 - T2) * 100
result = theta
return result
def calcAngularDistance(Rt, R):
#print(np.transpose(Rt))
#t1=np.ones((3,3))
rotDiff = np.dot(Rt.T, R/np.linalg.det(R))
#print(rotDiff)
trace = np.trace(rotDiff)
#print(np.arccos(1)/math.pi)
trace2 = np.min([float(3.0000), np.max([float(-1.0000), float(trace)])])
#print((float(trace2) - 1.0) / 2.0)
#pdb.set_trace()
return float(180 * np.arccos((float(trace2) - 1.0) / 2.0) / math.pi)
def get6dpose1(Rt,Tt, R, T, sy=0,class_id='',hv=0):
if sy==1:
R_loss = compute_RT_degree_cm_symmetry(Rt, R,class_id,hv)
else:
R_loss=calcAngularDistance(Rt, R)
Tt = Tt.reshape(3,1)
T = T.reshape(3,1)
t_loss=cv2.norm(Tt-T,normType=cv2.NORM_L2) # loss
#print(cv2.norm(Tt-T))
#print(np.linalg.norm(Tt-T))
#pdb.set_trace()
return R_loss, t_loss
def getFiles_cate(file_dir,suf,a,b, sort=1):
L=[]
for root, dirs, files in os.walk(file_dir):
#print('root: ',dirs)
for file in files:
if os.path.splitext(file)[0][4:] == suf:
L.append(os.path.join(root, file))
if sort==1:
L.sort(key=lambda x: int(x[b-len(suf)-a:b-len(suf)]))#0000.png
return L
def getFiles_ab_cate(file_dir,suf,a,b, sort=1):
L=[]
for root, dirs, files in os.walk(file_dir):
#print('root: ',dirs)
for file in files:
if file.split('_')[1]== suf:
#print(os.path.join(root, file))
#sdf
L.append(os.path.join(root, file))
# L.sort(key=lambda x:int(x[-9:-4])) # 0000
if sort==1:
L.sort(key=lambda x: int(x.split('/')[-1].split('_')[0]))#0000.png
return L
def depth_2_pc(depth, K, bbx=[1, 2, 3, 4], step=1):
x1 = bbx[0]
x2 = bbx[1]
y1 = bbx[2]
y2 = bbx[3]
fx = K[0, 0]
ux = K[0, 2]
fy = K[1, 1]
uy = K[1, 2]
W = y2 - y1 + 1
H = x2 - x1 + 1
xw0 = np.arange(y1, y2, step)
xw0 = np.expand_dims(xw0, axis=0)
xw0 = np.tile(xw0.T, 2)
uu0 = np.zeros_like(xw0, dtype=np.float32)
uu0[:, 0] = ux
uu0[:, 1] = uy
mesh = np.zeros((len(range(0, H, step)) * xw0.shape[0], 3))
c = 0
for i in range(x1, x2, step):
xw = xw0.copy()
uu = uu0.copy()
xw[:, 0] = i ### W 2
z = depth[xw[:, 0], xw[:, 1]] ##W 1
xw[:, 0] = xw[:, 0] * z
xw[:, 1] = xw[:, 1] * z
uu[:, 0] = uu[:, 0] * z
uu[:, 1] = uu[:, 1] * z
X = (xw[:, 1] - uu[:, 0]) / fx
Y = (xw[:, 0] - uu[:, 1]) / fy
mesh[xw.shape[0] * c:xw.shape[0] * (c + 1), 0] = X
mesh[xw.shape[0] * c:xw.shape[0] * (c + 1), 1] = Y
mesh[xw.shape[0] * c:xw.shape[0] * (c + 1), 2] = z
c += 1
return mesh
def depth_2_pc_seg(depth, K, bbx, seg, step=1):
x1 = bbx[0]
x2 = bbx[1]
y1 = bbx[2]
y2 = bbx[3]
# dep = np.concatenate((dep, seg), axis=1)
dep = np.zeros()
fx = K[0, 0]
ux = K[0, 2]
fy = K[1, 1]
uy = K[1, 2]
W = y2 - y1 + 1
H = x2 - x1 + 1
xw0 = np.arange(y1, y2, step)
xw0 = np.expand_dims(xw0, axis=0)
xw0 = np.tile(xw0.T, 2)
uu0 = np.zeros_like(xw0, dtype=np.float32)
uu0[:, 0] = ux
uu0[:, 1] = uy
mesh = np.zeros((len(range(0, H, step)) * xw0.shape[0], 3))
c = 0
for i in range(x1, x2, step):
xw = xw0.copy()
uu = uu0.copy()
xw[:, 0] = i ### W 2
z = depth[xw[:, 0], xw[:, 1]] ##W 1
xw[:, 0] = xw[:, 0] * z
xw[:, 1] = xw[:, 1] * z
uu[:, 0] = uu[:, 0] * z
uu[:, 1] = uu[:, 1] * z
X = (xw[:, 1] - uu[:, 0]) / fx
Y = (xw[:, 0] - uu[:, 1]) / fy
mesh[xw.shape[0] * c:xw.shape[0] * (c + 1), 0] = X
mesh[xw.shape[0] * c:xw.shape[0] * (c + 1), 1] = Y
mesh[xw.shape[0] * c:xw.shape[0] * (c + 1), 2] = z
c += 1
return mesh
def depth_2_mesh_bbx(depth,bbx,K, step=1, enl=0):
#bbx: r1,r2, c1,c2
x1 = int(max(bbx[0],0))-enl
x2 = int(min(bbx[1],depth.shape[0]))+enl
y1 = int(max(bbx[2],0))-enl
y2 = int(min(bbx[3],depth.shape[1]))+enl
mesh = depth_2_pc(depth, K, bbx = [x1,x2,y1,y2], step=step)
return mesh
def depth_2_mesh_all(depth,K):
#dep=np.logical_and(depth[:,:],depth[:,:])
r,c=np.where(depth>0)
r1 = r.min()
r2 = r.max()
c1 = c.min()
c2 = c.max()
mesh=depth_2_mesh_bbx(depth, [r1,r2,c1,c2], K, step=1, enl=0)
return mesh
def getFiles_ab(file_dir,suf,a,b):
L=[]
for root, dirs, files in os.walk(file_dir):
#print('root: ',dirs)
for file in files:
if os.path.splitext(file)[1] == suf:
#print(os.path.join(root, file))
#sdf
L.append(os.path.join(root, file))
# L.sort(key=lambda x:int(x[-9:-4])) # 0000
L.sort(key=lambda x: int(x[a:b]))#0000.png
return L
def shake_bbx(bbx, degrees=(0, 0), translate=(0.1, 0.1), scale=(0.9, 1.2), shear=(0, 0),W=640,H=480):
#### bbx: x1,x2,y1,y2
# random.seed(1092)
# print(random.random())
bw = bbx[1]-bbx[0]
cx = bbx[0]+bw//2
bh = bbx[3]-bbx[2]
cy = bbx[2]+bh//2
targets = np.array([bbx[0], bbx[2], bbx[1], bbx[3]])
a = random.random() * (degrees[1] - degrees[0]) + degrees[0]
s = random.random() * (scale[1] - scale[0]) + scale[0]
R = np.eye(3)
# R[:2] = cv2.getRotationMatrix2D(angle=a, center=(W / 2, H / 2), scale=s)
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(int(cx), int(cy)), scale=s)
# Translation
T = np.eye(3)
T[0, 2] = (random.random() * 2 - 1) * translate[0] * bw # x translation (pixels)
T[1, 2] = (random.random() * 2 - 1) * translate[1] * bh # y translation (pixels)
# T[0, 2] = translate[0] * bw # x translation (pixels)
# T[1, 2] = translate[1] * bh # y translation (pixels)
# Shear
S = np.eye(3)
S[0, 1] = math.tan((random.random() * (shear[1] - shear[0]) + shear[0]) * math.pi / 180) # x shear (deg)
S[1, 0] = math.tan((random.random() * (shear[1] - shear[0]) + shear[0]) * math.pi / 180) # y shear (deg)
M = S @ T @ R # Combined rotation matrix. ORDER IS IMPORTANT HERE!!
# M = np.eye(3)
# if len(targets) > 0:
n = 1
points = targets.copy().reshape(1,4)
# print(random.random())
# warp points
xy = np.ones((n * 4, 3))
xy[:, :2] = points[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
xy = (xy @ M.T)[:, :2].reshape(n, 8)
# create new boxes
x = xy[:, [0, 2, 4, 6]]
y = xy[:, [1, 3, 5, 7]]
xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
# apply angle-based reduction of bounding boxes
radians = a * math.pi / 180
reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5
x = (xy[:, 2] + xy[:, 0]) / 2
y = (xy[:, 3] + xy[:, 1]) / 2
w = (xy[:, 2] - xy[:, 0]) * reduction
h = (xy[:, 3] - xy[:, 1]) * reduction
xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T
# reject warped points outside of image
x1 = int(np.clip(xy[0][0], 0, W))
x2 = int(np.clip(xy[0][2], 0, W))
y1 = int(np.clip(xy[0][1], 0, H))
y2 = int(np.clip(xy[0][3], 0, H))
return np.array([x1, x2,y1, y2])
def depth_out_iou(depth, box1_yolo, box2_gt, z=0):
ioubb = get_bbxs_iou(box1_yolo, box2_gt)
if z == 0:
depth[ioubb[2]:ioubb[3], ioubb[0]:ioubb[1]] = 0
return depth, ioubb