-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathanalysis.py
1674 lines (1344 loc) · 59.7 KB
/
analysis.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
"""
PhotoScan Analyse 0.4.2
"""
version = "0.4.2"
import copy
import os
import re
import sys
from STL_Writer import Binary_STL_Writer
__author__ = 'philipp.atorf'
import math
from collections import defaultdict
from math import sqrt
import PhotoScan
import svd
from pysvg.builders import *
import pysvg
import imp
imp.reload(pysvg)
from pysvg.builders import *
class I3_Photo():
"""
I3 Photo can store photo information.
:ivar label: image label
:ivar points: list of visible points
:ivar photoScan_camera: PhotoScan.Camera representation of this Photo
:ivar sigma: standard deviation of the image measurement. calculatet from the covarianzmatrix of all measurements
"""
def __init__(self, label=None):
"""
"""
self.label = label
self.points = []
""":type : list of I3_Point"""
self.photoScan_camera = None
""":type : PhotoScan.Camera"""
self.__sigma_I = None
""":type : PhotoScan.Vector"""
self.__sigma_C = None
""":type : PhotoScan.Vector"""
self.thumbnail_path = None
def add_point(self, new_point=None):
"""
:rtype : I3_Point
"""
if new_point is None:
new_point = I3_Point()
self.points.append(new_point)
return self.points[-1]
def __calc_sigma(self, where='I'):
"""
returns the standard deviation of the x and y image measurements.
the calculation used the covarianzmatrix (see. http://www.chemgapedia.de/vsengine/vlu/vsc/de/ch/13/vlu/daten/multivariate_datenanalyse_allg/multivar_datenanalyse_allg.vlu/Page/vsc/de/ch/13/anc/daten/multivar_datenanalyse_allg/varianz_kovarianzmatrix.vscml.html)
:rtype : PhotoScan.Vector
"""
error_matrix = self.get_error_matrix(where)
cov = self.calc_cov_from_error_matrix(error_matrix)
sigma_x = math.sqrt(cov[0, 0])
sigma_y = math.sqrt(cov[1, 1])
return PhotoScan.Vector([sigma_x, sigma_y])
def __calc_sigma_I(self):
if self.__sigma_I is None:
self.__sigma_I = self.__calc_sigma('I')
return self.__sigma_I
def __call_sigma_C(self):
if self.__sigma_C is None:
self.__sigma_C = self.__calc_sigma('C')
return self.__sigma_C
def __set_sigma_I(self, sigma):
self.__sigma_I = sigma
def __set_sigma_C(self, sigma):
self.__sigma_C = sigma
def get_max_error(self):
error_matrix = self.get_error_matrix()
max_error = PhotoScan.Vector((0, 0))
max_error.x = max(abs(l[0]) for l in error_matrix)
max_error.y = max(abs(l[1]) for l in error_matrix)
return max_error
@staticmethod
def calc_cov_from_error_matrix(error_matrix):
# X_list = []
# for error in pointError:
# X_list.append([error.x, error.y, error.z])
X_matrix = PhotoScan.Matrix(error_matrix)
C = X_matrix.t() * X_matrix
C = C * (1 / (len(error_matrix)))
return C
def get_error_matrix(self, where='I'):
"""
the value of each row of error matrix shows the image error in x and y.
normalie this matrix is calculated by subtraction the measurement by the
mean of all measurements (coloumn mean) [x_11 - x_mean, y_11-y_mean;...]
"""
error_matrix = []
for point in self.points:
if where == 'I':
error_matrix.append([point.error_I.x, point.error_I.y])
elif where == 'C':
error_matrix.append([point.error_C.x, point.error_C.y])
return error_matrix
@staticmethod
def print_report_header():
r_str = 'Photoscan Analysis Image-Measurement-Report (Unit = Pixel) \n'
r_str += '{0:>12s}{1:>14s}{2:>9s}{3:>9s}{4:>9s}{5:>9s}{6:>9s}\n' \
.format('Camera Name',
'Projections',
'SIGMA x',
'SIGMA y',
'SIGMA P',
'MAX x',
'MAX y')
return r_str
def print_report_line(self):
r_str = ''
sigma = self.sigma_I
max_error = self.get_max_error()
r_str += '{:>12s}{:14d}{:9.5f}{:9.5f}{:9.5f}{:9.5f}{:9.5f}\n'. \
format(self.label,
len(self.points),
sigma.x,
sigma.y,
sigma.norm(),
max_error.x,
max_error.y)
return r_str
sigma_I = property(__calc_sigma_I, __set_sigma_I)
sigma_C = property(__call_sigma_C, __set_sigma_C)
class I3_Point():
"""
Representation of a feature point in a Image and the world point.
:ivar projection_I: reprojection of the world point into the image plane in meter
:ivar measurement_I: measurement of the feature in pixel
:ivar track_id: global id of the point in meter
:ivar coord_Chunk: chunk coordinates of the point in meter
:ivar coord_C: camera coordinates of the point in meter
"""
def __init__(self,
projection_I=None,
measurement_I=None,
measurement_C=None,
track_id=None,
coord_Chunk=None,
coord_C=None,
):
self.projection_I = projection_I
self.measurement_I = measurement_I
self.measurement_C = measurement_C
self.track_id = track_id
self.coord_Chunk = coord_Chunk
self.coord_C = coord_C
self.intersection_cout = 0
@property
def error_I(self):
"""
reprojection error in pixel
:return:
"""
return self.projection_I - self.measurement_I
@property
def error_C(self):
"""
reprojection error in meter on the image plance with a distance of 1m
"""
point_on_image_plane = self.coord_C / self.coord_C.z
return point_on_image_plane - self.measurement_C
@property
def coord_W(self):
transform_Chunk2W = PhotoScan.app.document.chunk.transform.matrix
coord_chunk_homogen = self.coord_Chunk
coord_chunk_homogen.size = 4
coord_chunk_homogen.w = 1
return transform_Chunk2W * self.coord_Chunk
class I3_Project():
"""
I3_Project is the main class of the module.
it is used to controll the workflow of the analysis.
Beside some helper functions, the main workflow functions are:
print_report()
create_project_SVG()
export_STL(binary=True, factor=factor)
:ivar photos: list of all photos in this project
:ivar point_photo_reference: dictonary with track_id as key
and a list of all photos, in which the points are visible, as value
"""
def __init__(self, chunk=None):
self.photos = []
""":type: list[I3_Photo]"""
self.point_photo_reference = {}
""":type: dict[int, list[I3_Photo]]"""
self.path = PhotoScan.app.document.path
self.adjustment = None
project_directory = "\\".join(self.path.split('\\')[:-1])
analyse_dir = PhotoScan.app.getExistingDirectory(
'Please create or select a folder where the analys files will be saved')
if analyse_dir:
self.directory = analyse_dir
else:
self.directory = project_directory
if chunk:
self.__fill_photos_with_points(chunk)
def __get_point_photos_reference(self):
if not self.point_photo_reference:
points_photo_dict = self.point_photo_reference
for photo in self.photos:
for point in photo.points:
if point.track_id in points_photo_dict:
points_photo_dict[point.track_id].append(photo)
else:
points_photo_dict[point.track_id] = []
points_photo_dict[point.track_id].append(photo)
return self.point_photo_reference
def export_for_OpenScad(self, filename='openScad'):
filename += ".scad"
adjustment = Peseudo_3D_intersection_adjustment(self.__get_point_photos_reference())
ellipsoid_parameter_list = adjustment._get_eigvalues_eigvectors_pos_cov_for_track_id()
output_str = "factor = 0.051;\n"
for ellipsoid_parameter in ellipsoid_parameter_list:
eig_val, eig_vec, pos = ellipsoid_parameter
output_str += Py_2_OpenScad.errorEllipse_from_eig(eig_vec, eig_val, pos)
f = open(self.directory + '\\' + filename, 'w')
f.write(output_str)
f.close()
print('save file ', filename, ' to: ', self.directory)
def export_STL(self, filename=None, binary=None, factor=None):
if filename is None:
filename = 'stl_export'
filename += '.stl'
if binary is None:
binary = True
if factor is None:
factor = 100
print('start output STL-File with factor {:8.6f}: '.format(factor) + filename)
PhotoScan.app.update()
if self.adjustment is None:
self.adjustment = Peseudo_3D_intersection_adjustment(self.__get_point_photos_reference())
ellipsoid_parameter_list = self.adjustment._get_eigvalues_eigvectors_pos_cov_for_track_id()
output_str = "solid Ellipsoids\n"
stl_handler = STL_Handler()
if not binary:
for ellipsoid_parameter in ellipsoid_parameter_list:
eig_val, eig_vec, pos = ellipsoid_parameter
output_str += stl_handler.create_ellipsoid_stl(eig_vec, eig_val, pos, factor, False)
## output_str += Py_2_OpenScad.errorEllipse_from_eig(eig_vec, eig_val, pos)
output_str += "endsolid Ellipsoids"
f = open(self.directory + '\\' + filename, 'w')
f.write(output_str)
f.close()
print('save file ', filename, ' to: ', self.directory)
else:
data = []
for ellipsoid_parameter in ellipsoid_parameter_list:
eig_val, eig_vec, pos, cov = ellipsoid_parameter
data.extend(stl_handler.create_ellipsoid_stl(eig_vec, eig_val, pos, factor, True))
with open(self.directory + '\\' + filename, 'wb') as fp:
writer = Binary_STL_Writer(fp)
writer.add_faces(data)
writer.close()
print('save bin file ', filename, ' to: ', self.directory)
def exportEllipsoids(self, filename=None):
if filename is None:
filename = 'ellipsoid_export'
filename += '.ell'
if self.adjustment is None:
self.adjustment = Peseudo_3D_intersection_adjustment(self.__get_point_photos_reference())
ellipsoid_list = self.adjustment._get_eigvalues_eigvectors_pos_cov_for_track_id()
export_str = "xc yc zc\n" \
"xr.x xr.y xr.z\n" \
"yr.x yr.y yr.z\n" \
"zr.x zr.y zr.z\n" \
"C11 C12 C13\n" \
"C21 C22 C23\n" \
"C31 C32 C33\n"
for ellipsoid in ellipsoid_list:
eigVal = PhotoScan.Vector(ellipsoid[0])
eigVecs = PhotoScan.Matrix(ellipsoid[1])
pos = PhotoScan.Vector(ellipsoid[2])
cov = ellipsoid[3]
xr = list(eigVecs.col(0) * eigVal[0])
yr = list(eigVecs.col(1) * eigVal[1])
zr = list(eigVecs.col(2) * eigVal[2])
xc = pos[0]
yc = pos[1]
zc = pos[2]
export_str += "{:.2e} {:.2e} {:.2e}\n".format(xc, yc, zc)
export_str += "{:.2e} {:.2e} {:.2e}\n".format(xr[0], xr[1], xr[2])
export_str += "{:.2e} {:.2e} {:.2e}\n".format(yr[0], yr[1], yr[2])
export_str += "{:.2e} {:.2e} {:.2e}\n".format(zr[0], zr[1], zr[2])
export_str += "{:.4e} {:.4e} {:.4e}\n".format(cov[0, 0], cov[0, 1], cov[0, 2])
export_str += "{:.4e} {:.4e} {:.4e}\n".format(cov[1, 0], cov[1, 1], cov[1, 2])
export_str += "{:.4e} {:.4e} {:.4e}\n".format(cov[2, 0], cov[2, 1], cov[2, 2])
f = open(self.directory + '\\' + filename, 'w')
f.write(export_str)
f.close()
print('save file ', filename, ' to: ', self.directory)
def _get_RMS_4_all_photos(self, photos=None):
"""
returns the root mean square for all photos in this project
:param photos:
:return:
"""
if not photos:
photos = self.photos
var_x_sum = 0
var_y_sum = 0
for photo in photos:
sigma_photo = photo.sigma_I
var_x_sum += sigma_photo.x ** 2
var_y_sum += sigma_photo.y ** 2
rms_x = math.sqrt(var_x_sum / len(photos))
rms_y = math.sqrt(var_y_sum / len(photos))
return rms_x, rms_y
def __save_thumbnails(self):
for photo in self.photos:
thumbnail_path = self.directory + '/' + photo.label.lower()
success = photo.photoScan_camera.thumbnail.image().save(thumbnail_path)
if success:
photo.thumbnail_path = thumbnail_path
else:
print('can not save thumbnail')
def __fill_photos_with_points(self, chunk):
"""
saves all photos (with points) in the chunck to slef.photos
:param chunk:
:return:
"""
all_photos = self.photos
point_cloud = chunk.point_cloud
points = point_cloud.points
npoints = len(points)
projections = chunk.point_cloud.projections
w_point_construction_cout = {}
for camera in chunk.cameras:
if not camera.transform:
continue
# create new photo
this_photo = I3_Photo(camera.label)
this_photo.photoScan_camera = camera
all_photos.append(this_photo)
T = camera.transform.inv()
calib = camera.sensor.calibration
point_index = 0
for proj in projections[camera]:
track_id = proj.track_id
while point_index < npoints and points[point_index].track_id < track_id:
point_index += 1
if point_index < npoints and points[point_index].track_id == track_id:
if not points[point_index].valid:
continue
point_Chunk = points[point_index].coord
point_C = T * point_Chunk
point_C.size = 3
point_I = calib.project(point_C)
# print("-------------",track_id)
# print("center",calib.project(PhotoScan.Vector([0,0,1])))
# print("PointW",point_Chunk)
# print("PointC ",point_C)
# print("point_I proj", point_I )
measurement_I = proj.coord
measurement_C = calib.unproject(measurement_I)
# print("measI",measurement_I)
# print("mearC",measurement_C)
# error_I = calib.error(point_C, measurement_I)
# error_C = point_C - measurement_C * point_C.z
# print(point_C)
# print(measurement_C)
# save Point in curren Photo
# cout from how many photos a point is created
if track_id in w_point_construction_cout:
w_point_construction_cout[track_id] += 1
else:
# first time ot this track id
w_point_construction_cout[track_id] = 1
if point_I:
point = this_photo.add_point()
point.track_id = track_id
point.projection_I = point_I
point.measurement_I = measurement_I
point.coord_C = point_C
point.coord_Chunk = point_Chunk
point.measurement_C = measurement_C
# point.projection_C = error_C
for photo in self.photos:
for point in photo.points:
point.intersection_cout = w_point_construction_cout[point.track_id]
def save_and_print_report(self, filename=None):
"""
prints and saves the report. the report contains information
about each photo (count of measurements, standard deviation and max_error)
in this project
:param filename: filename to save the file
:return:
"""
if filename is None:
filename = 'report'
filename += '.txt'
r_str = ""
r_str += I3_Photo.print_report_header()
for phots in self.photos:
assert isinstance(phots, I3_Photo)
r_str += phots.print_report_line()
r_str += '\n'
rms_x, rms_y = self._get_RMS_4_all_photos()
r_str += '{:>26s}{:9.5f}{:9.5f}'.format('RMS:', rms_x, rms_y)
print(r_str)
f = open(self.directory + '\\' + filename, 'w')
f.write(r_str)
f.close()
print('save file ', filename, ' to: ', self.directory)
def create_project_SVG(self, filename=None, error_factor=None, cols=None):
"""
this methode creates a svg file. The file contains a overview of
all images with its feature-points and error vectors. additionally a
overview shows the number of measurements in one raster cell.
:param error_factor: magnification factor of the error-vector
:param cols: the number of columns used to generate the overview image
:return:
"""
self.__save_thumbnails()
if filename is None:
filename = 'image_measurements'
if error_factor is None:
error_factor = 40
if cols is None:
cols = 20
filename += '.svg'
s = svg()
summery_SVG = SVG_Photo_Representation(self.photos)
summery_SVG.point_radius = 1
summery, height = summery_SVG.get_raw_error_vector_svg(factor=error_factor)
s.addElement(summery)
#Summery Cout Raster
summery_group = g()
summery_error_raster, height = summery_SVG.get_raw_error_vector_svg(as_raster=True,
factor=error_factor, cols=cols,
option="frequency")
summery_count_raster = summery_SVG.get_raster_count_svg(cols, option="frequency")
legend = summery_SVG.count_legend
trans_legend = TransformBuilder()
trans_legend.setTranslation(605, 20)
legend.set_transform(trans_legend.getTransform())
summery_group.addElement(summery_count_raster)
summery_group.addElement(summery_error_raster)
summery_group.addElement(legend)
# Summery Intersection Raster
summery_intersection_raster = summery_SVG.get_raster_count_svg(cols, option="intersections")
summery_error_raster_for_intersections, height = summery_SVG.get_raw_error_vector_svg(as_raster=True,
factor=error_factor,
cols=cols,
option="intersections")
legend = summery_SVG.intersection_legend
trans_legend = TransformBuilder()
trans_legend.setTranslation(605, height + 20)
legend.set_transform(trans_legend.getTransform())
trans_intersction_raster = TransformBuilder()
trans_intersction_raster.setTranslation(0, height + 20)
summery_intersection_raster.set_transform(trans_intersction_raster.getTransform())
trans_summery_intersection = TransformBuilder()
trans_summery_intersection.setTranslation(0, height)
summery_error_raster_for_intersections.set_transform(trans_summery_intersection.getTransform())
summery_group.addElement(summery_intersection_raster)
summery_group.addElement(summery_error_raster_for_intersections)
summery_group.addElement(legend)
# Group Transformation
trans_raster = TransformBuilder()
trans_raster.setTranslation(700, 0)
summery_group.set_transform(trans_raster.getTransform())
s.addElement(summery_group)
totol_height = height
i = 1
for photo in self.photos:
svg_photo = SVG_Photo_Representation([photo])
photoSVG_group, group_height = svg_photo.get_raw_error_vector_svg(factor=error_factor)
# Group Transformation
trans = TransformBuilder()
trans.setTranslation(0, group_height * i)
photoSVG_group.set_transform(trans.getTransform())
s.addElement(photoSVG_group)
totol_height += group_height
i += 1
s.set_height(totol_height)
s.save(self.directory + '\\' + filename)
print('save file ', filename, ' to: ', self.directory)
class X_vector_element():
"""
container class for X-Vector (Parameter Vector) elements used in the adjustment
"""
paramerter_type_point = 'point'
paramerter_type_cam = 'cam'
value_type_X = 'X'
value_type_Y = 'Y'
value_type_Z = 'Z'
value_type_R = 'R'
def __init__(self, parameter_type, value_type, value, id_x):
self.value_type = value_type
self.parameter_type = parameter_type
self.value = value
self.id_x = id_x
def __str__(self):
if self.value_type == self.value_type_R:
return "{:s} {:s} :{:s} id:{:s}".format(self.parameter_type,
self.value_type,
str(self.value),
str(self.id_x))
else:
return "{:s} {:s} :{:.9f} id:{:s}".format(self.parameter_type,
self.value_type,
self.value,
str(self.id_x))
class L_vector_element():
"""
container class for L-Vector (measurement vector) elements used in the adjustment
"""
value_type_x = 'x'
value_type_y = 'y'
def __init__(self, cam_id, track_id, value_type, value, sigma):
self.cam_id = cam_id
self.track_id = track_id
self.value_type = value_type
self.value = value
self.sigma = sigma # standard deviation
def __str__(self):
return "{:s} track_id:{:d} value_type:{:s} value:{:.9f} sigam:{:.9f} ".format(self.cam_id,
self.track_id,
self.value_type,
self.value,
self.sigma)
class Peseudo_3D_intersection_adjustment():
"""
this class can calculate the jakobian matrix and the weight matrix and
the covarianzmatrix of the 3D Points
"""
measurment_x = 'x'
measurment_y = 'y'
rotation = 'R'
point_X = 'X'
point_Y = 'Y'
point_Z = 'Z'
cam_X = 'X_0'
cam_Y = 'Y_0'
cam_Z = 'Z_0'
def __init__(self, point_with_reference=None):
"""
:type point_with_reference: dict[int, list[I3_Photo]]
"""
self.points = point_with_reference
self.points_pos = {}
@staticmethod
def _get_eigen_vel_vec(m):
"""
return a tuble of eigenvalue and eigenvectro for a given Matrix using SVD
the eigenvalue are not sorted!!!
:param m: PhotoScan.Matrix
:rtype : (list[float],list[list[float]])
"""
rows, cols = m.size
m_list = []
for r in range(0, rows):
new_row_for_list = []
for col in list(m.row(r)):
new_row_for_list.append(col)
m_list.append(new_row_for_list)
s, v, d = svd.svd(m_list)
eigenvalues = v
eigenvector = s # PhotoScan.Matrix(s)
# sorted_indeces =sorted(range(len(eigenvalues)), key=lambda k: v[k])
return eigenvalues, eigenvector
def _get_eigvalues_eigvectors_pos_cov_for_track_id(self, track_id=None):
"""
returns a list of a tuple of Eigenvalue, Eigenvector and Position for
a track_id. if no id is passed it returns a list of all points
:type track_id: int
:param track_id: track_id or None. i
:rtype : (list[float],list[list[float]],list[float],list[list[float]])
"""
if track_id:
list_of_track_ids = [track_id]
else:
list_of_track_ids = self.points.keys()
return_list = []
for track_id in list_of_track_ids:
cov = self.get_cov_for_point(track_id)
eig_val, eig_vec = self._get_eigen_vel_vec(cov)
pos_vector = None
for point in self.points[track_id][0].points:
if point.track_id == track_id:
# pos_vector = point.coord_Chunk
pos_vector = point.coord_W
# pos_vector = self.points[track_id][0].points[track_id].coord_W
pos = [pos_vector.x, pos_vector.y, pos_vector.z]
return_list.append((eig_val, eig_vec, pos, cov))
return return_list
def get_cov_for_point(self, track_id):
"""
calculate the covarianze matrix for one point
:param track_id: id of a 3D Point
:return: 3x3 Cov-Matrix
:rtype : PhotoScan.Matrix
"""
jacobian_matrix, X_vector, L_vector = self.get_jacobian(track_id)
A = jacobian_matrix
P = self.__get_P_matrix(L_vector, 1)
N = A.t() * P * A
Qxx = N.inv()
return Qxx
@staticmethod
def __get_P_matrix(L_vector, sigma0=1):
"""
calculate the weight matrix for a given measurement vector and a sigma0
:type L_vector: list of L_vector_element
:param L_vector:
:param sigma0:
:return:
"""
# todo: wie kann ich sigma0 richtig bestimmen
K_ll_diag = []
for L_element in L_vector:
k_l = L_element.sigma ** 2
K_ll_diag.append(k_l)
K_ll = PhotoScan.Matrix.Diag(K_ll_diag)
Q_ll = 1 / sigma0 ** 2 * K_ll
# Invers is only allowd for 4x4 Matrix. Invers of diag-matrix is 1/A[i,i]
for i in range(0, Q_ll.size[0]):
Q_ll[i, i] = 1 / Q_ll[i, i]
P = Q_ll
return P
def get_jacobian(self, track_id, point_photo_reference=None):
"""
returns the jacobian matrix for one point
:param track_id:
:param point_photo_reference:
:return:
"""
if point_photo_reference is None:
point_photo_reference = self.points
photos = point_photo_reference[track_id]
X_vector = []
L_vectro = []
jacobian = []
for photo in photos:
""":type photo: I3_Photo"""
assert isinstance(photo, I3_Photo)
X_to_optimize = [self.point_X, self.point_Y, self.point_Z]
X_vector_for_cam = []
L_vector_for_cam = []
paramerter_type = X_vector_element.paramerter_type_cam
transform_Chunk2W = PhotoScan.app.document.chunk.transform.matrix
R_t = photo.photoScan_camera.transform
# etweder von links oder rechts
R_t = transform_Chunk2W * R_t
cam_center_x = R_t[0, 3]
cam_center_y = R_t[1, 3]
cam_center_z = R_t[2, 3]
# center_x = photo.photoScan_camera.transform *
R = PhotoScan.Matrix([[R_t[0, 0], R_t[0, 1], R_t[0, 2]],
[R_t[1, 0], R_t[1, 1], R_t[1, 2]],
[R_t[2, 0], R_t[2, 1], R_t[2, 2]]])
cam_R = X_vector_element(paramerter_type,
X_vector_element.value_type_R,
R,
photo.label)
cam_X = X_vector_element(paramerter_type, X_vector_element.value_type_X, cam_center_x,
photo.label)
cam_Y = X_vector_element(paramerter_type, X_vector_element.value_type_Y, cam_center_y,
photo.label)
cam_Z = X_vector_element(paramerter_type, X_vector_element.value_type_Z, cam_center_z,
photo.label)
X_vector_for_cam.extend([cam_X, cam_Y, cam_Z, cam_R])
# point = photo.points[0]
for point in photo.points:
if point.track_id == track_id:
#self.points_pos[track_id] = point.coord_Chunk
self.points_pos[track_id] = point.coord_W
paramerter_type = X_vector_element.paramerter_type_point
point_X = X_vector_element(paramerter_type, X_vector_element.value_type_X, point.coord_W.x,
track_id)
point_Y = X_vector_element(paramerter_type, X_vector_element.value_type_Y, point.coord_W.y,
track_id)
point_Z = X_vector_element(paramerter_type, X_vector_element.value_type_Z, point.coord_W.z,
track_id)
X_vector_for_cam.extend([point_X, point_Y, point_Z])
L_x = L_vector_element(photo.label, track_id, L_vector_element.value_type_x, point.measurement_C.x,
photo.sigma_C.x)
L_y = L_vector_element(photo.label, track_id, L_vector_element.value_type_y, point.measurement_C.y,
photo.sigma_C.y)
L_vector_for_cam.extend([L_x, L_y])
jacobian_row = self.get_jacobian_row_for_point(X_vector_for_cam,
L_vector_for_cam,
X_to_optimize)
X_vector.extend(X_vector_for_cam)
L_vectro.extend(L_vector_for_cam)
jacobian.extend(jacobian_row)
jacobian_matrix = PhotoScan.Matrix(jacobian)
return jacobian_matrix, X_vector, L_vectro
def get_jacobian_row_for_point(self, X_vector, L_vector, X_used):
"""
get the row of the jacobian for a specific parameter - measurement combination
see Luhmann page 244,308
:type X_vector: list of X_vector_element
:type L_vector: list of L_vector_element
:type X_used: list of str
:param X_vector: list of X_vector_element
:param L_vector: list of L_vector_element
:param X_used: list of str
:return:
"""
z = 1 # because all unprojected points has z=1
R = None
X_0 = None
Y_0 = None
Z_0 = None
X = None
Y = None
Z = None
for X_element in X_vector:
if X_element.parameter_type == X_element.paramerter_type_cam:
if X_element.value_type == X_element.value_type_R:
R = X_element.value
elif X_element.value_type == X_element.value_type_X:
X_0 = X_element.value
elif X_element.value_type == X_element.value_type_Y:
Y_0 = X_element.value
elif X_element.value_type == X_element.value_type_Z:
Z_0 = X_element.value
elif X_element.parameter_type == X_element.paramerter_type_point:
if X_element.value_type == X_element.value_type_X:
X = X_element.value
elif X_element.value_type == X_element.value_type_Y:
Y = X_element.value
elif X_element.value_type == X_element.value_type_Z:
Z = X_element.value
k_x = R[0, 0] * (X - X_0) + R[1, 0] * (Y - Y_0) + R[2, 0] * (Z - Z_0)
k_y = R[0, 1] * (X - X_0) + R[1, 1] * (Y - Y_0) + R[2, 1] * (Z - Z_0)
N = R[0, 2] * (X - X_0) + R[1, 2] * (Y - Y_0) + R[2, 2] * (Z - Z_0)
row_x = [None] * len(X_used) # row for x image measurement
row_y = [None] * len(X_used) # row for y image maesurement
for L in L_vector:
if L.value_type == L_vector_element.value_type_x:
for i, X in enumerate(X_used):
if X == self.point_X:
# df(x)/dX
row_x[i] = -(z / N ** 2) * (R[0, 2] * k_x - R[0, 0] * N)
if X == self.point_Y:
row_x[i] = -(z / N ** 2) * (R[1, 2] * k_x - R[1, 0] * N)
if X == self.point_Z:
row_x[i] = -(z / N ** 2) * (R[2, 2] * k_x - R[2, 0] * N)
elif L.value_type == L_vector_element.value_type_y:
for i, X in enumerate(X_used):
if X == self.point_X:
# df(x)/dX
row_y[i] = -(z / N ** 2) * (R[0, 2] * k_y - R[0, 1] * N)
if X == self.point_Y:
row_y[i] = -(z / N ** 2) * (R[1, 2] * k_y - R[1, 1] * N)
if X == self.point_Z:
row_y[i] = -(z / N ** 2) * (R[2, 2] * k_y - R[2, 1] * N)
jacobian = [row_x, row_y]
return jacobian
class Py_2_OpenScad():
"""
class with one method to draw a allipsoid in OpenScad
not used by now
"""
@classmethod
def errorEllipse_from_eig(cls, eigvector, eigvalue, position, factor=1):
"""
:rtype : str
:return : scad_string
:param eigvector: 3x3 list each column is a eigenvector
:param eigvalue: 1x3 list of eigenvalue. each corrensponding to the column in eigenvector
:param position: 1x3 list of x,y,z coordinates
:param factor: the scale factor
:type eigvector: list of float
:type eigvalue: list of float
:type position: list of float
:type factor: float
"""
sorted_indeces_descanding = sorted(range(len(eigvalue)), key=lambda k: eigvalue[k])[::-1]
sorted_eigenvalue = []
for sort_i in sorted_indeces_descanding:
sorted_eigenvalue.append(eigvalue[sort_i])
v1 = []
v2 = []
v3 = []
for row in eigvector:
v1.append(row[sorted_indeces_descanding[0]])
v2.append(row[sorted_indeces_descanding[1]])
v3.append(row[sorted_indeces_descanding[2]])
roh = 180 / math.pi
gamma = math.atan(v1[1] / v1[0]) * roh
len_x_ = math.sqrt(v1[0] ** 2 + v1[1] ** 2)
beta = math.atan(v1[2] / len_x_) * roh
alpha = -math.atan(v3[1] / v3[2]) * roh
scale = list(
map(lambda x: x / factor,
[sqrt(sorted_eigenvalue[0]), sqrt(sorted_eigenvalue[1]), sqrt(sorted_eigenvalue[2])]))
scad_string = "render(){"
scad_string += "translate([{:6.3f},{:6.3f},{:6.3f}])".format(position[0], position[1], position[2])
scad_string += "rotate([{:6.3f},{:6.3f},{:6.3f}])".format(alpha, beta, gamma)