-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathigit_texture_mapping.cpp
More file actions
1736 lines (1527 loc) · 57 KB
/
Copy pathigit_texture_mapping.cpp
File metadata and controls
1736 lines (1527 loc) · 57 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"igit_texture_mapping.h"
#include"igit_functions.h"
#include "igit_SFM.h"
#include<qdir.h>
#include<qtextstream.h>
#include<opencv2\opencv.hpp>
#include<opencv2\core\core.hpp>
#include<qdebug.h>
#include<QProgressDialog>
#include"qprocess.h"
#include"qapplication.h"
#include <ctime>
//******************************************NON CLASS MEMBERS****************************************************************//
///////////////////////////////////////////readProjFromFile///////////////////////////////////////////////////////////////////
void readProjFromFile(cv::Mat& proj, QString txt_name)
{
// cout<<txt_name.toStdString()<<endl;
QFile file(txt_name);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
}
else{
QTextStream in(&file);
int line_num = 0;
while (!in.atEnd())
{
QString line = in.readLine();
// cout<<line.toStdString()<<endl;
if (line_num > 0)
{
QStringList fields = line.split(" ");
for (int i = 0; i < 4; i++)
{
proj.at<float>(line_num - 1, i) = fields.takeFirst().toFloat();
}
}
line_num++;
}
}
}
///////////////////////////////////////////decomposedProjMatrix///////////////////////////////////////////////////////////////
Camera decomposeProjMatrix(const cv::Mat & proj)
{
Camera cam;
// projection matrix
proj.copyTo(cam.project_);
// direction
cam.dir_.at<float>(0) = cam.project_.at<float>(2, 0);
cam.dir_.at<float>(1) = cam.project_.at<float>(2, 1);
cam.dir_.at<float>(2) = cam.project_.at<float>(2, 2);
cam.dir_ = cam.dir_ / cv::norm(cam.dir_);
// get position
cv::Mat KR(3, 3, CV_32FC1);
cv::Mat KT(3, 1, CV_32FC1);
// get position
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
KR.at<float>(i, j) = cam.project_.at<float>(i, j);
}
}
for (int i = 0; i < 3; i++)
KT.at<float>(i, 0) = cam.project_.at<float>(i, 3);
cam.pos_ = -KR.inv()* KT;
// compute the focal
cv::Mat R0(3, 1, CV_32FC1);
cv::Mat R1(3, 1, CV_32FC1);
cv::Mat R2(3, 1, CV_32FC1);
for (int i = 0; i < 3; i++)
{
R0.at<float>(i) = KR.at<float>(0, i);
R1.at<float>(i) = KR.at<float>(1, i);
R2.at<float>(i) = KR.at<float>(2, i);
}
cam.focal_ = 0.5*abs(norm(R0.cross(R2))) + 0.5*abs(norm(R1.cross(R2)));
// axises of the camera
cam.zaxis_ = cam.dir_;
cam.yaxis_ = cam.zaxis_.cross(R0);
cam.yaxis_ = cam.yaxis_ / norm(cam.yaxis_);
cam.xaxis_ = cam.yaxis_.cross(cam.zaxis_);
cam.xaxis_ = cam.xaxis_ / norm(cam.xaxis_);
R0.release();
R1.release();
R2.release();
KR.release();
KT.release();
return cam;
}
///////////////////////////////////////////loadVisibilityFromPatchFile////////////////////////////////////////////////////////
QVector<QVector<int> > loadVisibilityFromPatchFile(QString patch_file_name)
{
QVector<QVector<int> > vis;
QFile file(patch_file_name);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
}
else{
QTextStream in(&file);
int line_num = 0;
int counter = 0;
while (!in.atEnd())
{
QString line = in.readLine();
QStringList fields = line.split(" ");
if (line_num == 1)
{
int points_num = fields.takeFirst().toInt();
//vis.resize(points_num);
}
if (line_num > 1)
{
if (line.startsWith("PATCH"))
{
counter = 0;
}
if (counter == 5){
QVector<int> tmp;
while (fields.size() != 0)
{
tmp.append(fields.takeFirst().toInt());
}
tmp.pop_back();
vis.append(tmp);
}
counter++;
}
line_num++;
}
return vis;
}
}
//******************************************* CLASS MEMBERS*****************************************************************//
////////////////////////////////////////////iniitialization///////////////////////////////////////////////////////////////////
void TextureMapping::initialization()
{
//-----------------------------load texture images ---------------------------------//
// texture images are loaded from pmvs/visualize
// we load all the images right now which used a lot of memory, which should be changed
emit textEdit("[Loading Texture Images...");
emit statusBar("Loading Texture Images");
//***********************************************************************************//
// 考虑到内存需要做一些修改。 主要是两个部分用到了图像:1. MRF 进行梯度运算 2. 创建纹理图像
// 进行拼图。 前者需要所有的图像,但是实际上只需要灰度图像即可。后者需要彩色图像,但是只需要
//只需要加载实际用到的视角即可。这样可以起到节省内存的作用
//************************************************************************************//
t_gray_images_.clear();
loadGrayImages();
emit textEdit(" Done!]");
//----------------------------load projection matrix--------------------------------//
// we loaded projection matrix from pmvs/txt/ and each txt corresponding to a projection
// matrix
emit textEdit("[ Loading Projection Matrix...");
emit statusBar("Loading Projection Matrix");
t_cameras_->clear();
if (loadCameras())emit enableActionCameras();
emit textEdit(" Done!]");
//----------------------------load visibility information --------------------------//
// visibility information are loaded from *.patch file, this file containes the coordinates,
// the normal, the photometric consistency score of each patch, following the visible views
// The visible views are the visibility information we needed
emit textEdit(" [ Loading Visibility Infomation...");
emit statusBar("Loading Visibility Infomation");
for (int i = 0; i < t_dense_pts_->size(); i++)(*t_dense_pts_)[i].vis.clear();
loadVisibility();
emit textEdit(" Done!]");
//------------------------------intial data -------------------------------------------//
// visibility data in t_dense_vis_ is one to one correponding to t_points_ids not t_dense_pts_
// for some points in t_dense_pts_ may be deleted as noise
// Note that the data in t_points_ids are not from little to large, it' order is interupted!!!
#if 1
t_dense_vis_.clear();
foreach(int id, *t_points_ids_)
{
t_dense_vis_.append((*t_dense_pts_)[id].vis);
}
#endif
#if 0
t_dense_vis_.clear();
foreach(Point pt, *t_dense_pts_)
{
t_dense_vis_.append(pt.vis);
}
#endif
//--------------------------------visibility of vertices -----------------------------------------------------//
// Note that the visibility loaded from file are visibility of dense points and the vertices are interploated by
// poisson suface reconstruction, and hence the visibilty of the vertices should be computed. Once the visibilities
// of the facets are computed the visibilities of a facet can be obtainded by calculate the intersection set of
// the visibilities fof the vertex. And besides, the normal of a vertex can by caluculate as the mean of it's nieghbours
emit textEdit(" [Compute the Visibility of V ertices...");
emit statusBar("Compute the Visibility of Vertices");
t_vertices_vis_.clear();
computeVertexNormalAndVisibility();
emit textEdit(" Done!]");
int valid_num0 = 0;
for (int i = 0; i < t_vertices_vis_.size(); i++)
{
if (t_vertices_vis_[i].size() > 0) valid_num0++;
}
float aspect = (float)valid_num0 / (float)t_vertices_vis_.size();
QString txt0 = QString("%1 Valid Vectices %2 Vertices Radio: %3").arg(valid_num0).arg(t_vertices_vis_.size()).arg(aspect);
textEdit(txt0);
//---------------------------compute the visibility of facet from file-----------------------//
// the visibility information of the facet needed to be computed. First the visibility of each
// vertices are computed, and then the visibility of the facet are computed as the intersection
// of the visible views of all the vertices
emit textEdit(" [Compute the Visibility of Facets...");
emit statusBar("Compute the Visibility of Facets");
t_initial_facet_vis_.clear();
t_initial_facet_vis_.resize(t_facets_->size());
computeFacetsVisibilityFromFile();
emit textEdit(" Done!]");
int valid_num11 = 0;
int total_num11 = t_initial_facet_vis_.size();
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
if (t_initial_facet_vis_[i].size() >= 2) valid_num11++;
}
float radio11 = (float)valid_num11 / (float)total_num11;
QString txt11 = QString("Valid facets num: %1 Total num : %2 Radio : %3").arg(valid_num11).arg(total_num11).arg(radio11);
textEdit(txt11);
//---------------------------compute the texture coordinates ----------------------//
// each vertices of the facet are projected into their corresponding view of images, and
// the texture coordinates are retained for filter the visibility and for texture mapping
// and in the final the texture coordinates should be normalized to [0, 1]
emit textEdit(" [Compute the Texture Coordinates...");
emit statusBar("Compute the Texture Coordinates");
t_initial_facet_coordinates_.clear();
t_initial_facet_coordinates_.resize(t_facets_->size());
computeTextureCoordinates();
emit textEdit(" Done!]");
#if 1
//---------------------------filter the visibility----------------------------------------//
// the visibility of each facet is filterd, to improve the quality of the texture image,
// each points only the view through which the 3D point projected into the nearly center
// of the image are maitained, others are filtered out.
emit textEdit(" [Filter the Visibility...");
emit statusBar("Filter the Visibility");
filterVisibility();
emit textEdit(" Done!]");
int valid_num1 = 0;
int total_num1 = t_initial_facet_vis_.size();
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
if (t_initial_facet_vis_[i].size() >= 2) valid_num1++;
}
float radio = (float)valid_num1 / (float)total_num1;
QString txt1 = QString("Valid facets num: %1 Total num : %2 Radio : %3").arg(valid_num1).arg(total_num1).arg(radio);
textEdit(txt1);
#endif
//---------------------------computeFacetsVisibilityViaProjection-------------------------------------------//
/// A part of facets' visibiulity can not be found from the visibility loaded from file, as a supplement, we
// calculate the visibilities through projection. We project the facet to all the views and if the projectd coordinates
// are among a reasonable region the visibility and the coordinates are maintained.
emit textEdit(" [compute Facets Visibility Via Projection...");
emit statusBar("compute Facets Visibility ViaProjection");
computeFacetsVisibilityViaProjection();
emit textEdit(" Done!]");
#if 0
//----------------------------computeFacetsVisibilityAndCoordinate-------------------//
// compute the texture coordinates and visibility of facets
// we project the vertices of each facet into all the views and if the projections of all the
// vertices are close to the center of an image, we consider the view is visible for the facet
// We can do this because there are very little occlusions from air to ground view.
emit textEdit("[Compute Facets Visibility And Texture Coordinates...");
emit statusBar("Compute Facets Visibility And Texture Coordinates");
computeFacetsVisibilityAndCoordinates();
emit textEdit("Done!]");
#endif
//--------------------------trim the facets------------------------------------------------//
// after poisson surface reconstruction there are many facets that are generated without points
// nearby, and hence there will be no texture mapping form them. We elaminate the facets that
// hase no visible view
emit textEdit("[Trim the Surface...");
emit statusBar("Trim the Surface");
facetTrimmer();
emit textEdit("Done!]");
//*********************************************************************************************//
//* 还可以根据NCC 或者 SIFT描述子进行进一步的删除,另外本身自带的visibility在这里没有用到 *//
//* *//
//***********************************************************************************************//
}
///////////////////////////////////////////loadTextureImages/////////////////////////////////////////////////////////////////
bool TextureMapping::loadGrayImages()
{
cv::Mat img;
QDir dir;
if (dir.exists(tr("pmvs/visualize")))
{
QString path = QDir::currentPath() + tr("/pmvs/visualize");
dir.setPath(path);
dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QStringList filter;
filter << "*.jpg";
// ply files
QFileInfoList fileList = dir.entryInfoList(filter);
int nFiles = fileList.size();
for (int i = 0; i < nFiles; i++)
{
// text file
QString img_file_name = fileList.at(i).filePath();
textEdit(img_file_name);
QStringList fields = img_file_name.split("/");
QString name(fields.takeLast());
//QImage img;
//img.load(img_file_name);
img = cv::imread(img_file_name.toStdString().c_str(), 0);
if (t_height_ == 0 || t_width_ == 0)
{
t_height_ = img.rows;
t_width_ = img.cols;
}
t_gray_images_.insert(name, img);
}
}
else{
statusBar("Error to read projection matrixs");
}
img.release();
return true;
}
///////////////////////////////////////////loadTextureImages/////////////////////////////////////////////////////////////////
bool TextureMapping::loadTextureImages()
{
QImage img;
t_texture_images_.clear();
QDir dir;
if (!dir.exists(tr("pmvs/visualize"))) return false;
for (QMap<uint, uint> ::iterator iter = t_label_mapping_.begin(); iter != t_label_mapping_.end(); iter++)
{
uint vis_id = iter.key();
QString name;
name.sprintf("%08d.jpg", (int)vis_id);
QString img_dir = "pmvs/visualize/" + name;
textEdit(img_dir);
img.load(img_dir);
t_texture_images_.insert(name, img);
}
return true;
}
//////////////////////////////////////////////loadProjMatrix/////////////////////////////////////////////////////////////////
bool TextureMapping::loadCameras()
{
QDir dir;
if (dir.exists(tr("pmvs/txt")))
{
QString path = QDir::currentPath() + tr("/pmvs/txt");
dir.setPath(path);
dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QStringList filter;
filter << "*.txt";
// ply files
QFileInfoList fileList = dir.entryInfoList(filter);
int nFiles = fileList.size();
for (int i = 0; i < nFiles; i++)
{
// text file
QString txt_file_name = fileList.at(i).filePath();
textEdit(txt_file_name);
QStringList fields = txt_file_name.split("/");
QString name(fields.takeLast());
name.replace(".txt", ".jpg");
if (!txt_file_name.isEmpty())
{
cv::Mat proj(3, 4, CV_32FC1);
readProjFromFile(proj, txt_file_name);
Camera cam = decomposeProjMatrix(proj);
cam.color_ = QColor((int)rand() & 255, (int)rand() & 255, (int)rand() & 255);
cam.img_dir_ = name.toStdString();
t_cameras_->insert(name, cam);
}
}
}
else{
statusBar("Error to read projection matrixs");
}
return true;
}
///////////////////////////////////////////loadVisibility////////////////////////////////////////////////////////////////////
bool TextureMapping::loadVisibility()
{
QVector<QVector<int> > all_vis;
QDir dir;
if (!dir.exists(tr("pmvs/models"))) return false;
QString path = QDir::currentPath() + tr("/pmvs/models");
dir.setPath(path);
dir.setFilter(QDir::Files | QDir::NoSymLinks | QDir::NoDotAndDotDot);
QStringList filter;
filter << "*.patch";
// ply files
QFileInfoList fileList = dir.entryInfoList(filter);
int nFiles = fileList.size();
// create a progress dialog
//QProgressDialog progress;
//progress.setLabelText(tr("Loading Visibility Points..."));
//progress.setWindowModality(Qt::WindowModal);
//progress.setRange(0, nFiles);
int nSteps = 0;
for (int i = 0; i < nFiles; i++)
{
//progress.setValue(nSteps);
//qApp->processEvents();
// the last file containes all the points
QString patch_file_name = fileList.at(i).filePath();
textEdit("Loading Visibility From " + patch_file_name);
//load points
QVector<QVector<int> > sub_vis = loadVisibilityFromPatchFile(patch_file_name);
foreach(QVector<int> v, sub_vis)
{
all_vis.append(v);
}
sub_vis.clear();
//if (progress.wasCanceled())
//{
// return false;
//}
nSteps++;
}
if (all_vis.size() != t_dense_pts_->size())
{
statusBar("Warning: Visibility Does not Match Dense Points! ");
}
else{
// we do this because some points may be elaminated as noise and the visibility must correspod to each
// point
for (int i = 0; i < all_vis.size(); i++)
{
(*t_dense_pts_)[i].vis.swap(all_vis[i]);
}
}
all_vis.clear();
return true;
}
///////////////////////////////////////////comput Vertex visibility /////////////////////////////////////////////////////////
void TextureMapping::computeVertexNormalAndVisibility()
{
//----------------------------------------compute K nearest neighbours-------------------------------------------------//
// dense points are generated from PMVS and contain visibility information, while vertices of mesh are not for they are obtained
// by interplotation. We first compute the neighbours of each vertex and then get the visibility from the neighbours.
emit textEdit(" [Compute K Nearest Neighbours...");
emit statusBar("Compute K Neares Neighbours ");
int Knn = 5;
#if 1
QVector<Point> dense_points;
foreach(int id, *t_points_ids_)
{
dense_points.append((*t_dense_pts_)[id]);
}
#endif
QVector<QVector<int> > neighbours = kNearesNeighbours(Knn, *t_vertices_, dense_points);
emit textEdit(" Done!]");
//----------------------------------------compute the normal of each vertex------------------------------------------//
// Dense points generated from cmvs owns normal information but the vertices do not. We recovered the normal of each
// vertex by calculating the mean of the neighbours's normals.
emit textEdit(" [Compute Normals of Vertices...");
emit statusBar("Compute Normals of Vertices ");
int counter = 0;
foreach(QVector<int> nhbr, neighbours)
{
qglviewer::Vec normal(0, 0, 0);
foreach(int pt_id, nhbr)
{
normal.x += (*t_dense_pts_)[pt_id].normal_x;
normal.y += (*t_dense_pts_)[pt_id].normal_y;
normal.z += (*t_dense_pts_)[pt_id].normal_z;
}
normal = normal / Knn;
normal.normalize();
(*t_vertices_)[counter].normal_x = normal.x;
(*t_vertices_)[counter].normal_y = normal.y;
(*t_vertices_)[counter].normal_z = normal.z;
counter++;
}
emit textEdit(" Done!]");
//----------------------------------------computhe the visibility of each vertex-------------------------------------//
// we have no visibility information about the vertices, since the vertices do not reconstructed by PMVS
// but are generated by interplotation. We get the visibility of information a vertex by computing the histgram for
// visibility of K neighbours, and the vis whose merge more than 0.75 * Knn are maintained
emit textEdit(" [Compute Visibility of Vertices...");
emit statusBar("Compute Visibility of Vertices ");
foreach(QVector<int>nhbr, neighbours)
{
// the key of map is the view index
// the value of the map is the number it merges in neighbors
QMap<int, int> map_vis;
foreach(int pt_id, nhbr)// for each neighboring point
{
foreach(int vis_id, t_dense_vis_[pt_id])// the visible views of each neighboring point
{
if (map_vis.contains(vis_id)) map_vis[vis_id]++;
else{
map_vis[vis_id] =1;
}
}
}
// check the number each view merges, only whose value above 0.75 of its neighbors are maintained
QVector<int> single_pt_vis;
foreach(int key, map_vis.keys())
{
foreach(int value, map_vis.values(key))
{
if (value >= 2)
{
single_pt_vis.append(key);
}
}
}
t_vertices_vis_.append(single_pt_vis);
}
emit textEdit(" Done!]");
}
///////////////////////////////////////////computeVerticesVisibilityFromFile/////////////////////////////////////////////////
bool TextureMapping::computeFacetsVisibilityFromFile()
{
//---------------------------------------compute the visibility of each facet-----------------------------------------//
// since we have obtained the view of each vertices, and each facet is composed by several vertices
// hence the view of each facet is computed by intersection of view set of each vertices
int facet_id = 0;
foreach(QVector<int> facet, *t_facets_)
{
QSet<int> intersection_vis;
for (int i = 0; i < t_cameras_->size(); i++)
{
intersection_vis.insert(i);
}
// compute the intersection of the visibility of each vertices
foreach(int id, facet)
{
QSet<int> tmp;
foreach(int vis, t_vertices_vis_[id])
{
tmp.insert(vis);
}
intersection_vis = intersection_vis.intersect(tmp);
}
foreach(int id, intersection_vis)
{
t_initial_facet_vis_[facet_id].append(id);
}
facet_id++;
}
return true;
}
///////////////////////////////////////////computeFacetsVisibilityViaProjection//////////////////////////////////////////////
void TextureMapping::computeFacetsVisibilityViaProjection()
{
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
// ignore the facet that has visible views
if (t_initial_facet_vis_[i].size() >= 2)continue;
t_initial_facet_vis_[i].clear();
t_initial_facet_coordinates_[i].clear();
for (int j = 0; j < t_cameras_->size(); j++)// each vis
{
//**** project matrix****//
int vis_id = j;
QString name;
name.sprintf("%08d.jpg", vis_id);
Camera cam = (*t_cameras_)[name];
//**** check whether this facet is visible in this view ****//
bool valid = true;
QVector<QPoint> coordinates;
for (int k = 0; k < (*t_facets_)[i].size(); k++)// each vertex
{
int pt_id = (*t_facets_)[i][k];
//*************** check the angle between vertex normal and the line************************//
//* *//
//* *//
//**************************************end*************************************************//
Point pt3D = (*t_vertices_)[pt_id];
QPoint pt2D;
projectionFrom3DTo2D(pt3D, cam.project_, pt2D);
coordinates.append(pt2D);
if (!isValidVis(pt2D, 0))
{
valid = false;
break;
}
}
//**** if the facet is view is visible ****//
if (valid == true)
{
t_initial_facet_vis_[i].append(vis_id);
t_initial_facet_coordinates_[i].append(coordinates);
}
}
}
int valid_num1 = 0;
int total_num1 = t_initial_facet_vis_.size();
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
if (t_initial_facet_vis_[i].size() >= 2) valid_num1++;
}
float radio = (float)valid_num1 / (float)total_num1;
QString txt1 = QString("Valid facets num: %1 Total num : %2 Radio : %3").arg(valid_num1).arg(total_num1).arg(radio);
textEdit(txt1);
}
////////////////////////////////////////////computeTextureCoordinates///////////////////////////////////////////////////////////
void TextureMapping::computeTextureCoordinates()
{
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
if (t_initial_facet_vis_[i].size() == 0) continue;
// texture coordinates of a facet in all views
QVector< QVector<QPoint> > coordinates_of_all_views;
for (int j = 0; j < t_initial_facet_vis_[i].size(); j++)
{
int vis_id = t_initial_facet_vis_[i][j];
QString name;
name.sprintf("%08d.jpg", vis_id);
Camera cam = (*t_cameras_)[name];
// coordinages
QVector<QPoint> coordinates_of_each_view;
foreach(int pt_id, (*t_facets_)[i])
{
Point pt3D = (*t_vertices_)[pt_id];
QPoint pt2D;
projectionFrom3DTo2D(pt3D, cam.project_, pt2D);
coordinates_of_each_view.append(pt2D);
}
coordinates_of_all_views.append(coordinates_of_each_view);
}
t_initial_facet_coordinates_[i].swap(coordinates_of_all_views);
}
}
//////////////////////////////////////////// filterVisibility //////////////////////////////////////////////////////////////////
void TextureMapping::filterVisibility()
{
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
if (t_initial_facet_vis_[i].size() == 0) continue;
for (int j = 0; j < t_initial_facet_vis_[i].size(); j++)
{
// each visible view of facet
int vis_id = t_initial_facet_vis_[i][j];
// projected vertices of each facet
QVector<QPoint> projected_vertices = t_initial_facet_coordinates_[i][j];
//-------------------whether this view should be aborted or not ------------------------------//
// if a facet is visible in a view it must satify that all the the projections of all
// the verticea are near the center of the image
bool aborted = false;
for (int k = 0; k < projected_vertices.size(); k++)
{
QPoint pt2D = projected_vertices[k];
if (!isValidVis(pt2D, 0.1))// this threshold is important
{
aborted = true;
break;
}
}
if (aborted == true)
{
t_initial_facet_vis_[i].clear();
t_initial_facet_coordinates_[i].clear();
}
}
}
}
//////////////////////////////////////////// isValidVis ///////////////////////////////////////////////////////////////////////
bool TextureMapping::isValidVis(QPoint pt, float thresh)
{
int w0 = int(thresh * (float)t_width_ + 0.5);
int w1 = int((1 - thresh)* (float)t_width_ + 0.5);
int h0 = int(thresh * (float)t_height_ + 0.5);
int h1 = int((1 - thresh) * (float)t_height_ + 0.5);
if (pt.x() > w0 && pt.x() < w1 && pt.y() > h0&& pt.y() < h1)
{
return true;
}
else{
return false;
}
}
///////////////////////////////////////////facet trimmer //////////////////////////////////////////////////////////////////////
void TextureMapping::facetTrimmer()
{
//---------------------eliminate the facets with visible views less than 2--------------------------------//
QVector<QVector<int> > facets_new;
QVector<QVector<QVector<QPoint> > > texture_coordinates_new;
QVector<QVector<int > > facet_vis_new;
for (int i = 0; i < t_initial_facet_vis_.size(); i++)
{
if (t_initial_facet_vis_[i].size() > 1)
{
facets_new.append((*t_facets_)[i]);
texture_coordinates_new.append(t_initial_facet_coordinates_[i]);
facet_vis_new.append(t_initial_facet_vis_[i]);
}
}
t_facets_->swap(facets_new);
t_initial_facet_coordinates_.swap(texture_coordinates_new);
t_initial_facet_vis_.swap(facet_vis_new);
//------------------update vertice, facets, edges, and texture coordinates---------------------------------//
// collect all the facets
QVector<QVector<Point> > all_facets;
all_facets.resize(t_facets_->size());
int counter = 0;
foreach(QVector<int> facet, *t_facets_)
{
foreach(int id, facet)
{
all_facets[counter].append((*t_vertices_)[id]);
}
counter++;
}
// updating
updateMesh(all_facets);
facets_new.clear();
texture_coordinates_new.clear();
facet_vis_new.clear();
all_facets.clear();
}
///////////////////////////////////////////updateMeshWithTextureCoords///////////////////////////////////////////////
void TextureMapping::updateMesh(QVector<QVector<Point> > & facets)
{
//-----------------------------------update vertices, edges and facets------------------------------------//
// create a table for inquerying the new index of vertex
// Note: we can do this because the structure of Point is special defined(overlod of operator < in "data_type.h").
// and may not work for other type of structure.
map<Point, int> table;
foreach(QVector<Point> facet, facets)
{
foreach(Point pt, facet)
{
table.insert(make_pair(pt, 0));
}
}
//attach index to each point
int index = 0;
for (map<Point, int> ::iterator iter = table.begin(); iter != table.end(); iter++)
{
iter->second = index;
index++;
}
QVector<Point> new_vertices;
QVector<QVector<int> > new_facets;
QVector<QPair<int, int> > new_edges;
// get new vertices
for (map<Point, int> ::iterator iter = table.begin(); iter != table.end(); iter++)
{
new_vertices.append(iter->first);
}
// get new facets
foreach(QVector<Point> facet, facets)
{
QVector<int> facetID;
foreach(Point pt, facet)
{
facetID.append(table[pt]);
}
new_facets.append(facetID);
}
// get new edges
QSet<QPair<int, int> > e;
foreach(QVector<int> facet, new_facets)
{
int pt_num = facet.size();
for (int i = 0; i < pt_num; i++)
{
int id0 = facet[i];
int id1 = facet[(i + 1) % pt_num];
if (id0 < id1) e.insert(qMakePair(id0, id1));
if (id1 < id0) e.insert(qMakePair(id1, id0));
}
}
QSet<QPair<int, int> > ::const_iterator iter = e.constBegin();
while (iter != e.constEnd())
{
new_edges << (*iter);
iter++;
}
t_vertices_->swap(new_vertices);
t_edges_->swap(new_edges);
t_facets_->swap(new_facets);
table.clear();
new_vertices.clear();
new_facets.clear();
new_edges.clear();
e.clear();
}
///////////////////////////////////////////computeFacetsVisibilityAndCoordinates/////////////////////////////////////
void TextureMapping::computeFacetsVisibilityAndCoordinates()
{
cv::Mat proj;
t_initial_facet_vis_.clear();
t_initial_facet_coordinates_.clear();
t_initial_facet_vis_.resize(t_facets_->size());
t_initial_facet_coordinates_.resize(t_facets_->size());
for (int i = 0; i < t_facets_->size(); i++)// each facet
{
for (int j = 0; j < t_cameras_->size(); j++)// each vis
{
//**** project matrix****//
int vis_id = j;
QString name;
name.sprintf("%08d.jpg", vis_id);
Camera cam = (*t_cameras_)[name];
//**** check whether this facet is visible in this view ****//
bool valid = true;
QVector<QPoint> coordinates;
for (int k = 0; k < (*t_facets_)[i].size(); k++)// each vertex
{
int pt_id = (*t_facets_)[i][k];
//*************** check the angle between vertex normal and the line************************//
//* *//
//* *//
//**************************************end*************************************************//
Point pt3D = (*t_vertices_)[pt_id];
QPoint pt2D;
projectionFrom3DTo2D(pt3D, cam.project_, pt2D);
coordinates.append(pt2D);
if (!isValidVis(pt2D, 0))
{
valid = false;
break;
}
}
//**** if the facet is view is visible ****//
if (valid == true)
{
t_initial_facet_vis_[i].append(vis_id);
t_initial_facet_coordinates_[i].append(coordinates);
}
}
}
proj.release();
}
//////////////////////////////////////////facetRelation////////////////////////////////////////////////////////////////////////
TextureMapping::FacetRelationShip TextureMapping::facetRelation(int i, int j)
{
QVector<int> facet0 = (*t_facets_)[i];
QVector<int> facet1 = (*t_facets_)[j];
int counter = 0;
foreach(int id0, facet0)
{
if (facet1.contains(id0))
{
counter++;
}
}
if (counter == 1) return TextureMapping::COMMON_VERTEX;
else if (counter == 2) return TextureMapping::COMMON_EDGE;
else {
return TextureMapping::NONE;
}
}
///////////////////////////////////////////kNearestNeighboursFacets////////////////////////////////////////////////////////////
QVector<QVector<int> > TextureMapping::kNearestNeighboursFacets(TextureMapping::FacetRelationShip type)
{
//------------------------------------- get the center of the facets ---------------------------------------//
QVector<Point> centers;
foreach(QVector<int> facet, *t_facets_)
{
Point c(0, 0, 0);
int N = facet.size();
foreach(int id, facet)
{
c.x += 1.0 / (float)N * (*t_vertices_)[id].x;
c.y += 1.0 / (float)N * (*t_vertices_)[id].y;
c.z += 1.0 / (float)N * (*t_vertices_)[id].z;
}
centers.append(c);
}
//-------------------------------------- find the candidate neighbours of each facet -----------------------//
QVector< QVector<int> >neighbours_tmp = kNearesNeighbours(10, centers, centers);
//---------------------------------------find the final neighbours of each facet----------------------------//
QVector< QVector<int> > neighbours;
neighbours.resize(t_facets_->size());
for (int i = 0; i < neighbours_tmp.size(); i++)
{
int id0 = i;
for (int j = 0; j < neighbours_tmp[i].size(); j++)
{
int id1 = neighbours_tmp[i][j];
if (id0 == id1) continue;
// facets share a vertex or a facets are considered as neighbours
if (facetRelation(id0, id1) == type)
{
neighbours[i].append(id1);
}
}
}
return neighbours;
}
////////////////////////////////////////////MRF_Optimization()//////////////////////////////////////////////////////////////////
void TextureMapping::MRF_Optimization()
{
#if DEBUG_
//********************************debug--intial view labels*******************************//
QFile file("DEBUG_intial_facet_vis.txt");