-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathcameras.py
1660 lines (1326 loc) · 59.6 KB
/
cameras.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 cv2
import numpy as np
from copy import copy
from scipy.sparse import lil_matrix, dok_matrix
from scipy import optimize
from scipy import signal
from numba import jit
from collections import defaultdict, Counter
import toml
import itertools
from tqdm import trange
from pprint import pprint
import time
from .boards import merge_rows, extract_points, \
extract_rtvecs, get_video_params
from .utils import get_initial_extrinsics, make_M, get_rtvec, \
get_connections
@jit(nopython=True, parallel=True)
def triangulate_simple(points, camera_mats):
num_cams = len(camera_mats)
A = np.zeros((num_cams * 2, 4))
for i in range(num_cams):
x, y = points[i]
mat = camera_mats[i]
A[(i * 2):(i * 2 + 1)] = x * mat[2] - mat[0]
A[(i * 2 + 1):(i * 2 + 2)] = y * mat[2] - mat[1]
u, s, vh = np.linalg.svd(A, full_matrices=True)
p3d = vh[-1]
p3d = p3d[:3] / p3d[3]
return p3d
def get_error_dict(errors_full, min_points=10):
n_cams = errors_full.shape[0]
errors_norm = np.linalg.norm(errors_full, axis=2)
good = ~np.isnan(errors_full[:, :, 0])
error_dict = dict()
for i in range(n_cams):
for j in range(i+1, n_cams):
subset = good[i] & good[j]
err_subset = errors_norm[:, subset][[i, j]]
err_subset_mean = np.mean(err_subset, axis=0)
if np.sum(subset) > min_points:
percents = np.percentile(err_subset_mean, [15, 75])
# percents = np.percentile(err_subset, [25, 75])
error_dict[(i, j)] = (err_subset.shape[1], percents)
return error_dict
def check_errors(cgroup, imgp):
p3ds = cgroup.triangulate(imgp)
errors_full = cgroup.reprojection_error(p3ds, imgp, mean=False)
return get_error_dict(errors_full)
def subset_extra(extra, ixs):
if extra is None:
return None
new_extra = {
'objp': extra['objp'][ixs],
'ids': extra['ids'][ixs],
'rvecs': extra['rvecs'][:, ixs],
'tvecs': extra['tvecs'][:, ixs]
}
return new_extra
def resample_points_extra(imgp, extra, n_samp=25):
n_cams, n_points, _ = imgp.shape
ids = remap_ids(extra['ids'])
n_ids = np.max(ids)+1
good = ~np.isnan(imgp[:, :, 0])
ixs = np.arange(n_points)
cam_counts = np.zeros((n_ids, n_cams), dtype='int64')
for idnum in range(n_ids):
cam_counts[idnum] = np.sum(good[:, ids == idnum], axis=1)
cam_counts_random = cam_counts + np.random.random(size=cam_counts.shape)
best_boards = np.argsort(-cam_counts_random, axis=0)
cam_totals = np.zeros(n_cams, dtype='int64')
include = set()
for cam_num in range(n_cams):
for board_id in best_boards[:, cam_num]:
include.update(ixs[ids == board_id])
cam_totals += cam_counts[board_id]
if cam_totals[cam_num] >= n_samp or \
cam_counts_random[board_id, cam_num] < 1:
break
final_ixs = sorted(include)
newp = imgp[:, final_ixs]
extra = subset_extra(extra, final_ixs)
return newp, extra
def resample_points(imgp, extra=None, n_samp=25):
# if extra is not None:
# return resample_points_extra(imgp, extra, n_samp)
n_cams = imgp.shape[0]
good = ~np.isnan(imgp[:, :, 0])
ixs = np.arange(imgp.shape[1])
num_cams = np.sum(~np.isnan(imgp[:, :, 0]), axis=0)
include = set()
for i in range(n_cams):
for j in range(i+1, n_cams):
subset = good[i] & good[j]
n_good = np.sum(subset)
if n_good > 0:
## pick points, prioritizing points seen by more cameras
arr = np.copy(num_cams[subset]).astype('float64')
arr += np.random.random(size=arr.shape)
picked_ix = np.argsort(-arr)[:n_samp]
picked = ixs[subset][picked_ix]
include.update(picked)
final_ixs = sorted(include)
newp = imgp[:, final_ixs]
extra = subset_extra(extra, final_ixs)
return newp, extra
def medfilt_data(values, size=15):
padsize = size+5
vpad = np.pad(values, (padsize, padsize), mode='reflect')
vpadf = signal.medfilt(vpad, kernel_size=size)
return vpadf[padsize:-padsize]
def nan_helper(y):
return np.isnan(y), lambda z: z.nonzero()[0]
def interpolate_data(vals):
nans, ix = nan_helper(vals)
out = np.copy(vals)
try:
out[nans] = np.interp(ix(nans), ix(~nans), vals[~nans])
except ValueError:
out[:] = 0
return out
def remap_ids(ids):
unique_ids = np.unique(ids)
ids_out = np.copy(ids)
for i, num in enumerate(unique_ids):
ids_out[ids == num] = i
return ids_out
def transform_points(points, rvecs, tvecs):
"""Rotate points by given rotation vectors and translate.
Rodrigues' rotation formula is used.
"""
theta = np.linalg.norm(rvecs, axis=1)[:, np.newaxis]
with np.errstate(invalid='ignore'):
v = rvecs / theta
v = np.nan_to_num(v)
dot = np.sum(points * v, axis=1)[:, np.newaxis]
cos_theta = np.cos(theta)
sin_theta = np.sin(theta)
rotated = cos_theta * points + \
sin_theta * np.cross(v, points) + \
dot * (1 - cos_theta) * v
return rotated + tvecs
class Camera:
def __init__(self,
matrix=np.eye(3),
dist=np.zeros(5),
size=None,
rvec=np.zeros(3),
tvec=np.zeros(3),
name=None,
extra_dist=False):
self.set_camera_matrix(matrix)
self.set_distortions(dist)
self.set_size(size)
self.set_rotation(rvec)
self.set_translation(tvec)
self.set_name(name)
self.extra_dist = extra_dist
def get_dict(self):
return {
'name': self.get_name(),
'size': list(self.get_size()),
'matrix': self.get_camera_matrix().tolist(),
'distortions': self.get_distortions().tolist(),
'rotation': self.get_rotation().tolist(),
'translation': self.get_translation().tolist(),
}
def load_dict(self, d):
self.set_camera_matrix(d['matrix'])
self.set_rotation(d['rotation'])
self.set_translation(d['translation'])
self.set_distortions(d['distortions'])
self.set_name(d['name'])
self.set_size(d['size'])
def from_dict(d):
cam = Camera()
cam.load_dict(d)
return cam
def get_camera_matrix(self):
return self.matrix
def get_distortions(self):
return self.dist
def set_camera_matrix(self, matrix):
self.matrix = np.array(matrix, dtype='float64')
def set_focal_length(self, fx, fy=None):
if fy is None:
fy = fx
self.matrix[0, 0] = fx
self.matrix[1, 1] = fy
def get_focal_length(self, both=False):
fx = self.matrix[0, 0]
fy = self.matrix[1, 1]
if both:
return (fx, fy)
else:
return (fx + fy) / 2.0
def set_distortions(self, dist):
self.dist = np.array(dist, dtype='float64').ravel()
def set_rotation(self, rvec):
self.rvec = np.array(rvec, dtype='float64').ravel()
def get_rotation(self):
return self.rvec
def set_translation(self, tvec):
self.tvec = np.array(tvec, dtype='float64').ravel()
def get_translation(self):
return self.tvec
def get_extrinsics_mat(self):
return make_M(self.rvec, self.tvec)
def get_name(self):
return self.name
def set_name(self, name):
self.name = str(name)
def set_size(self, size):
"""set size as (width, height)"""
self.size = size
def get_size(self):
"""get size as (width, height)"""
return self.size
def resize_camera(self, scale):
"""resize the camera by scale factor, updating intrinsics to match"""
size = self.get_size()
new_size = size[0] * scale, size[1] * scale
matrix = self.get_camera_matrix()
new_matrix = matrix * scale
new_matrix[2, 2] = 1
self.set_size(new_size)
self.set_camera_matrix(new_matrix)
def get_params(self):
params = np.zeros(8 + self.extra_dist, dtype='float64')
params[0:3] = self.get_rotation()
params[3:6] = self.get_translation()
params[6] = self.get_focal_length()
dist = self.get_distortions()
params[7] = dist[0]
if self.extra_dist:
params[8] = dist[1]
return params
def set_params(self, params):
self.set_rotation(params[0:3])
self.set_translation(params[3:6])
self.set_focal_length(params[6])
dist = np.zeros(5, dtype='float64')
dist[0] = params[7]
if self.extra_dist:
dist[1] = params[8]
self.set_distortions(dist)
def distort_points(self, points):
shape = points.shape
points = points.reshape(-1, 1, 2)
new_points = np.dstack([points, np.ones((points.shape[0], 1, 1))])
out, _ = cv2.projectPoints(new_points, np.zeros(3), np.zeros(3),
self.matrix.astype('float64'),
self.dist.astype('float64'))
return out.reshape(shape)
def undistort_points(self, points):
shape = points.shape
points = points.reshape(-1, 1, 2)
out = cv2.undistortPoints(points,
self.matrix.astype('float64'),
self.dist.astype('float64'))
return out.reshape(shape)
def project(self, points):
points = points.reshape(-1, 1, 3)
out, _ = cv2.projectPoints(points, self.rvec, self.tvec,
self.matrix.astype('float64'),
self.dist.astype('float64'))
return out
def reprojection_error(self, p3d, p2d):
proj = self.project(p3d).reshape(p2d.shape)
return p2d - proj
def copy(self):
return \
Camera(matrix=self.get_camera_matrix().copy(),
dist=self.get_distortions().copy(),
size=self.get_size(),
rvec=self.get_rotation().copy(),
tvec=self.get_translation().copy(),
name=self.get_name(),
extra_dist=self.extra_dist)
class FisheyeCamera(Camera):
def __init__(self,
matrix=np.eye(3),
dist=np.zeros(4),
size=None,
rvec=np.zeros(3),
tvec=np.zeros(3),
name=None,
extra_dist=False):
self.set_camera_matrix(matrix)
self.set_distortions(dist)
self.set_size(size)
self.set_rotation(rvec)
self.set_translation(tvec)
self.set_name(name)
self.extra_dist = extra_dist
def from_dict(d):
cam = FisheyeCamera()
cam.load_dict(d)
return cam
def get_dict(self):
d = super().get_dict()
d['fisheye'] = True
return d
def distort_points(self, points):
shape = points.shape
points = points.reshape(-1, 1, 2)
new_points = np.dstack([points, np.ones((points.shape[0], 1, 1))])
out, _ = cv2.fisheye.projectPoints(new_points,
np.zeros(3), np.zeros(3),
self.matrix.astype('float64'),
self.dist.astype('float64'))
return out.reshape(shape)
def undistort_points(self, points):
shape = points.shape
points = points.reshape(-1, 1, 2)
out = cv2.fisheye.undistortPoints(points.astype('float64'),
self.matrix.astype('float64'),
self.dist.astype('float64'))
return out.reshape(shape)
def project(self, points):
points = points.reshape(-1, 1, 3)
out, _ = cv2.fisheye.projectPoints(points,
self.rvec, self.tvec,
self.matrix.astype('float64'),
self.dist.astype('float64'))
return out
def set_params(self, params):
self.set_rotation(params[0:3])
self.set_translation(params[3:6])
self.set_focal_length(params[6])
dist = np.zeros(4, dtype='float64')
dist[0] = params[7]
if self.extra_dist:
dist[1] = params[8]
# dist[2] = params[9]
# dist[3] = params[10]
self.set_distortions(dist)
def get_params(self):
params = np.zeros(8+self.extra_dist, dtype='float64')
params[0:3] = self.get_rotation()
params[3:6] = self.get_translation()
params[6] = self.get_focal_length()
dist = self.get_distortions()
params[7] = dist[0]
if self.extra_dist:
params[8] = dist[1]
# params[9] = dist[2]
# params[10] = dist[3]
return params
def copy(self):
return FisheyeCamera(
matrix=self.get_camera_matrix().copy(),
dist=self.get_distortions().copy(),
size=self.get_size(),
rvec=self.get_rotation().copy(),
tvec=self.get_translation().copy(),
name=self.get_name(),
extra_dist=self.extra_dist)
class CameraGroup:
def __init__(self, cameras, metadata={}):
self.cameras = cameras
self.metadata = metadata
def subset_cameras(self, indices):
cams = [self.cameras[ix].copy() for ix in indices]
return CameraGroup(cams, self.metadata)
def subset_cameras_names(self, names):
cur_names = self.get_names()
cur_names_dict = dict(zip(cur_names, range(len(cur_names))))
indices = []
for name in names:
if name not in cur_names_dict:
raise IndexError(
"name {} not part of camera names: {}".format(
name, cur_names
))
indices.append(cur_names_dict[name])
return self.subset_cameras(indices)
def project(self, points):
"""Given an Nx3 array of points, this returns an CxNx2 array of 2D points,
where C is the number of cameras"""
points = points.reshape(-1, 1, 3)
n_points = points.shape[0]
n_cams = len(self.cameras)
out = np.empty((n_cams, n_points, 2), dtype='float64')
for cnum, cam in enumerate(self.cameras):
out[cnum] = cam.project(points).reshape(n_points, 2)
return out
def triangulate(self, points, undistort=True, progress=False):
"""Given an CxNx2 array, this returns an Nx3 array of points,
where N is the number of points and C is the number of cameras"""
assert points.shape[0] == len(self.cameras), \
"Invalid points shape, first dim should be equal to" \
" number of cameras ({}), but shape is {}".format(
len(self.cameras), points.shape
)
one_point = False
if len(points.shape) == 2:
points = points.reshape(-1, 1, 2)
one_point = True
if undistort:
new_points = np.empty(points.shape)
for cnum, cam in enumerate(self.cameras):
# must copy in order to satisfy opencv underneath
sub = np.copy(points[cnum])
new_points[cnum] = cam.undistort_points(sub)
points = new_points
n_cams, n_points, _ = points.shape
out = np.empty((n_points, 3))
out[:] = np.nan
cam_mats = np.array([cam.get_extrinsics_mat() for cam in self.cameras])
if progress:
iterator = trange(n_points, ncols=70)
else:
iterator = range(n_points)
for ip in iterator:
subp = points[:, ip, :]
good = ~np.isnan(subp[:, 0])
if np.sum(good) >= 2:
out[ip] = triangulate_simple(subp[good], cam_mats[good])
if one_point:
out = out[0]
return out
def triangulate_possible(self, points, undistort=True,
min_cams=2, progress=False, threshold=0.5):
"""Given an CxNxPx2 array, this returns an Nx3 array of points
by triangulating all possible points and picking the ones with
best reprojection error
where:
C: number of cameras
N: number of points
P: number of possible options per point
"""
assert points.shape[0] == len(self.cameras), \
"Invalid points shape, first dim should be equal to" \
" number of cameras ({}), but shape is {}".format(
len(self.cameras), points.shape
)
n_cams, n_points, n_possible, _ = points.shape
cam_nums, point_nums, possible_nums = np.where(
~np.isnan(points[:, :, :, 0]))
all_iters = defaultdict(dict)
for cam_num, point_num, possible_num in zip(cam_nums, point_nums,
possible_nums):
if cam_num not in all_iters[point_num]:
all_iters[point_num][cam_num] = []
all_iters[point_num][cam_num].append((cam_num, possible_num))
for point_num in all_iters.keys():
for cam_num in all_iters[point_num].keys():
all_iters[point_num][cam_num].append(None)
out = np.full((n_points, 3), np.nan, dtype='float64')
picked_vals = np.zeros((n_cams, n_points, n_possible), dtype='bool')
errors = np.zeros(n_points, dtype='float64')
points_2d = np.full((n_cams, n_points, 2), np.nan, dtype='float64')
if progress:
iterator = trange(n_points, ncols=70)
else:
iterator = range(n_points)
for point_ix in iterator:
best_point = None
best_error = 200
n_cams_max = len(all_iters[point_ix])
for picked in itertools.product(*all_iters[point_ix].values()):
picked = [p for p in picked if p is not None]
if len(picked) < min_cams and len(picked) != n_cams_max:
continue
cnums = [p[0] for p in picked]
xnums = [p[1] for p in picked]
pts = points[cnums, point_ix, xnums]
cc = self.subset_cameras(cnums)
p3d = cc.triangulate(pts, undistort=undistort)
err = cc.reprojection_error(p3d, pts, mean=True)
if err < best_error:
best_point = {
'error': err,
'point': p3d[:3],
'points': pts,
'picked': picked,
'joint_ix': point_ix
}
best_error = err
if best_error < threshold:
break
if best_point is not None:
out[point_ix] = best_point['point']
picked = best_point['picked']
cnums = [p[0] for p in picked]
xnums = [p[1] for p in picked]
picked_vals[cnums, point_ix, xnums] = True
errors[point_ix] = best_point['error']
points_2d[cnums, point_ix] = best_point['points']
return out, picked_vals, points_2d, errors
def triangulate_ransac(self, points, undistort=True, min_cams=2, progress=False):
"""Given an CxNx2 array, this returns an Nx3 array of points,
where N is the number of points and C is the number of cameras"""
assert points.shape[0] == len(self.cameras), \
"Invalid points shape, first dim should be equal to" \
" number of cameras ({}), but shape is {}".format(
len(self.cameras), points.shape
)
n_cams, n_points, _ = points.shape
points_ransac = points.reshape(n_cams, n_points, 1, 2)
return self.triangulate_possible(points_ransac,
undistort=undistort,
min_cams=min_cams,
progress=progress)
@jit(parallel=True, forceobj=True)
def reprojection_error(self, p3ds, p2ds, mean=False):
"""Given an Nx3 array of 3D points and an CxNx2 array of 2D points,
where N is the number of points and C is the number of cameras,
this returns an CxNx2 array of errors.
Optionally mean=True, this averages the errors and returns array of length N of errors"""
one_point = False
if len(p3ds.shape) == 1 and len(p2ds.shape) == 2:
p3ds = p3ds.reshape(1, 3)
p2ds = p2ds.reshape(-1, 1, 2)
one_point = True
n_cams, n_points, _ = p2ds.shape
assert p3ds.shape == (n_points, 3), \
"shapes of 2D and 3D points are not consistent: " \
"2D={}, 3D={}".format(p2ds.shape, p3ds.shape)
errors = np.empty((n_cams, n_points, 2))
for cnum, cam in enumerate(self.cameras):
errors[cnum] = cam.reprojection_error(p3ds, p2ds[cnum])
if mean:
errors_norm = np.linalg.norm(errors, axis=2)
good = ~np.isnan(errors_norm)
errors_norm[~good] = 0
denom = np.sum(good, axis=0).astype('float64')
denom[denom < 1.5] = np.nan
errors = np.sum(errors_norm, axis=0) / denom
if one_point:
if mean:
errors = float(errors[0])
else:
errors = errors.reshape(-1, 2)
return errors
def bundle_adjust_iter(self, p2ds, extra=None,
n_iters=10, start_mu=15, end_mu=1,
max_nfev=200, ftol=1e-4,
n_samp_iter=100, n_samp_full=1000,
error_threshold=0.3,
verbose=False):
"""Given an CxNx2 array of 2D points,
where N is the number of points and C is the number of cameras,
this performs iterative bundle adjustsment to fine-tune the parameters of the cameras.
That is, it performs bundle adjustment multiple times, adjusting the weights given to points
to reduce the influence of outliers.
This is inspired by the algorithm for Fast Global Registration by Zhou, Park, and Koltun
"""
assert p2ds.shape[0] == len(self.cameras), \
"Invalid points shape, first dim should be equal to" \
" number of cameras ({}), but shape is {}".format(
len(self.cameras), p2ds.shape
)
p2ds_full = p2ds
extra_full = extra
p2ds, extra = resample_points(p2ds_full, extra_full,
n_samp=n_samp_full)
error = self.average_error(p2ds, median=True)
if verbose:
print('error: ', error)
mus = np.exp(np.linspace(np.log(start_mu), np.log(end_mu), num=n_iters))
if verbose:
print('n_samples: {}'.format(n_samp_iter))
for i in range(n_iters):
p2ds, extra = resample_points(p2ds_full, extra_full,
n_samp=n_samp_full)
p3ds = self.triangulate(p2ds)
errors_full = self.reprojection_error(p3ds, p2ds, mean=False)
errors_norm = self.reprojection_error(p3ds, p2ds, mean=True)
error_dict = get_error_dict(errors_full)
max_error = 0
min_error = 0
for k, v in error_dict.items():
num, percents = v
max_error = max(percents[-1], max_error)
min_error = max(percents[0], min_error)
mu = max(min(max_error, mus[i]), min_error)
good = errors_norm < mu
extra_good = subset_extra(extra, good)
p2ds_samp, extra_samp = resample_points(
p2ds[:, good], extra_good, n_samp=n_samp_iter)
error = np.median(errors_norm)
if error < error_threshold:
break
if verbose:
pprint(error_dict)
print('error: {:.2f}, mu: {:.1f}, ratio: {:.3f}'.format(error, mu, np.mean(good)))
self.bundle_adjust(p2ds_samp, extra_samp,
loss='linear', ftol=ftol,
max_nfev=max_nfev,
verbose=verbose)
p2ds, extra = resample_points(p2ds_full, extra_full,
n_samp=n_samp_full)
p3ds = self.triangulate(p2ds)
errors_full = self.reprojection_error(p3ds, p2ds, mean=False)
errors_norm = self.reprojection_error(p3ds, p2ds, mean=True)
error_dict = get_error_dict(errors_full)
if verbose:
pprint(error_dict)
max_error = 0
min_error = 0
for k, v in error_dict.items():
num, percents = v
max_error = max(percents[-1], max_error)
min_error = max(percents[0], min_error)
mu = max(max(max_error, end_mu), min_error)
good = errors_norm < mu
extra_good = subset_extra(extra, good)
self.bundle_adjust(p2ds[:, good], extra_good,
loss='linear',
ftol=ftol, max_nfev=max(200, max_nfev),
verbose=verbose)
error = self.average_error(p2ds, median=True)
p3ds = self.triangulate(p2ds)
errors_full = self.reprojection_error(p3ds, p2ds, mean=False)
error_dict = get_error_dict(errors_full)
if verbose:
pprint(error_dict)
if verbose:
print('error: ', error)
return error
def bundle_adjust(self, p2ds, extra=None,
loss='linear',
threshold=50,
ftol=1e-4,
max_nfev=1000,
weights=None,
start_params=None,
verbose=True):
"""Given an CxNx2 array of 2D points,
where N is the number of points and C is the number of cameras,
this performs bundle adjustsment to fine-tune the parameters of the cameras"""
assert p2ds.shape[0] == len(self.cameras), \
"Invalid points shape, first dim should be equal to" \
" number of cameras ({}), but shape is {}".format(
len(self.cameras), p2ds.shape
)
if extra is not None:
extra['ids_map'] = remap_ids(extra['ids'])
x0, n_cam_params = self._initialize_params_bundle(p2ds, extra)
if start_params is not None:
x0 = start_params
n_cam_params = len(self.cameras[0].get_params())
error_fun = self._error_fun_bundle
jac_sparse = self._jac_sparsity_bundle(p2ds, n_cam_params, extra)
f_scale = threshold
opt = optimize.least_squares(error_fun,
x0,
jac_sparsity=jac_sparse,
f_scale=f_scale,
x_scale='jac',
loss=loss,
ftol=ftol,
method='trf',
tr_solver='lsmr',
verbose=2 * verbose,
max_nfev=max_nfev,
args=(p2ds, n_cam_params, extra))
best_params = opt.x
for i, cam in enumerate(self.cameras):
a = i * n_cam_params
b = (i + 1) * n_cam_params
cam.set_params(best_params[a:b])
error = self.average_error(p2ds)
return error
@jit(parallel=True, forceobj=True)
def _error_fun_bundle(self, params, p2ds, n_cam_params, extra):
"""Error function for bundle adjustment"""
good = ~np.isnan(p2ds)
n_cams = len(self.cameras)
for i in range(n_cams):
cam = self.cameras[i]
a = i * n_cam_params
b = (i + 1) * n_cam_params
cam.set_params(params[a:b])
n_cams = len(self.cameras)
sub = n_cam_params * n_cams
n3d = p2ds.shape[1] * 3
p3ds_test = params[sub:sub+n3d].reshape(-1, 3)
errors = self.reprojection_error(p3ds_test, p2ds)
errors_reproj = errors[good]
if extra is not None:
ids = extra['ids_map']
objp = extra['objp']
min_scale = np.min(objp[objp > 0])
n_boards = int(np.max(ids)) + 1
a = sub+n3d
rvecs = params[a:a+n_boards*3].reshape(-1, 3)
tvecs = params[a+n_boards*3:a+n_boards*6].reshape(-1, 3)
expected = transform_points(objp, rvecs[ids], tvecs[ids])
errors_obj = 2 * (p3ds_test - expected).ravel() / min_scale
else:
errors_obj = np.array([])
return np.hstack([errors_reproj, errors_obj])
def _jac_sparsity_bundle(self, p2ds, n_cam_params, extra):
"""Given an CxNx2 array of 2D points,
where N is the number of points and C is the number of cameras,
compute the sparsity structure of the jacobian for bundle adjustment"""
point_indices = np.zeros(p2ds.shape, dtype='int32')
cam_indices = np.zeros(p2ds.shape, dtype='int32')
for i in range(p2ds.shape[1]):
point_indices[:, i] = i
for j in range(p2ds.shape[0]):
cam_indices[j] = j
good = ~np.isnan(p2ds)
if extra is not None:
ids = extra['ids_map']
n_boards = int(np.max(ids)) + 1
total_board_params = n_boards * (3 + 3) # rvecs + tvecs
else:
n_boards = 0
total_board_params = 0
n_cams = p2ds.shape[0]
n_points = p2ds.shape[1]
total_params_reproj = n_cams * n_cam_params + n_points * 3
n_params = total_params_reproj + total_board_params
n_good_values = np.sum(good)
if extra is not None:
n_errors = n_good_values + n_points * 3
else:
n_errors = n_good_values
A_sparse = dok_matrix((n_errors, n_params), dtype='int16')
cam_indices_good = cam_indices[good]
point_indices_good = point_indices[good]
# -- reprojection error --
ix = np.arange(n_good_values)
## update camera params based on point error
for i in range(n_cam_params):
A_sparse[ix, cam_indices_good * n_cam_params + i] = 1
## update point position based on point error
for i in range(3):
A_sparse[ix, n_cams * n_cam_params + point_indices_good * 3 + i] = 1
# -- match for the object points--
if extra is not None:
point_ix = np.arange(n_points)
## update all the camera parameters
# A_sparse[n_good_values:n_good_values+n_points*3,
# 0:n_cams*n_cam_params] = 1
## update board rotation and translation based on error from expected
for i in range(3):
for j in range(3):
A_sparse[n_good_values + point_ix*3 + i,
total_params_reproj + ids*3 + j] = 1
A_sparse[n_good_values + point_ix*3 + i,
total_params_reproj + n_boards*3 + ids*3 + j] = 1
## update point position based on error from expected
for i in range(3):
A_sparse[n_good_values + point_ix*3 + i,
n_cams*n_cam_params + point_ix*3 + i] = 1
return A_sparse
def _initialize_params_bundle(self, p2ds, extra):
"""Given an CxNx2 array of 2D points,
where N is the number of points and C is the number of cameras,
initializes the parameters for bundle adjustment"""
cam_params = np.hstack([cam.get_params() for cam in self.cameras])
n_cam_params = len(cam_params) // len(self.cameras)
total_cam_params = len(cam_params)
n_cams, n_points, _ = p2ds.shape
assert n_cams == len(self.cameras), \
"number of cameras in CameraGroup does not " \
"match number of cameras in 2D points given"
p3ds = self.triangulate(p2ds)
if extra is not None:
ids = extra['ids_map']
n_boards = int(np.max(ids[~np.isnan(ids)])) + 1
total_board_params = n_boards * (3 + 3) # rvecs + tvecs
# initialize to 0
rvecs = np.zeros((n_boards, 3), dtype='float64')
tvecs = np.zeros((n_boards, 3), dtype='float64')
if 'rvecs' in extra and 'tvecs' in extra:
rvecs_all = extra['rvecs']
tvecs_all = extra['tvecs']
for board_num in range(n_boards):
point_id = np.where(ids == board_num)[0][0]
cam_ids_possible = np.where(~np.isnan(p2ds[:, point_id, 0]))[0]
cam_id = np.random.choice(cam_ids_possible)
M_cam = self.cameras[cam_id].get_extrinsics_mat()
M_board_cam = make_M(rvecs_all[cam_id, point_id],
tvecs_all[cam_id, point_id])
M_board = np.matmul(np.linalg.inv(M_cam), M_board_cam)
rvec, tvec = get_rtvec(M_board)
rvecs[board_num] = rvec
tvecs[board_num] = tvec
else:
total_board_params = 0
x0 = np.zeros(total_cam_params + p3ds.size + total_board_params)
x0[:total_cam_params] = cam_params
x0[total_cam_params:total_cam_params+p3ds.size] = p3ds.ravel()
if extra is not None:
start_board = total_cam_params+p3ds.size
x0[start_board:start_board + n_boards*3] = rvecs.ravel()
x0[start_board + n_boards*3:start_board + n_boards*6] = \
tvecs.ravel()
return x0, n_cam_params
def optim_points(self, points, p3ds,
constraints=[],
constraints_weak=[],
scale_smooth=4,
scale_length=2, scale_length_weak=0.5,
reproj_error_threshold=15, reproj_loss='soft_l1',
n_deriv_smooth=1, scores=None, verbose=False):
"""
Take in an array of 2D points of shape CxNxJx2,
an array of 3D points of shape NxJx3,
and an array of constraints of shape Kx2, where
C: number of camera
N: number of frames
J: number of joints
K: number of constraints