-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathIcp.cpp
More file actions
2336 lines (1944 loc) · 81.2 KB
/
Icp.cpp
File metadata and controls
2336 lines (1944 loc) · 81.2 KB
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
#include "Icp.h"
#include <time.h>
#include <string.h>
#include <FL/Fl_Gl_Window.H>
#include <FL/gl.h>
#include <vtkTransformPolyDataFilter.h>
#include <vtkHomogeneousTransform.h>
#include <vtkLandmarkTransform.h>
#include <vtkPointData.h>
#include <vtkDataSetAttributes.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyData.h>
#include <vtkMath.h>
#include <vtkIdList.h>
#include <vtkSortDataArray.h>
#include <vtkArrayDataWriter.h>
#include <vtkArrayWriter.h>
#include <vtkDenseArray.h>
#include <queue>
#include "Struct.h"
#include "KDtree.h"
#include "LandmarksTransform.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vtkVertexGlyphFilter.h>
inline void vtkMatrix4x4MultiplyPoint(const double elem[16], const double in[4], double out[4])
{
double v1 = in[0];
double v2 = in[1];
double v3 = in[2];
double v4 = in[3];
out[0] = v1*elem[0] + v2*elem[1] + v3*elem[2] + v4*elem[3];
out[1] = v1*elem[4] + v2*elem[5] + v3*elem[6] + v4*elem[7];
out[2] = v1*elem[8] + v2*elem[9] + v3*elem[10] + v4*elem[11];
out[3] = v1*elem[12] + v2*elem[13] + v3*elem[14] + v4*elem[15];
}
inline void Transpose(const double inElements[16],
double outElements[16])
{
for (int i = 0; i < 4; i++)
{
for (int j = i; j < 4; j++)
{
double temp = inElements[4 * i + j];
outElements[4 * i + j] = inElements[4 * j + i];
outElements[4 * j + i] = temp;
}
}
}
inline void MultiplyPoint(const double elements[16],
const double in[4], double result[4])
{
::vtkMatrix4x4MultiplyPoint(elements, in, result);
}
inline void PointMultiply(const double elements[16],
const double in[4], double result[4])
{
double newElements[16];
::Transpose(elements, newElements);
::MultiplyPoint(newElements, in, result);
}
///si trop de parametre faire une structure icp pour stocker tous les parametres-----> idée!
ICP::ICP(OBJECT_MESH* SourceData, OBJECT_MESH* TargetData, CONTAINER_MESH Cont_Mesh, vtkFloatArray*loaded_parameter_list, vtkFloatArray* tabOfParameters, vtkFloatArray* tab_loadsave_parameter, vtkFloatArray *tabDisplay, int modeTransformation, bool existColor, bool bool_onlyMatching)
{
//////////////////////////////// RECUPERATION DES MAILLAGES SOURCE ET CIBLE
vtkSmartPointer<vtkPolyData> S = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPolyData> T = vtkSmartPointer<vtkPolyData>::New();
S->DeepCopy(SourceData);
T->DeepCopy(TargetData);
Cont_Mesh.Recover_PositionObject_in_PolyData(SourceData, S);
Cont_Mesh.Recover_PositionObject_in_PolyData(TargetData, T);
this->Source = SourceData;
this->Target = TargetData;
this->Cont_Mesh = Cont_Mesh;
// on reinitialise leurs deux matrices et leurs centres
Source->Mesh_init_Mat();
Target->Mesh_init_Mat();
Source->Compute_mean();
Target->Compute_mean();
///////////// RECUPERATION DES LANDMARKS
list_landmarks_source_test = vtkSmartPointer<vtkPoints>::New();
list_landmarks_source = vtkSmartPointer<vtkPoints>::New();
list_landmarks_target = vtkSmartPointer<vtkPoints>::New();
list_landmarks_init_source = vtkSmartPointer<vtkPoints>::New();
list_landmarks_init_target = vtkSmartPointer<vtkPoints>::New();
this->bool_onlyMatching = bool_onlyMatching;
if (!this->bool_onlyMatching){//mode recalage
Cont_Mesh.RecoverLandmarks(list_landmarks_init_source, list_landmarks_init_target);
numberOfLandmarks_Source = list_landmarks_init_target->GetNumberOfPoints();/// attention test
numberOfLandmarks_init = list_landmarks_init_target->GetNumberOfPoints();
vtkSmartPointer<vtkPoints> list_land_source = vtkSmartPointer<vtkPoints>::New();
for (int i = 0; i < numberOfLandmarks_init; i++){
list_land_source->InsertNextPoint(list_landmarks_init_source->GetPoint(i));
}
list_landmarks_init_source->DeepCopy(list_land_source);
}
else{
numberOfLandmarks_Source = 0;
numberOfLandmarks_init = 0;
}
/////////////////////////////////////////////// CONSTRUCTION DES ATTRIBUTS
////---------INITIALISATION DES LISTES DES POINTS
Target->Update(T->GetPoints());
Source->Update(S->GetPoints());
numberOfPoints_Source = Source->GetPoints()->GetNumberOfPoints();
/// creation de la liste des sommets source d'origine (point+normale)
list_vertice_init_source = vtkSmartPointer<vtkFloatArray>::New();
list_vertice_init_source->SetNumberOfComponents(7);
vtkSmartPointer<vtkFloatArray> vertice_norms = vtkSmartPointer<vtkFloatArray>::New();
vertice_norms = vtkFloatArray::SafeDownCast(Source->GetPointData()->GetNormals());
double tuple[7];
for (int i = 0; i < Source->GetNumberOfPoints(); i++){
for (int j = 0; j < 3; j++){
tuple[j] = Source->GetPoint(i)[j];
tuple[j + 3] = vertice_norms->GetComponent(i, j);
}
tuple[6] = i;
list_vertice_init_source->InsertNextTuple(tuple);
}
///---------------------
///----- INITIALISATION DE LA LISTE DES PARAMETRES
this->bool_save_parameters = tab_loadsave_parameter->GetTuple1(0);//bool pour enregistrer les paramètres
this->bool_loaded_parameters = tab_loadsave_parameter->GetTuple1(1);//bool pour enregistrer les paramètres
parameter_list = vtkSmartPointer<vtkFloatArray>::New();
parameter_list->SetNumberOfComponents(12);
parameter_list->SetNumberOfTuples(4);
vtkSmartPointer<vtkIdList> modeList_toDo = vtkSmartPointer<vtkIdList>::New();
modeList_toDo->DeepCopy(SetOfLoadedParameters(loaded_parameter_list, tabOfParameters, modeTransformation));
/////--- NETTOYAGE DES COURBURES: MODIFIE LES VALEURS TROP GRANDES OU TROP PETITES
percentageCurv = tabOfParameters->GetTuple1(9);// pourcentage pour les courbures
Target->Sort_Curv_ICP("Maximum_Curvature", percentageCurv / 2.0f);
Target->Sort_Curv_ICP("Minimum_Curvature", percentageCurv / 2.0f);
Source->Sort_Curv_ICP("Maximum_Curvature", percentageCurv / 2.0f);
Source->Sort_Curv_ICP("Minimum_Curvature", percentageCurv / 2.0f);
//--------- CONSTRUCTION DES ALPHA POUR LA RECHERCHE DANS LE KDTREE
double Pointmin_max[6];
double norPointmin_max[6];
double curvMinMax[8];// taille = 8 car la fonction "find_minMax_CoordofCurv" est generale pour toutes les courbures
/// on cherche les maximums et minimums de chaque coordonnée
Target->Find_minMax_CoordofPoint_Normal(Pointmin_max, norPointmin_max);
Target->Find_minMax_CoordofCurv(curvMinMax);
///---- CONSTRUCTION DES LISTES DES ERREURS ET DU TEMPS DE CALCUL ET LE SEUIL DES ERREURS
errors = vtkSmartPointer<vtkFloatArray>::New();
errors->SetNumberOfComponents(5);
number_errors = 0;
time = vtkSmartPointer<vtkFloatArray>::New();
time->SetNumberOfComponents(4);
threshold = new float[2];
threshold[0] = tabOfParameters->GetTuple1(6);//ite_max
threshold[1] = tabOfParameters->GetTuple1(7);// seuil pourcentage
tab_weights = vtkSmartPointer<vtkFloatArray>::New();
IndexSphere_i_Source = vtkSmartPointer<vtkFloatArray>::New();
list_landmarks_dimN_target_LA = vtkSmartPointer<vtkFloatArray>::New();
///----- INITIALISATION DES PARAMETRES
mode_transformation = -1;//En mode 'step by step', on commence par rigide par défaut
weight_vertice_addland = -1;
weight_land_addland = -1;
dec = 1; //dec par defaut
cpt_mode = 0; // 0 si utilisation des landmarks et 1 si utilisation des points source et du kdtree
dim_points = 4; /// (coord points + indice)
percentageRadius_of_sphere_LA = tabOfParameters->GetTuple1(8);
this->existColor = existColor;// les tags existent sur les deux maillages
bool_tags = (tabOfParameters->GetTuple1(2) != -1 && existColor);
Compute_dim_of_points(tabOfParameters); /// calcule les parametres et les dimension des points
Init_alpha_tab(Pointmin_max, norPointmin_max, curvMinMax);// construction des alpha pour le KDtree
///----- INITIALISATION DE LA COULEUR ET TABLEAU D'AFFICHAGE DES CORRESPONDANCES
tab_display = vtkSmartPointer<vtkFloatArray>::New();
tab_display->SetNumberOfComponents(1);
tab_display->SetNumberOfTuples(4);
tab_display->DeepCopy(tabDisplay);
vect_matching_color[0] = 0.f; // couleur des correspondances par défaut
vect_matching_color[1] = 0.5f;
vect_matching_color[2] = 1.f;
///--------INITIALISATION DES POIDS POUR LES CORRESPONDANCES
weights = vtkSmartPointer<vtkFloatArray>::New();
weights->SetNumberOfComponents(1);
weights->SetNumberOfValues(numberOfLandmarks_Source);
//-------- CONSTRUCTION DES POINTS A N DIMENSIONS
list_landmarks_dimN_source = vtkSmartPointer<vtkFloatArray>::New();
list_landmarks_dimN_source->SetNumberOfComponents(dim_points);
list_landmarks_dimN_source->SetNumberOfTuples(Source->GetNumberOfPoints());
list_landmarks_dimN_target = vtkSmartPointer<vtkFloatArray>::New();
list_landmarks_dimN_target->SetNumberOfComponents(dim_points);
list_landmarks_dimN_target->SetNumberOfTuples(Target->GetNumberOfPoints());
Initialisation_of_points_ofDimN(Source, list_landmarks_dimN_source);
Initialisation_of_points_ofDimN(Target, list_landmarks_dimN_target);
/////-------- CONSTRUCTION DU KDTREE POUR DES POINTS A N DIMENSIONS
cout << " color? :: " << bool_tags << endl;
clock_t debut;
debut = clock();
tree = new KDtree(list_landmarks_dimN_target, bool_tags);// on met comme indice la couleur si elle existe pour ne pas l'avoir dans la construction du kdtree (qu'elle est un axe)
cout << "------- Temps consomme : " << ((double)(clock() - debut) / CLOCKS_PER_SEC) << endl;
/*debut = clock(); // a enlever
test = new KDtree1(list_landmarks_dimN_target, bool_tags);
cout << "------- Temps consomme : " << ((double)(clock() - debut) / CLOCKS_PER_SEC) << endl;
*/
//------- DEMARRAGE DE L'ICP
if (!this->bool_onlyMatching){
BeginICP(tabOfParameters, tab_loadsave_parameter, modeTransformation, tabDisplay, modeList_toDo);
}
else{
OnlyMatching();
}
}
// on calcule seulement les correspondances entre source et cible
void ICP::OnlyMatching(){
list_landmarks_source->Reset();
for (int i = 0; i < numberOfPoints_Source; i++){
if (i%dec == 0){
list_landmarks_source->InsertNextPoint(Source->GetPoint(i));
}
}
numberOfLandmarks_Source = list_landmarks_source->GetNumberOfPoints();
list_landmarks_dimN_source = vtkSmartPointer<vtkFloatArray>::New();
list_landmarks_dimN_source->SetNumberOfComponents(dim_points);
list_landmarks_dimN_source->SetNumberOfTuples(numberOfLandmarks_Source);
Initialisation_of_points_ofDimN(Source, list_landmarks_dimN_source);
list_landmarks_dimN_target = vtkSmartPointer<vtkFloatArray>::New();
list_landmarks_dimN_target->SetNumberOfComponents(dim_points);
list_landmarks_dimN_target->SetNumberOfTuples(list_landmarks_dimN_source->GetNumberOfTuples());
Pairs_matching(list_landmarks_dimN_source, list_landmarks_dimN_target);
}
// debut de l'ICP
void ICP::BeginICP(vtkSmartPointer<vtkFloatArray> tabOfParameters, vtkFloatArray* tab_loadsave_parameter, int modeTransformation, vtkSmartPointer<vtkFloatArray> tabDisplay, vtkSmartPointer<vtkIdList> modeList_toDo){
cout << "+++++++ DEBUT ICP ++++++" << endl;
// on recupere les parametres si on a charge un fichier sinon c'est ceux de l'interface
if (!bool_loaded_parameters)
SetData(tabOfParameters, modeTransformation, tabDisplay, tab_loadsave_parameter);
else{
for (int i = 0; i <modeList_toDo->GetNumberOfIds(); i++){
SetData(tabOfParameters, modeList_toDo->GetId(i), tabDisplay, tab_loadsave_parameter);
}
bool_loaded_parameters = false;
}
}
vtkSmartPointer<vtkIdList> ICP::SetOfLoadedParameters(vtkSmartPointer<vtkFloatArray> loaded_parameter_list, vtkSmartPointer<vtkFloatArray> tabOfParameters, int modeTransformation){
vtkSmartPointer<vtkIdList> modeList_toDo = vtkSmartPointer<vtkIdList>::New();
if (!bool_loaded_parameters){// si on n'a pas chargé les parametres d'un fichier
for (int i = 0; i < 4; i++){
float tuple_parameter[12] = { 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
parameter_list->SetTuple(i, tuple_parameter);
}
}
else{/// si on a chargé des parametres d'un fichier
parameter_list->DeepCopy(loaded_parameter_list);
Analyse_Loaded_Parameter_list(modeList_toDo);
modeTransformation = modeList_toDo->GetId(0);
SetTabOfParameter(tabOfParameters, modeList_toDo->GetId(0));//Mise en jour de tabofparameters
}
return modeList_toDo;
}
void ICP::Analyse_Loaded_Parameter_list(vtkIdList* modeList_toDo){
//cette fonction permet de savoir les modes qui ont été fait
// et de désigner le mode final à executer sachant que
//similitude , affine , localement affine sont dépendant les uns des autres;
//Excepté pour le mode rigide.
if (1 == parameter_list->GetComponent(0, 0))
modeList_toDo->InsertNextId(-1);
if (1 == parameter_list->GetComponent(1, 0) && 1 != parameter_list->GetComponent(2, 0) && 1 != parameter_list->GetComponent(3, 0))
modeList_toDo->InsertNextId(SIMILITUDE);
if (1 == parameter_list->GetComponent(1, 0) && 1 == parameter_list->GetComponent(2, 0) && 1!=parameter_list->GetComponent(3, 0))
modeList_toDo->InsertNextId(AFFINE);
if (1 == parameter_list->GetComponent(1, 0) && 1 == parameter_list->GetComponent(2, 0) && 1 == parameter_list->GetComponent(3, 0))
modeList_toDo->InsertNextId(LOC_AFFINE);
}
void ICP::SetTabOfParameter(vtkSmartPointer<vtkFloatArray>tabOfParameters, int modeTransformation){
// on recupère pour chaque mode leurs parametres du fichier chargé dans la variable "tabOfParameters"
int index = 0;
if (modeTransformation == -1)
index = 0;
else if (modeTransformation == SIMILITUDE)
index = 1;
else if (modeTransformation == AFFINE)
index = 2;
else if (modeTransformation == LOC_AFFINE)
index = 3;
double *tuple = parameter_list->GetTuple(index);
for (int i = 0; i < parameter_list->GetNumberOfComponents(); i++){
tabOfParameters->SetTuple1(i, tuple[i + 2]);
}
//affiche(tuple,11);
}
void ICP::StoreParameters(){
//Stocke les parametres de chaque mode
if (bool_save_parameters){
int index;
if (mode_transformation == RIGID)
index = 0;
else if (mode_transformation == SIMILITUDE)
index = 1;
else if (mode_transformation == AFFINE)
index = 2;
else if (mode_transformation == LOC_AFFINE)
index = 3;
cout << "Store parameters " << index << endl;
double tuple[12] = { 1, mode_transformation, tab_weights->GetTuple1(0), tab_weights->GetTuple1(1), tab_weights->GetTuple1(2), tab_weights->GetTuple1(3), dec, percentRadius_filter, threshold[0], threshold[1], percentageRadius_of_sphere_LA, percentageCurv };
parameter_list->SetTuple(index, tuple);
//affiche(tuple, 12);
}
}
void ICP::Init_alpha_tab(double Pointmin_max[6], double norPointmin_max[6], double curvMinMax[8]){
// Calcule les alpha permettant à normaliser les coordonnées des points dans le kdtree
Init_alpha_of_coord(Pointmin_max,norPointmin_max);
Init_alpha_of_curv(curvMinMax);
if (tab_weights->GetTuple1(1) != -1 && tab_weights->GetTuple1(0) == -1)
//si dim_points a coordonnée du points et les courbures mais pas les coordonnées des normales
{
alpha[3] = alpha[6];
alpha[4] = alpha[7];
}
/*cout << endl;
affiche(alpha, 8);*/
}
void ICP::Init_alpha_of_coord(double Pointmin_max[6], double norPointmin_max[6]){
// cette fonction calcule les alpha des coordonnées des points et des normales pour le kdtree
double PXmax = Pointmin_max[3];
double PXmin = Pointmin_max[0];
double PYmax = Pointmin_max[4];
double PYmin = Pointmin_max[1];
double PZmax = Pointmin_max[5];
double PZmin = Pointmin_max[2];
double NorXPmax = norPointmin_max[3];
double NorXPmin = norPointmin_max[0];
double NorYPmax = norPointmin_max[4];
double NorYPmin =norPointmin_max[1];
double NorZPmax = norPointmin_max[5];
double NorZPmin = norPointmin_max[2];
float coorp = max(max((PXmax - PXmin), (PYmax - PYmin)), (PZmax - PZmin));
float norcoodp = max(max((NorXPmax - NorXPmin), (NorYPmax - NorYPmin)), (NorZPmax - NorZPmin));
alpha[0] = 1.f / coorp;
alpha[1] = 1.f / coorp ;// point
alpha[2] = 1.f / coorp ;//point
alpha[3] = 1.f / norcoodp;
alpha[4] = 1.f / norcoodp;//normale
alpha[5] = 1.f / norcoodp;//normale
////// premiere idée
//// on cherche le min des minimums entre chaque coordonnée du point puis celle de la normale
//// de même pour la maximum
//double Pmax = max(max(Pointmin_max[3], Pointmin_max[4]), Pointmin_max[5]);
//double Pmin = min(min(Pointmin_max[0], Pointmin_max[1]), Pointmin_max[2]);
//double NorPmax = max(max(norPointmin_max[3], norPointmin_max[4]), norPointmin_max[5]);
//double NorPmin = min(min(norPointmin_max[0], norPointmin_max[1]), norPointmin_max[2]);
//
//alpha[0] = 1.f/(Pmax - Pmin);
//alpha[3] = 1.f/(NorPmax - NorPmin);
//alpha[1] = alpha[0];// point
//alpha[2] = alpha[0];//point
//alpha[4] = alpha[3];//normale
//alpha[5] = alpha[3];//normale
/////idée de l'article Fedmar
//double PXmax = Pointmin_max[3];
//double PXmin = Pointmin_max[0];
//double PYmax = Pointmin_max[4];
//double PYmin = Pointmin_max[1];
//double PZmax = Pointmin_max[5];
//double PZmin = Pointmin_max[2];
//double NorXPmax = norPointmin_max[3];
//double NorXPmin = norPointmin_max[0];
//double NorYPmax = norPointmin_max[4];
//double NorYPmin =norPointmin_max[1];
//double NorZPmax = norPointmin_max[5];
//double NorZPmin = norPointmin_max[2];
//
//alpha[0] = 1.f / (PXmax - PXmin);
//alpha[1] = 1.f / (PYmax - PYmin);// point
//alpha[2] = 1.f / (PZmax - PZmin);//point
//alpha[3] = 1.f / (NorXPmax - NorXPmin);
//alpha[4] = 1.f / (NorYPmax - NorYPmin);//normale
//alpha[5] = 1.f / (NorZPmax - NorZPmin);//normale
}
void ICP::Init_alpha_of_curv(double curvMinMax[8]){
// on cherche les min et les max des deux coubures principales
// curv1 = courbure du maximum et curv2 = coubure du minimum
int index1 = 0, index2 = 0;
bool bool_curv = (tab_weights->GetTuple1(1) != -1);
double curv1Min, curv2Min;
double curv1Max, curv2Max;
double curv1_val = -1;
double curv2_val = -1;
if (bool_curv){
index1 = 0; // index1 pour la courbure min
index2 = 1;// index2 pour la courbure max
// les autres index sont pour les autres courbures(moyenne et gaussienne)
curv1Min = curvMinMax[index1];
curv1Max = curvMinMax[index1 + 4];
curv2Min = curvMinMax[index2];
curv2Max = curvMinMax[index2 + 4];
curv1_val = 1.f / (curv1Max - curv1Min);
curv2_val = 1.f / (curv2Max - curv2Min);
}
alpha[6] = curv1_val;
alpha[7] = curv2_val;
}
void ICP::Compute_dim_of_points(vtkFloatArray* tabOfParameters){
// cette fonction va recupèrer et/ou calculer pour la plus part des elements
//du tableau (la dimension des points, le diviseur du nombre de points, le pourcentage du
//rayon pour le filtre,
// le poids des landmarks si ajouté avec les vertices).
///---CONSTRUCTION DU TABLEAU DES POIDS CONSTANTS pour le kdtree (recuperer de l'interface)
tab_weights->Reset();
tab_weights->SetNumberOfComponents(1);
dim_points = 4; /// par defaut on a au début que les coordonnées des points + son indice
dec_user = tabOfParameters->GetTuple(4)[0]; // le diviseur "dec" choisi par utilisateur
percentRadius_filter = tabOfParameters->GetTuple(5)[0];// le pourcentage du rayon pour le filtre
// Normale
float weight_normale = -1;
if (tabOfParameters->GetTuple1(0) != -1){
weight_normale = tabOfParameters->GetTuple1(0);
dim_points += 3;
}
//Courbure
float weight_curv = -1;
if (tabOfParameters->GetTuple1(1) != -1) {
dim_points += 2;
weight_curv = tabOfParameters->GetTuple1(1);
}
//Couleur
float weight_color = -1;
if (bool_tags) {
dim_points+=1;
weight_color=tabOfParameters->GetTuple1(2);
}
// Si on a les landmarks en plus des vertices
bool_landmarks_add = false;
weight_vertice_addland = -1;
weight_land_addland = -1;
if (tabOfParameters->GetTuple1(3) != -1){
bool_landmarks_add = true;
int div;
if (dec_user != -1)
div = dec_user;
else
div = numberOfPoints_Source / MAX_NUMBER_OF_POINTS;
// on calcule les poids des landmarks ajoutés
int numberVertice = numberOfPoints_Source / div;
weight_land_addland = tabOfParameters->GetTuple1(3) * numberVertice;
weight_vertice_addland = 1;
if (weight_land_addland == numberVertice){
// si on a le même poids (1) alors on prends que les landmarks.
weight_vertice_addland = 0;
weight_land_addland = 1;
}
}
tab_weights->InsertNextTuple1(weight_normale); /// 0 --- normale
tab_weights->InsertNextTuple1(weight_curv); /// 1 --- courbure
tab_weights->InsertNextTuple1(weight_color); /// 2 --- couleur
tab_weights->InsertNextTuple1(weight_land_addland); /// 3 --- landmarks
/*cout << " tab_weights" << endl;
for (int i = 0; i < 4; i++){
cout << tab_weights->GetTuple1(i)<<" ";
}
cout << endl;*/
}
void ICP::Initialisation_of_points_ofDimN(OBJECT_MESH *object, vtkSmartPointer<vtkFloatArray> list_landmarks_dimN_object){
// ici on recupere les normales, courbures, et la couleur pour chaque point de l'object
///------------ RECUPERATION DES NORMALES
vtkSmartPointer<vtkFloatArray> object_norms = vtkSmartPointer<vtkFloatArray>::New();
bool bool_norm = (tab_weights->GetTuple1(0) != -1);
if (bool_norm){
object_norms->DeepCopy(vtkFloatArray::SafeDownCast(object->GetPointData()->GetNormals()));
}
///------------- RECUPERATION COURBURE
vtkFloatArray *currentCurv1= vtkFloatArray::New();
currentCurv1->SetNumberOfComponents(1);
vtkFloatArray *currentCurv2 = vtkFloatArray::New();
currentCurv2->SetNumberOfComponents(1);
bool bool_curv = (tab_weights->GetTuple1(1) != -1);
if (bool_curv){
currentCurv1->DeepCopy(vtkFloatArray::SafeDownCast(object->GetPointData()->GetScalars("Maximum_Curvature")));
currentCurv2->DeepCopy(vtkFloatArray::SafeDownCast(object->GetPointData()->GetScalars("Minimum_Curvature")));
}
///------------- RECUPERATION COULEUR
vtkFloatArray *currentTags = vtkFloatArray::New();
currentTags->SetNumberOfComponents(1);
if (bool_tags){
currentTags->DeepCopy((vtkFloatArray*)(object->GetPointData()->GetScalars("Tags")));
}
int i1 = 0;
float val = 0;
list_landmarks_dimN_object->Reset();
list_landmarks_dimN_object->SetNumberOfComponents(dim_points);
list_landmarks_dimN_object->SetNumberOfTuples((int)(object->GetNumberOfPoints() / dec));
for (int i = 0; i < object->GetNumberOfPoints(); i++){
if (i%dec == 0){
for (int j = 0; j < dim_points-1; j++){
if (j < 3){// Point
val = object->GetPoint(i)[j];
}
else if (3 <= j && j < 6){// Normale
if (bool_norm)
val = object_norms->GetComponent(i, j - 3);
else if (!bool_norm && (j == 3 || j == 4)){
if (j == 3){
if (bool_curv){
val = currentCurv1->GetComponent(i, 0);// Courbure max
}
else if (bool_tags && !bool_curv)
val = currentTags->GetComponent(i, 0); // Couleur
}
else if (j == 4){
val = currentCurv2->GetComponent(i, 0);// Coubure min
}
}
else if (!bool_norm && bool_curv && j == 5){// Couleur
if (bool_tags)
val = currentTags->GetComponent(i, 0);
}
}
else if (j == 6 || j == 7){// Courbure min et max
if (j == 6){
if (bool_curv){
val = currentCurv1->GetComponent(i, 0);// Courbure max
}
else if (bool_tags && !bool_curv)
val = currentTags->GetComponent(i, 0); // Couleur
}
else if (j == 7){
val = currentCurv2->GetComponent(i, 0);// Coubure min
}
}
else if (j == 8){// Couleur
if (bool_tags)
val = currentTags->GetComponent(i, 0);
}
list_landmarks_dimN_object->SetComponent(i1, j, val);
}//for
list_landmarks_dimN_object->SetComponent(i1, dim_points - 1, i1);
i1++;
}//if
}//for
currentCurv1->Delete();
currentCurv2->Delete();
currentTags->Delete();
}
//Destructeur
ICP::~ICP(){
}
// ICP iteration
void ICP::Iteration()
{
// On a deux sortes d'itération : l'une pour Rigide, Similitude et Affine (R_S_A)
// et l'autre pour le Localement Affine (LA)
if (mode_transformation != LOC_AFFINE)
IterationFor_R_S_A();
else{
IterationFor_LA();
}
}
// ICP iteration pour Rigide, Similitude et Affine
void ICP::IterationFor_R_S_A()
{
icp_cpt_mode = 0;
float error_trans = 1;
float err = 0, cpt_err_mode = 0;
int MaxIte = threshold[0];
float MaxErrorPercentage = threshold[1];
vtkSmartPointer<vtkPoints> list_filter_source = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkPoints> list_filter_target = vtkSmartPointer<vtkPoints>::New();
while ((abs(error_trans) > MaxErrorPercentage) && icp_cpt_mode < MaxIte && problem == 0){
cout << " \n\t*********** ITE **** NUMBER ******** " << icp_cpt_mode << endl;
weights->Reset();
weights->SetNumberOfComponents(1);
weights->SetNumberOfTuples(numberOfLandmarks_Source);
list_filter_source->Reset();
list_filter_target->Reset();
//on cherche à construire les correspondances
Pairs_matching(list_landmarks_dimN_source,list_landmarks_dimN_target);
//on filtre les correspondances trouvées à partir des données que l'utilisateur a selectionné
Filter(list_filter_source, list_filter_target);
if (problem == 1) //on arrete la boucle si le filtre ne donne pas de correspondances
break;
//on calcule la transformation à partir des correspondances et mise à jour de la source
Transformation(list_filter_source, list_filter_target);
// recuperation des erreurs
if (number_errors != 0){
//on prends le dernier indice
vtkIdType lastId = number_errors - 1;
cpt_err_mode++; /// à voir si on peut mettre "icp_cpt_mode" à la place de "cpt_err_mode"
cout << "erreur " << errors->GetComponent(lastId, 0) << " " << errors->GetComponent(lastId, 1) << " " << errors->GetComponent(lastId, 2) << " " << errors->GetComponent(lastId, 3) << endl;
if (cpt_err_mode == 1){//pour la premiere iteration on prend l'erreur lui meme
error_trans = errors->GetComponent(lastId, 1);// on prend sur les erreurs de la liste des correspondance source (landmark/vertice)
cout << "erreur1 de distance entre les points ::::: " << error_trans << endl;
}
else if (cpt_err_mode >= 2){//sinon on calcule un pourcentage d'erreur entre l'erreur precedante et courante
error_trans = abs(errors->GetComponent(lastId, 1) - errors->GetComponent(lastId - 1, 1) ) / errors->GetComponent(lastId - 1, 1);
cout << "erreur de distance pred ::::: " << error_trans << endl;
}
}
icp_cpt_mode++;
}
//Mise a jour des positions des landmarks
Cont_Mesh.Set_List_of_SourceLandmarks_Coordinates(list_landmarks_init_source);
}
// ICP iteration pour Localement affine
void ICP::IterationFor_LA(int radius){
sphere_Set* sphereList = new sphere_Set[numberOfPoints_Source];
IndexSphere_i_Source->Reset();
IndexSphere_i_Source->SetNumberOfComponents(1);
vtkSmartPointer<vtkPoints> new_list_source = vtkSmartPointer<vtkPoints>::New();
new_list_source->SetNumberOfPoints(numberOfPoints_Source);
UpdateCurvObject(Source, Source->GetPoints());
icp_cpt_mode = 0;
float error_trans = 1;
float cpt_err_mode = 0;
// calcule le rayon
float R = 1.;
float diameter = 2 * Source->object_radius;
if (percentageRadius_of_sphere_LA <= 0)
percentageRadius_of_sphere_LA = ((float)radius);
R = percentageRadius_of_sphere_LA / 100. *diameter;
cout << "rrayon " << R << endl;
//recupère les seuils d'arret
int MaxIte = threshold[0];
float MaxErrorPercentage = threshold[1];// *2 * Target->object_radius / 100.;
/// pretraitement des spheres pour chaque point Mk
numberOfLandmarks_Source = numberOfPoints_Source;
dec = 1;
Initialisation_of_points_ofDimN(Source, list_landmarks_dimN_source);
list_landmarks_source->Reset();
list_landmarks_source->SetNumberOfPoints(numberOfPoints_Source);
list_landmarks_target->Reset();
list_landmarks_target->SetNumberOfPoints(numberOfPoints_Source);
Build_SphereSetKDtree(sphereList, R);
matriX* matrix_list = new matriX[numberOfPoints_Source];
float err = 0;
/// LES ITERATIONS
while ((abs(error_trans) > MaxErrorPercentage) && icp_cpt_mode < MaxIte && problem == 0){//MaxIte
cout << " \n\t*********** ITE **** NUMBER ******** " << icp_cpt_mode << endl;
// reinitialisation du KDtree source
clock_t debut;
debut = clock();
err = 0;
//---- ON CALCULE LES POINTS PLUS PROCHE ET LEUR TRANSFORMATION RIGIDE
list_landmarks_dimN_target_LA->Reset();
list_landmarks_dimN_target_LA->SetNumberOfComponents(list_landmarks_dimN_source->GetNumberOfComponents());
list_landmarks_dimN_target_LA->SetNumberOfTuples(list_landmarks_dimN_source->GetNumberOfTuples());
Pairs_matching(list_landmarks_dimN_source, list_landmarks_dimN_target_LA);
/// filtrer ici selon la couleur si besoin
clock_t debutMatrice;
debutMatrice = clock();
// liste des matrices
Build_matrixlist(matrix_list, sphereList);
// liste des nouveaux points
new_list_source->Reset();
Build_LA_transformation(matrix_list, sphereList, new_list_source, &err);
double res_timeMatrice = (double)(clock() - debutMatrice) / CLOCKS_PER_SEC;
cout << "Temps ::: Compute Matrice Affine :: " << res_timeMatrice << " sec. " << endl;
cout << "yyy"<<problem;
if (problem==0)
list_landmarks_source->DeepCopy(new_list_source);
if (problem != 0){
fl_alert("ERROR : Radius is too small %f", R);
break;
}
// time
double res_time = (double)(clock() - debut) / CLOCKS_PER_SEC;
cout << "Temps iteration LA : " << res_time << " " << endl;
if (problem == 0){
//Calcule l'erreur de l'iteration pour le même mode
error_trans = err / (float)(numberOfPoints_Source);
double errors_tuple[5] = { mode_transformation, error_trans, -1, -1, cpt_mode };// a voir pour les landmarks et total
errors->InsertNextTuple(errors_tuple);
number_errors++;
vtkIdType lastId = number_errors - 1;
cpt_err_mode++;
cout << "erreur " << errors->GetComponent(lastId, 0) << " " << errors->GetComponent(lastId, 1) << " " << errors->GetComponent(lastId, 2) << " " << errors->GetComponent(lastId, 3) << endl;
if (cpt_err_mode == 1){
error_trans = errors->GetComponent(lastId, 1);// on prend sur les erreurs de la liste des correspondance source (landmark/vertice)
cout << "erreur1 de distance entre les points ::::: " << error_trans << endl;
}
else if (cpt_err_mode >= 2){
error_trans = abs(errors->GetComponent(lastId, 1) - errors->GetComponent(lastId - 1, 1)) / errors->GetComponent(lastId - 1, 1);
cout << "erreur de distance pred ::::: " << error_trans << endl;
}
UpdateCurvObject(Source, new_list_source);
Initialisation_of_points_ofDimN(Source, list_landmarks_dimN_source);
}
icp_cpt_mode++;
}// fin while
if (problem == 0){// on fait les correspondances
list_landmarks_dimN_target_LA->Reset();
list_landmarks_dimN_target_LA->SetNumberOfComponents(dim_points);
list_landmarks_dimN_target_LA->SetNumberOfTuples(list_landmarks_dimN_source->GetNumberOfTuples());
Pairs_matching(list_landmarks_dimN_source, list_landmarks_dimN_target_LA);// dim N
// filtrer ici aussi
}
cout << "mmmm" << endl;
//free(matrix_list);
cout << "Finish LA " << endl;
}
//void ICP::Build_SphereSet(sphere_Set* sphereList, float R){
// if (bool_kdtree_LA){ // a mettre dans constructeur et fichier des paramètres et updata
// Build_SphereSetKDtree(sphereList,R);
// }
// else{
// Build_SphereSet_Neighbord(sphereList, R);
// }
//}
// Construit les ensembles de sphere(Mk)
void ICP::Build_SphereSetKDtree(sphere_Set* sphereList, float R){
cout << "construction du kdtree et de l'ensemble de sphere en cours" << endl;
vtkSmartPointer<vtkFloatArray> list_landmarks_dimN_source_addIndex = vtkSmartPointer<vtkFloatArray>::New();
list_landmarks_dimN_source_addIndex->SetNumberOfComponents(4);// point 3D + 1 pour l'indice
list_landmarks_dimN_source_addIndex->SetNumberOfTuples(numberOfPoints_Source);
for (int i = 0; i < numberOfPoints_Source; i++){
double tuple[4] = { Source->GetPoint(i)[0], Source->GetPoint(i)[1], Source->GetPoint(i)[2], i };
list_landmarks_dimN_source_addIndex->SetTuple(i, tuple);
list_landmarks_source->SetPoint(i, tuple[0], tuple[1], tuple[2]);
}
clock_t debutKDt;
debutKDt = clock();
///-----------KDTREE
cout << "KDtree Source" << endl;
KDtree sourceTree(list_landmarks_dimN_source_addIndex, 0); // kdtree avec des points (coordonnée 3D + indice)
cout << "fait" << endl;
//----------
// time
double res_timeKDt = (double)(clock() - debutKDt) / CLOCKS_PER_SEC;
cout << "Temps KDtree ::: " << res_timeKDt << " " << endl;
clock_t debutSPhere;
debutSPhere = clock();
//----------------SPHERE
cout << "Construction des Spheres: ";
for (int i = 0; i < numberOfPoints_Source && problem == 0; i++){
double point_3dim[3] = { Source->GetPoint(i)[0], Source->GetPoint(i)[1], Source->GetPoint(i)[2] };
// on recupère tous les indices des points Ml dans un rayon R
IndexSphere_i_Source->Reset();// = vtkSmartPointer<vtkFloatArray>::New();
IndexSphere_i_Source->SetNumberOfComponents(1);
IndexSphere_i_Source = sourceTree.PointsInRadius(point_3dim, R);
if (IndexSphere_i_Source->GetNumberOfTuples() == 0){
// cout << "ii " << i << endl;
problem += 2; //si on le remet à mettre dans parametre
fl_alert("ERROR: the sphere radius for the transformation mode LOC_AFFINE\n is too small , radius = %f (chosen percentage : %f %)", R, percentageRadius_of_sphere_LA);
break;// à tester par sure que cela marche
}
else{
sphereList[i].list = vtkSmartPointer<vtkFloatArray>::New();
sphereList[i].list->SetNumberOfComponents(1);
sphereList[i].list->DeepCopy(IndexSphere_i_Source);
}
}
cout << "fait" << endl;
double res_timeSphere = (double)(clock() - debutSPhere) / CLOCKS_PER_SEC;
cout << "Temps:: Sphere :: " << res_timeSphere << " " << endl;
}
//void ICP::Build_SphereSet_Neighbord(sphere_Set* sphereList, float R){
// cout << "Neighbord" << endl;
// Source->Find_Tab_of_neighborhood();
// cout << "l" << endl;
// Source->Compute_mean_of_edge();
// cout << "mean " << Source->mean_arr << endl;
// cout << "yyynei" << endl;
//
// queue<pair<float, float>> to_do;
// cout << "rrr" << endl;
//
// vtkSmartPointer<vtkPoints> list = vtkSmartPointer<vtkPoints>::New();
// list->DeepCopy(Source->GetPoints());
// vtkSmartPointer<vtkPoints> list1 = vtkSmartPointer<vtkPoints>::New();
// list1->DeepCopy(Source->GetPoints());
//
// //int i = 0;
// for (int i = 0; i < numberOfPoints_Source && problem==0; i++){
// vtkSmartPointer<vtkFloatArray> done_list = vtkSmartPointer<vtkFloatArray>::New();
// done_list->SetNumberOfComponents(2);
// //cout << "eee" << endl;
// pair<float, float> ref = { i, 0 };
// //cout << "eee" << endl;
// to_do.push(ref);
// //cout << "eee" << endl;
// int indexRef = i;
// //cout << "eee" << endl;
// double * pRef = Source->GetPoint(indexRef);
// //cout << "eee" << endl;
// while (!to_do.empty()){
// int index_to_do = (to_do.front()).first;
// float dist_to_do = (to_do.front()).second;
// to_do.pop();
// done_list->InsertNextTuple2(index_to_do, dist_to_do);
//
// double * pS = list->GetPoint(index_to_do);
//
// set<int> temp = Source->set_neighborbhood[index_to_do];
//
// //if (i == 0){
// // //cout << " " << temp.size() << endl;
// //}
//
// //for (int j = 0; j <temp.size(); j++){/// on regarde ces voisins
// std::set<int>::iterator it;
// // verification qu'ils ont les mêmes couleurs
// //si une nouvelle couleur apparait la taille va changer
// for (it = temp.begin(); it != temp.end(); ++it){
// int indexN = *it;
//
//
// //int indexN = *temp.begin();// pb
//
// double * pNeighbord = list1->GetPoint(indexN);
// /*if (i == 0){
// cout << " o " << indexN << endl; affiche(pNeighbord, 3); cout << endl;
// cout << " b " << !IsEqual(pS, pNeighbord, 3) << " " << !IsEqual(pRef, pNeighbord, 3) << " " << !AppartientI(index_to_do, done_list) << endl;
// }*/
// if (!IsEqual(pS, pNeighbord, 3)&& !IsEqual(pRef,pNeighbord,3) && !AppartientI(indexN,done_list) ){
// float distN = dist_to_do + sqrt(vtkMath::Distance2BetweenPoints(pS, pNeighbord));
// /*if (i == 0)
// cout << distN << endl;*/
// if (distN<=(Source->mean_arr*2 )){
// //cout << "la";
// pair<float, float> val = {indexN,distN};
// to_do.push(val);
// }
// }
//
// }//end for
//
// }//end while
//
// if (done_list->GetNumberOfTuples() == 0){
// // cout << "ii " << i << endl;
// problem += 2; //si on le remet à mettre dans parametre
// fl_alert("ERROR: the sphere radius for the transformation mode LOC_AFFINE\n is too small , radius = %f (chosen percentage : %f %)", R, percentageRadius_of_sphere_LA);
// break;// à tester par sure que cela marche
// }
// else{
// vtkSmartPointer<vtkFloatArray> done_list_temp = vtkSmartPointer<vtkFloatArray>::New();
// done_list_temp->SetNumberOfComponents(1);
// for (int u = 0; u < done_list->GetNumberOfTuples(); u++){
// done_list_temp->InsertNextTuple1(done_list->GetComponent(u, 0));
// }
//
//
// sphereList[i].list = vtkSmartPointer<vtkFloatArray>::New();
// sphereList[i].list->SetNumberOfComponents(1);
// sphereList[i].list->DeepCopy(done_list_temp);
// }
//
//
// }//end for
// cout << sphereList[0].list->GetNumberOfTuples() << endl;
// cout << "done" << endl;
//
//}