-
-
Notifications
You must be signed in to change notification settings - Fork 892
/
SceneTexture.cpp
2354 lines (2198 loc) · 85.6 KB
/
SceneTexture.cpp
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
/*
* SceneTexture.cpp
*
* Copyright (c) 2014-2015 SEACAVE
*
* Author(s):
*
* cDc <cdc.seacave@gmail.com>
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* Additional Terms:
*
* You are required to preserve legal notices and author attributions in
* that material or in the Appropriate Legal Notices displayed by works
* containing it.
*/
#include "Common.h"
#include "Scene.h"
#include "RectsBinPack.h"
// connected components
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
using namespace MVS;
// D E F I N E S ///////////////////////////////////////////////////
// uncomment to enable multi-threading based on OpenMP
#ifdef _USE_OPENMP
#define TEXOPT_USE_OPENMP
#endif
// uncomment to use SparseLU for solving the linear systems
// (should be faster, but not working on old Eigen)
#if !defined(EIGEN_DEFAULT_TO_ROW_MAJOR) || EIGEN_WORLD_VERSION>3 || (EIGEN_WORLD_VERSION==3 && EIGEN_MAJOR_VERSION>2)
#define TEXOPT_SOLVER_SPARSELU
#endif
// method used to try to detect outlier face views
// (should enable more consistent textures, but it is not working)
#define TEXOPT_FACEOUTLIER_NA 0
#define TEXOPT_FACEOUTLIER_MEDIAN 1
#define TEXOPT_FACEOUTLIER_GAUSS_DAMPING 2
#define TEXOPT_FACEOUTLIER_GAUSS_CLAMPING 3
#define TEXOPT_FACEOUTLIER TEXOPT_FACEOUTLIER_GAUSS_CLAMPING
// method used to find optimal view per face
#define TEXOPT_INFERENCE_LBP 1
#define TEXOPT_INFERENCE_TRWS 2
#define TEXOPT_INFERENCE TEXOPT_INFERENCE_LBP
// inference algorithm
#if TEXOPT_INFERENCE == TEXOPT_INFERENCE_LBP
#include "../Math/LBP.h"
namespace MVS {
typedef LBPInference::NodeID NodeID;
// Potts model as smoothness function
LBPInference::EnergyType STCALL SmoothnessPotts(LBPInference::NodeID, LBPInference::NodeID, LBPInference::LabelID l1, LBPInference::LabelID l2) {
return l1 == l2 && l1 != 0 && l2 != 0 ? LBPInference::EnergyType(0) : LBPInference::EnergyType(LBPInference::MaxEnergy);
}
}
#endif
#if TEXOPT_INFERENCE == TEXOPT_INFERENCE_TRWS
#include "../Math/TRWS/MRFEnergy.h"
namespace MVS {
// TRWS MRF energy using Potts model
typedef unsigned NodeID;
typedef unsigned LabelID;
typedef TypePotts::REAL EnergyType;
static const EnergyType MaxEnergy(1);
struct TRWSInference {
typedef MRFEnergy<TypePotts> MRFEnergyType;
typedef MRFEnergy<TypePotts>::Options MRFOptions;
CAutoPtr<MRFEnergyType> mrf;
CAutoPtrArr<MRFEnergyType::NodeId> nodes;
inline TRWSInference() {}
void Init(NodeID nNodes, LabelID nLabels) {
mrf = new MRFEnergyType(TypePotts::GlobalSize(nLabels));
nodes = new MRFEnergyType::NodeId[nNodes];
}
inline bool IsEmpty() const {
return mrf == NULL;
}
inline void AddNode(NodeID n, const EnergyType* D) {
nodes[n] = mrf->AddNode(TypePotts::LocalSize(), TypePotts::NodeData(D));
}
inline void AddEdge(NodeID n1, NodeID n2) {
mrf->AddEdge(nodes[n1], nodes[n2], TypePotts::EdgeData(MaxEnergy));
}
EnergyType Optimize() {
MRFOptions options;
options.m_eps = 0.005;
options.m_iterMax = 1000;
#if 1
EnergyType lowerBound, energy;
mrf->Minimize_TRW_S(options, lowerBound, energy);
#else
EnergyType energy;
mrf->Minimize_BP(options, energy);
#endif
return energy;
}
inline LabelID GetLabel(NodeID n) const {
return mrf->GetSolution(nodes[n]);
}
};
}
#endif
// S T R U C T S ///////////////////////////////////////////////////
typedef Mesh::Vertex Vertex;
typedef Mesh::VIndex VIndex;
typedef Mesh::Face Face;
typedef Mesh::FIndex FIndex;
typedef Mesh::TexCoord TexCoord;
typedef Mesh::TexIndex TexIndex;
typedef int MatIdx;
typedef Eigen::Triplet<float,MatIdx> MatEntry;
typedef Eigen::SparseMatrix<float,Eigen::ColMajor,MatIdx> SparseMat;
enum Mask {
empty = 0,
border = 128,
interior = 255
};
struct MeshTexture {
// used to render the surface to a view camera
typedef TImage<cuint32_t> FaceMap;
struct RasterMesh : TRasterMesh<RasterMesh> {
typedef TRasterMesh<RasterMesh> Base;
FaceMap& faceMap;
FIndex idxFace;
Image8U mask;
bool validFace;
RasterMesh(const Mesh::VertexArr& _vertices, const Camera& _camera, DepthMap& _depthMap, FaceMap& _faceMap)
: Base(_vertices, _camera, _depthMap), faceMap(_faceMap) {}
void Clear() {
Base::Clear();
faceMap.memset((uint8_t)NO_ID);
}
void Raster(const ImageRef& pt, const Point3f& bary) {
const Point3f pbary(PerspectiveCorrectBarycentricCoordinates(bary));
const Depth z(ComputeDepth(pbary));
ASSERT(z > Depth(0));
Depth& depth = depthMap(pt);
if (depth == 0 || depth > z) {
depth = z;
faceMap(pt) = validFace && (validFace = (mask(pt) != 0)) ? idxFace : NO_ID;
}
}
};
// used to represent a pixel color
typedef Point3f Color;
typedef CLISTDEF0(Color) Colors;
// used to store info about a face (view, quality)
struct FaceData {
IIndex idxView;// the view seeing this face
float quality; // how well the face is seen by this view
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
Color color; // additionally store mean color (used to remove outliers)
#endif
};
typedef cList<FaceData,const FaceData&,0,8,uint32_t> FaceDataArr; // store information about one face seen from several views
typedef cList<FaceDataArr,const FaceDataArr&,2,1024,FIndex> FaceDataViewArr; // store data for all the faces of the mesh
typedef cList<Mesh::FaceIdxArr, const Mesh::FaceIdxArr&,2,1024, FIndex> VirtualFaceIdxsArr; // store face indices for each virtual face
// used to assign a view to a face
typedef uint32_t Label;
typedef cList<Label,Label,0,1024,FIndex> LabelArr;
// represents a texture patch
struct TexturePatch {
Label label; // view index
Mesh::FaceIdxArr faces; // indices of the faces contained by the patch
RectsBinPack::Rect rect; // the bounding box in the view containing the patch
};
typedef cList<TexturePatch,const TexturePatch&,1,1024,FIndex> TexturePatchArr;
// used to optimize texture patches
struct SeamVertex {
struct Patch {
struct Edge {
uint32_t idxSeamVertex; // the other vertex of this edge
FIndex idxFace; // the face containing this edge in this patch
inline Edge() {}
inline Edge(uint32_t _idxSeamVertex) : idxSeamVertex(_idxSeamVertex) {}
inline bool operator == (uint32_t _idxSeamVertex) const {
return (idxSeamVertex == _idxSeamVertex);
}
};
typedef cList<Edge,const Edge&,0,4,uint32_t> Edges;
uint32_t idxPatch; // the patch containing this vertex
Point2f proj; // the projection of this vertex in this patch
Edges edges; // the edges starting from this vertex, contained in this patch (exactly two for manifold meshes)
inline Patch() {}
inline Patch(uint32_t _idxPatch) : idxPatch(_idxPatch) {}
inline bool operator == (uint32_t _idxPatch) const {
return (idxPatch == _idxPatch);
}
};
typedef cList<Patch,const Patch&,1,4,uint32_t> Patches;
VIndex idxVertex; // the index of this vertex
Patches patches; // the patches meeting at this vertex (two or more)
inline SeamVertex() {}
inline SeamVertex(uint32_t _idxVertex) : idxVertex(_idxVertex) {}
inline bool operator == (uint32_t _idxVertex) const {
return (idxVertex == _idxVertex);
}
Patch& GetPatch(uint32_t idxPatch) {
const uint32_t idx(patches.Find(idxPatch));
if (idx == NO_ID)
return patches.emplace_back(idxPatch);
return patches[idx];
}
inline void SortByPatchIndex(IndexArr& indices) const {
indices.resize(patches.size());
std::iota(indices.Begin(), indices.End(), 0);
std::sort(indices.Begin(), indices.End(), [&](IndexArr::Type i0, IndexArr::Type i1) -> bool {
return patches[i0].idxPatch < patches[i1].idxPatch;
});
}
};
typedef cList<SeamVertex,const SeamVertex&,1,256,uint32_t> SeamVertices;
// used to iterate vertex labels
struct PatchIndex {
bool bIndex;
union {
uint32_t idxPatch;
uint32_t idxSeamVertex;
};
};
typedef CLISTDEF0(PatchIndex) PatchIndices;
struct VertexPatchIterator {
uint32_t idx;
uint32_t idxPatch;
const SeamVertex::Patches* pPatches;
inline VertexPatchIterator(const PatchIndex& patchIndex, const SeamVertices& seamVertices) : idx(NO_ID) {
if (patchIndex.bIndex) {
pPatches = &seamVertices[patchIndex.idxSeamVertex].patches;
} else {
idxPatch = patchIndex.idxPatch;
pPatches = NULL;
}
}
inline operator uint32_t () const {
return idxPatch;
}
inline bool Next() {
if (pPatches == NULL)
return (idx++ == NO_ID);
if (++idx >= pPatches->size())
return false;
idxPatch = (*pPatches)[idx].idxPatch;
return true;
}
};
// used to sample seam edges
typedef TAccumulator<Color> AccumColor;
typedef Sampler::Linear<float> Sampler;
struct SampleImage {
AccumColor accumColor;
const Image8U3& image;
const Sampler sampler;
inline SampleImage(const Image8U3& _image) : image(_image), sampler() {}
// sample the edge with linear weights
void AddEdge(const TexCoord& p0, const TexCoord& p1) {
const TexCoord p01(p1 - p0);
const float length(norm(p01));
ASSERT(length > 0.f);
const int nSamples(ROUND2INT(MAXF(length, 1.f) * 2.f)-1);
AccumColor edgeAccumColor;
for (int s=0; s<nSamples; ++s) {
const float len(static_cast<float>(s) / nSamples);
const TexCoord samplePos(p0 + p01 * len);
const Color color(image.sample<Sampler,Color>(sampler, samplePos));
edgeAccumColor.Add(RGB2YCBCR(color), 1.f-len);
}
accumColor.Add(edgeAccumColor.Normalized(), length);
}
// returns accumulated color
Color GetColor() const {
return accumColor.Normalized();
}
};
// used to interpolate adjustments color over the whole texture patch
typedef TImage<Color> ColorMap;
public:
MeshTexture(Scene& _scene, unsigned _nResolutionLevel=0, unsigned _nMinResolution=640);
~MeshTexture();
void ListVertexFaces();
bool ListCameraFaces(FaceDataViewArr&, float fOutlierThreshold, int nIgnoreMaskLabel, const IIndexArr& views);
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
bool FaceOutlierDetection(FaceDataArr& faceDatas, float fOutlierThreshold) const;
#endif
void CreateVirtualFaces(const FaceDataViewArr& facesDatas, FaceDataViewArr& virtualFacesDatas, VirtualFaceIdxsArr& virtualFaces, unsigned minCommonCameras=2, float thMaxNormalDeviation=25.f) const;
IIndexArr SelectBestView(const FaceDataArr& faceDatas, FIndex fid, unsigned minCommonCameras, float ratioAngleToQuality) const;
bool FaceViewSelection(unsigned minCommonCameras, float fOutlierThreshold, float fRatioDataSmoothness, int nIgnoreMaskLabel, const IIndexArr& views);
void CreateSeamVertices();
void GlobalSeamLeveling();
void LocalSeamLeveling();
void GenerateTexture(bool bGlobalSeamLeveling, bool bLocalSeamLeveling, unsigned nTextureSizeMultiple, unsigned nRectPackingHeuristic, Pixel8U colEmpty, float fSharpnessWeight, int maxTextureSize);
template <typename PIXEL>
static inline PIXEL RGB2YCBCR(const PIXEL& v) {
typedef typename PIXEL::Type T;
return PIXEL(
v[0] * T(0.299) + v[1] * T(0.587) + v[2] * T(0.114),
v[0] * T(-0.168736) + v[1] * T(-0.331264) + v[2] * T(0.5) + T(128),
v[0] * T(0.5) + v[1] * T(-0.418688) + v[2] * T(-0.081312) + T(128)
);
}
template <typename PIXEL>
static inline PIXEL YCBCR2RGB(const PIXEL& v) {
typedef typename PIXEL::Type T;
const T v1(v[1] - T(128));
const T v2(v[2] - T(128));
return PIXEL(
v[0]/* * T(1) + v1 * T(0)*/ + v2 * T(1.402),
v[0]/* * T(1)*/ + v1 * T(-0.34414) + v2 * T(-0.71414),
v[0]/* * T(1)*/ + v1 * T(1.772)/* + v2 * T(0)*/
);
}
protected:
static void ProcessMask(Image8U& mask, int stripWidth);
static void PoissonBlending(const Image32F3& src, Image32F3& dst, const Image8U& mask, float bias=1.f);
public:
const unsigned nResolutionLevel; // how many times to scale down the images before mesh optimization
const unsigned nMinResolution; // how many times to scale down the images before mesh optimization
// store found texture patches
TexturePatchArr texturePatches;
// used to compute the seam leveling
PairIdxArr seamEdges; // the (face-face) edges connecting different texture patches
Mesh::FaceIdxArr components; // for each face, stores the texture patch index to which belongs
IndexArr mapIdxPatch; // remap texture patch indices after invalid patches removal
SeamVertices seamVertices; // array of vertices on the border between two or more patches
// valid the entire time
Mesh::VertexFacesArr& vertexFaces; // for each vertex, the list of faces containing it
BoolArr& vertexBoundary; // for each vertex, stores if it is at the boundary or not
Mesh::FaceFacesArr& faceFaces; // for each face, the list of adjacent faces, NO_ID for border edges (optional)
Mesh::TexCoordArr& faceTexcoords; // for each face, the texture-coordinates of the vertices
Mesh::TexIndexArr& faceTexindices; // for each face, the texture-coordinates of the vertices
Mesh::Image8U3Arr& texturesDiffuse; // texture containing the diffuse color
// constant the entire time
Mesh::VertexArr& vertices;
Mesh::FaceArr& faces;
ImageArr& images;
Scene& scene; // the mesh vertices and faces
};
// creating an invalid mask for the given image corresponding to
// the invalid pixels generated during image correction for the lens distortion;
// the returned mask has the same size as the image and is set to zero for invalid pixels
static Image8U DetectInvalidImageRegions(const Image8U3& image)
{
const cv::Scalar upDiff(3);
const int flags(8 | (255 << 8));
Image8U mask(image.rows + 2, image.cols + 2);
mask.memset(0);
Image8U imageGray;
cv::cvtColor(image, imageGray, cv::COLOR_BGR2GRAY);
if (imageGray(0, 0) == 0)
cv::floodFill(imageGray, mask, cv::Point(0, 0), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(image.rows / 2, 0) == 0)
cv::floodFill(imageGray, mask, cv::Point(0, image.rows / 2), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(image.rows - 1, 0) == 0)
cv::floodFill(imageGray, mask, cv::Point(0, image.rows - 1), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(image.rows - 1, image.cols / 2) == 0)
cv::floodFill(imageGray, mask, cv::Point(image.cols / 2, image.rows - 1), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(image.rows - 1, image.cols - 1) == 0)
cv::floodFill(imageGray, mask, cv::Point(image.cols - 1, image.rows - 1), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(image.rows / 2, image.cols - 1) == 0)
cv::floodFill(imageGray, mask, cv::Point(image.cols - 1, image.rows / 2), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(0, image.cols - 1) == 0)
cv::floodFill(imageGray, mask, cv::Point(image.cols - 1, 0), 255, NULL, cv::Scalar(0), upDiff, flags);
if (imageGray(0, image.cols / 2) == 0)
cv::floodFill(imageGray, mask, cv::Point(image.cols / 2, 0), 255, NULL, cv::Scalar(0), upDiff, flags);
mask = (mask(cv::Rect(1,1, imageGray.cols,imageGray.rows)) == 0);
return mask;
}
MeshTexture::MeshTexture(Scene& _scene, unsigned _nResolutionLevel, unsigned _nMinResolution)
:
nResolutionLevel(_nResolutionLevel),
nMinResolution(_nMinResolution),
vertexFaces(_scene.mesh.vertexFaces),
vertexBoundary(_scene.mesh.vertexBoundary),
faceFaces(_scene.mesh.faceFaces),
faceTexcoords(_scene.mesh.faceTexcoords),
faceTexindices(_scene.mesh.faceTexindices),
texturesDiffuse(_scene.mesh.texturesDiffuse),
vertices(_scene.mesh.vertices),
faces(_scene.mesh.faces),
images(_scene.images),
scene(_scene)
{
}
MeshTexture::~MeshTexture()
{
vertexFaces.Release();
vertexBoundary.Release();
faceFaces.Release();
}
// extract array of triangles incident to each vertex
// and check each vertex if it is at the boundary or not
void MeshTexture::ListVertexFaces()
{
scene.mesh.EmptyExtra();
scene.mesh.ListIncidenteFaces();
scene.mesh.ListBoundaryVertices();
scene.mesh.ListIncidenteFaceFaces();
}
// extract array of faces viewed by each image
bool MeshTexture::ListCameraFaces(FaceDataViewArr& facesDatas, float fOutlierThreshold, int nIgnoreMaskLabel, const IIndexArr& _views)
{
// create faces octree
Mesh::Octree octree;
Mesh::FacesInserter::CreateOctree(octree, scene.mesh);
// extract array of faces viewed by each image
IIndexArr views(_views);
if (views.empty()) {
views.resize(images.size());
std::iota(views.begin(), views.end(), IIndex(0));
}
facesDatas.resize(faces.size());
Util::Progress progress(_T("Initialized views"), views.size());
typedef float real;
TImage<real> imageGradMag;
TImage<real>::EMat mGrad[2];
FaceMap faceMap;
DepthMap depthMap;
#ifdef TEXOPT_USE_OPENMP
bool bAbort(false);
#pragma omp parallel for private(imageGradMag, mGrad, faceMap, depthMap)
for (int_t idx=0; idx<(int_t)views.size(); ++idx) {
#pragma omp flush (bAbort)
if (bAbort) {
++progress;
continue;
}
const IIndex idxView(views[(IIndex)idx]);
#else
for (IIndex idxView: views) {
#endif
Image& imageData = images[idxView];
if (!imageData.IsValid()) {
++progress;
continue;
}
// load image
unsigned level(nResolutionLevel);
const unsigned imageSize(imageData.RecomputeMaxResolution(level, nMinResolution));
if ((imageData.image.empty() || MAXF(imageData.width,imageData.height) != imageSize) && !imageData.ReloadImage(imageSize)) {
#ifdef TEXOPT_USE_OPENMP
bAbort = true;
#pragma omp flush (bAbort)
continue;
#else
return false;
#endif
}
imageData.UpdateCamera(scene.platforms);
// compute gradient magnitude
imageData.image.toGray(imageGradMag, cv::COLOR_BGR2GRAY, true);
cv::Mat grad[2];
mGrad[0].resize(imageGradMag.rows, imageGradMag.cols);
grad[0] = cv::Mat(imageGradMag.rows, imageGradMag.cols, cv::DataType<real>::type, (void*)mGrad[0].data());
mGrad[1].resize(imageGradMag.rows, imageGradMag.cols);
grad[1] = cv::Mat(imageGradMag.rows, imageGradMag.cols, cv::DataType<real>::type, (void*)mGrad[1].data());
#if 1
cv::Sobel(imageGradMag, grad[0], cv::DataType<real>::type, 1, 0, 3, 1.0/8.0);
cv::Sobel(imageGradMag, grad[1], cv::DataType<real>::type, 0, 1, 3, 1.0/8.0);
#elif 1
const TMatrix<real,3,5> kernel(CreateDerivativeKernel3x5());
cv::filter2D(imageGradMag, grad[0], cv::DataType<real>::type, kernel);
cv::filter2D(imageGradMag, grad[1], cv::DataType<real>::type, kernel.t());
#else
const TMatrix<real,5,7> kernel(CreateDerivativeKernel5x7());
cv::filter2D(imageGradMag, grad[0], cv::DataType<real>::type, kernel);
cv::filter2D(imageGradMag, grad[1], cv::DataType<real>::type, kernel.t());
#endif
(TImage<real>::EMatMap)imageGradMag = (mGrad[0].cwiseAbs2()+mGrad[1].cwiseAbs2()).cwiseSqrt();
// apply some blur on the gradient to lower noise/glossiness effects onto face-quality score
cv::GaussianBlur(imageGradMag, imageGradMag, cv::Size(15, 15), 0, 0, cv::BORDER_DEFAULT);
// select faces inside view frustum
Mesh::FaceIdxArr cameraFaces;
Mesh::FacesInserter inserter(cameraFaces);
const TFrustum<float,5> frustum(Matrix3x4f(imageData.camera.P), (float)imageData.width, (float)imageData.height);
octree.Traverse(frustum, inserter);
// project all triangles in this view and keep the closest ones
faceMap.create(imageData.GetSize());
depthMap.create(imageData.GetSize());
RasterMesh rasterer(vertices, imageData.camera, depthMap, faceMap);
if (nIgnoreMaskLabel >= 0) {
// import mask
BitMatrix bmask;
DepthEstimator::ImportIgnoreMask(imageData, imageData.GetSize(), (uint16_t)OPTDENSE::nIgnoreMaskLabel, bmask, &rasterer.mask);
} else if (nIgnoreMaskLabel == -1) {
// creating mask to discard invalid regions created during image radial undistortion
rasterer.mask = DetectInvalidImageRegions(imageData.image);
#if TD_VERBOSE != TD_VERBOSE_OFF
if (VERBOSITY_LEVEL > 2)
cv::imwrite(String::FormatString("umask%04d.png", idxView), rasterer.mask);
#endif
}
rasterer.Clear();
for (FIndex idxFace : cameraFaces) {
rasterer.validFace = true;
const Face& facet = faces[idxFace];
rasterer.idxFace = idxFace;
rasterer.Project(facet);
if (!rasterer.validFace)
rasterer.Project(facet);
}
// compute the projection area of visible faces
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
CLISTDEF0IDX(uint32_t,FIndex) areas(faces.size());
areas.Memset(0);
#endif
#ifdef TEXOPT_USE_OPENMP
#pragma omp critical
#endif
{
// faceQuality is influenced by :
// + area: the higher the area the more gradient scores will be added to the face quality
// + sharpness: sharper image or image resolution or how close is to the face will result in higher gradient on the same face
// ON GLOSS IMAGES it happens to have a high volatile sharpness depending on how the light reflects under different angles
// + angle: low angle increases the surface area
for (int j=0; j<faceMap.rows; ++j) {
for (int i=0; i<faceMap.cols; ++i) {
const FIndex& idxFace = faceMap(j,i);
ASSERT((idxFace == NO_ID && depthMap(j,i) == 0) || (idxFace != NO_ID && depthMap(j,i) > 0));
if (idxFace == NO_ID)
continue;
FaceDataArr& faceDatas = facesDatas[idxFace];
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
uint32_t& area = areas[idxFace];
if (area++ == 0) {
#else
if (faceDatas.empty() || faceDatas.back().idxView != idxView) {
#endif
// create new face-data
FaceData& faceData = faceDatas.emplace_back();
faceData.idxView = idxView;
faceData.quality = imageGradMag(j,i);
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
faceData.color = imageData.image(j,i);
#endif
} else {
// update face-data
ASSERT(!faceDatas.empty());
FaceData& faceData = faceDatas.back();
ASSERT(faceData.idxView == idxView);
faceData.quality += imageGradMag(j,i);
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
faceData.color += Color(imageData.image(j,i));
#endif
}
}
}
// adjust face quality with camera angle relative to face normal
// tries to increase chances of a camera with perpendicular view on the surface (smoothened normals) to be selected
FOREACH(idxFace, facesDatas) {
FaceDataArr& faceDatas = facesDatas[idxFace];
if (faceDatas.empty() || faceDatas.back().idxView != idxView)
continue;
const Face& f = faces[idxFace];
const Vertex faceCenter((vertices[f[0]] + vertices[f[1]] + vertices[f[2]]) / 3.f);
const Point3f camDir(Cast<Mesh::Type>(imageData.camera.C) - faceCenter);
const Normal& faceNormal = scene.mesh.faceNormals[idxFace];
const float cosFaceCam(MAXF(0.001f, ComputeAngle(camDir.ptr(), faceNormal.ptr())));
faceDatas.back().quality *= SQUARE(cosFaceCam);
}
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
FOREACH(idxFace, areas) {
const uint32_t& area = areas[idxFace];
if (area > 0) {
Color& color = facesDatas[idxFace].back().color;
color = RGB2YCBCR(Color(color * (1.f/(float)area)));
}
}
#endif
}
++progress;
}
#ifdef TEXOPT_USE_OPENMP
if (bAbort)
return false;
#endif
progress.close();
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
if (fOutlierThreshold > 0) {
// try to detect outlier views for each face
// (views for which the face is occluded by a dynamic object in the scene, ex. pedestrians)
for (FaceDataArr& faceDatas: facesDatas)
FaceOutlierDetection(faceDatas, fOutlierThreshold);
}
#endif
return true;
}
// order the camera view scores with highest score first and return the list of first <minCommonCameras> cameras
// ratioAngleToQuality represents the ratio in witch we combine normal angle to quality for a face to obtain the selection score
// - a ratio of 1 means only angle is considered
// - a ratio of 0.5 means angle and quality are equally important
// - a ratio of 0 means only camera quality is considered when sorting
IIndexArr MeshTexture::SelectBestView(const FaceDataArr& faceDatas, FIndex fid, unsigned minCommonCameras, float ratioAngleToQuality) const
{
ASSERT(!faceDatas.empty());
#if 1
// compute scores based on the view quality and its angle to the face normal
float maxQuality = 0;
for (const FaceData& faceData: faceDatas)
maxQuality = MAXF(maxQuality, faceData.quality);
const Face& f = faces[fid];
const Vertex faceCenter((vertices[f[0]] + vertices[f[1]] + vertices[f[2]]) / 3.f);
CLISTDEF0IDX(float,IIndex) scores(faceDatas.size());
FOREACH(idxFaceData, faceDatas) {
const FaceData& faceData = faceDatas[idxFaceData];
const Image& imageData = images[faceData.idxView];
const Point3f camDir(Cast<Mesh::Type>(imageData.camera.C) - faceCenter);
const Normal& faceNormal = scene.mesh.faceNormals[fid];
const float cosFaceCam(ComputeAngle(camDir.ptr(), faceNormal.ptr()));
scores[idxFaceData] = ratioAngleToQuality*cosFaceCam + (1.f-ratioAngleToQuality)*faceData.quality/maxQuality;
}
// and sort the scores from to highest to smallest to get the best overall cameras
IIndexArr scorePodium(faceDatas.size());
std::iota(scorePodium.begin(), scorePodium.end(), 0);
scorePodium.Sort([&scores](IIndex i, IIndex j) {
return scores[i] > scores[j];
});
#else
// sort qualityPodium in relation to faceDatas[index].quality decreasing
IIndexArr qualityPodium(faceDatas.size());
std::iota(qualityPodium.begin(), qualityPodium.end(), 0);
qualityPodium.Sort([&faceDatas](IIndex i, IIndex j) {
return faceDatas[i].quality > faceDatas[j].quality;
});
// sort anglePodium in relation to face angle to camera increasing
const Face& f = faces[fid];
const Vertex faceCenter((vertices[f[0]] + vertices[f[1]] + vertices[f[2]]) / 3.f);
CLISTDEF0IDX(float,IIndex) cameraAngles(0, faceDatas.size());
for (const FaceData& faceData: faceDatas) {
const Image& imageData = images[faceData.idxView];
const Point3f camDir(Cast<Mesh::Type>(imageData.camera.C) - faceCenter);
const Normal& faceNormal = scene.mesh.faceNormals[fid];
const float cosFaceCam(ComputeAngle(camDir.ptr(), faceNormal.ptr()));
cameraAngles.emplace_back(cosFaceCam);
}
IIndexArr anglePodium(faceDatas.size());
std::iota(anglePodium.begin(), anglePodium.end(), 0);
anglePodium.Sort([&cameraAngles](IIndex i, IIndex j) {
return cameraAngles[i] > cameraAngles[j];
});
// combine podium scores to get overall podium
// and sort the scores in smallest to highest to get the best overall camera for current virtual face
CLISTDEF0IDX(float,IIndex) scores(faceDatas.size());
scores.Memset(0);
FOREACH(sIdx, faceDatas) {
scores[anglePodium[sIdx]] += ratioAngleToQuality * (sIdx+1);
scores[qualityPodium[sIdx]] += (1.f - ratioAngleToQuality) * (sIdx+1);
}
IIndexArr scorePodium(faceDatas.size());
std::iota(scorePodium.begin(), scorePodium.end(), 0);
scorePodium.Sort([&scores](IIndex i, IIndex j) {
return scores[i] < scores[j];
});
#endif
IIndexArr cameras(MIN(minCommonCameras, faceDatas.size()));
FOREACH(i, cameras)
cameras[i] = faceDatas[scorePodium[i]].idxView;
return cameras;
}
static bool IsFaceVisible(const MeshTexture::FaceDataArr& faceDatas, const IIndexArr& cameraList) {
size_t camFoundCounter(0);
for (const MeshTexture::FaceData& faceData : faceDatas) {
const IIndex cfCam = faceData.idxView;
for (IIndex camId : cameraList) {
if (cfCam == camId) {
if (++camFoundCounter == cameraList.size())
return true;
break;
}
}
}
return camFoundCounter == cameraList.size();
}
// build virtual faces with:
// - similar normal
// - high percentage of common images that see them
void MeshTexture::CreateVirtualFaces(const FaceDataViewArr& facesDatas, FaceDataViewArr& virtualFacesDatas, VirtualFaceIdxsArr& virtualFaces, unsigned minCommonCameras, float thMaxNormalDeviation) const
{
const float ratioAngleToQuality(0.67f);
const float cosMaxNormalDeviation(COS(FD2R(thMaxNormalDeviation)));
Mesh::FaceIdxArr remainingFaces(faces.size());
std::iota(remainingFaces.begin(), remainingFaces.end(), 0);
std::vector<bool> selectedFaces(faces.size(), false);
cQueue<FIndex, FIndex, 0> currentVirtualFaceQueue;
std::unordered_set<FIndex> queuedFaces;
do {
const FIndex startPos = RAND() % remainingFaces.size();
const FIndex virtualFaceCenterFaceID = remainingFaces[startPos];
ASSERT(currentVirtualFaceQueue.IsEmpty());
const Normal& normalCenter = scene.mesh.faceNormals[virtualFaceCenterFaceID];
const FaceDataArr& centerFaceDatas = facesDatas[virtualFaceCenterFaceID];
// select the common cameras
Mesh::FaceIdxArr virtualFace;
FaceDataArr virtualFaceDatas;
if (centerFaceDatas.empty()) {
virtualFace.emplace_back(virtualFaceCenterFaceID);
selectedFaces[virtualFaceCenterFaceID] = true;
const auto posToErase = remainingFaces.FindFirst(virtualFaceCenterFaceID);
ASSERT(posToErase != Mesh::FaceIdxArr::NO_INDEX);
remainingFaces.RemoveAtMove(posToErase);
} else {
const IIndexArr selectedCams = SelectBestView(centerFaceDatas, virtualFaceCenterFaceID, minCommonCameras, ratioAngleToQuality);
currentVirtualFaceQueue.AddTail(virtualFaceCenterFaceID);
queuedFaces.clear();
do {
const FIndex currentFaceId = currentVirtualFaceQueue.GetHead();
currentVirtualFaceQueue.PopHead();
// check for condition to add in current virtual face
// normal angle smaller than thMaxNormalDeviation degrees
const Normal& faceNormal = scene.mesh.faceNormals[currentFaceId];
const float cosFaceToCenter(ComputeAngleN(normalCenter.ptr(), faceNormal.ptr()));
if (cosFaceToCenter < cosMaxNormalDeviation)
continue;
// check if current face is seen by all cameras in selectedCams
ASSERT(!selectedCams.empty());
if (!IsFaceVisible(facesDatas[currentFaceId], selectedCams))
continue;
// remove it from remaining faces and add it to the virtual face
{
const auto posToErase = remainingFaces.FindFirst(currentFaceId);
ASSERT(posToErase != Mesh::FaceIdxArr::NO_INDEX);
remainingFaces.RemoveAtMove(posToErase);
selectedFaces[currentFaceId] = true;
virtualFace.push_back(currentFaceId);
}
// add all new neighbors to the queue
const Mesh::FaceFaces& ffaces = faceFaces[currentFaceId];
for (int i = 0; i < 3; ++i) {
const FIndex fIdx = ffaces[i];
if (fIdx == NO_ID)
continue;
if (!selectedFaces[fIdx] && queuedFaces.find(fIdx) == queuedFaces.end()) {
currentVirtualFaceQueue.AddTail(fIdx);
queuedFaces.emplace(fIdx);
}
}
} while (!currentVirtualFaceQueue.IsEmpty());
// compute virtual face quality and create virtual face
for (IIndex idxView: selectedCams) {
FaceData& virtualFaceData = virtualFaceDatas.emplace_back();
virtualFaceData.quality = 0;
virtualFaceData.idxView = idxView;
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
virtualFaceData.color = Point3f::ZERO;
#endif
unsigned processedFaces(0);
for (FIndex fid : virtualFace) {
const FaceDataArr& faceDatas = facesDatas[fid];
for (FaceData& faceData: faceDatas) {
if (faceData.idxView == idxView) {
virtualFaceData.quality += faceData.quality;
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
virtualFaceData.color += faceData.color;
#endif
++processedFaces;
break;
}
}
}
ASSERT(processedFaces > 0);
virtualFaceData.quality /= processedFaces;
#if TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
virtualFaceData.color /= processedFaces;
#endif
}
ASSERT(!virtualFaceDatas.empty());
}
virtualFacesDatas.emplace_back(std::move(virtualFaceDatas));
virtualFaces.emplace_back(std::move(virtualFace));
} while (!remainingFaces.empty());
}
#if TEXOPT_FACEOUTLIER == TEXOPT_FACEOUTLIER_MEDIAN
// decrease the quality of / remove all views in which the face's projection
// has a much different color than in the majority of views
bool MeshTexture::FaceOutlierDetection(FaceDataArr& faceDatas, float thOutlier) const
{
// consider as outlier if the absolute difference to the median is outside this threshold
if (thOutlier <= 0)
thOutlier = 0.15f*255.f;
// init colors array
if (faceDatas.size() <= 3)
return false;
FloatArr channels[3];
for (int c=0; c<3; ++c)
channels[c].resize(faceDatas.size());
FOREACH(i, faceDatas) {
const Color& color = faceDatas[i].color;
for (int c=0; c<3; ++c)
channels[c][i] = color[c];
}
// find median
for (int c=0; c<3; ++c)
channels[c].Sort();
const unsigned idxMedian(faceDatas.size() >> 1);
Color median;
for (int c=0; c<3; ++c)
median[c] = channels[c][idxMedian];
// abort if there are not at least 3 inliers
int nInliers(0);
BoolArr inliers(faceDatas.size());
FOREACH(i, faceDatas) {
const Color& color = faceDatas[i].color;
for (int c=0; c<3; ++c) {
if (ABS(median[c]-color[c]) > thOutlier) {
inliers[i] = false;
goto CONTINUE_LOOP;
}
}
inliers[i] = true;
++nInliers;
CONTINUE_LOOP:;
}
if (nInliers == faceDatas.size())
return true;
if (nInliers < 3)
return false;
// remove outliers
RFOREACH(i, faceDatas)
if (!inliers[i])
faceDatas.RemoveAt(i);
return true;
}
#elif TEXOPT_FACEOUTLIER != TEXOPT_FACEOUTLIER_NA
// A multi-variate normal distribution which is NOT normalized such that the integral is 1
// - centered is the vector for which the function is to be evaluated with the mean subtracted [Nx1]
// - X is the vector for which the function is to be evaluated [Nx1]
// - mu is the mean around which the distribution is centered [Nx1]
// - covarianceInv is the inverse of the covariance matrix [NxN]
// return exp(-1/2 * (X-mu)^T * covariance_inv * (X-mu))
template <typename T, int N>
inline T MultiGaussUnnormalized(const Eigen::Matrix<T,N,1>& centered, const Eigen::Matrix<T,N,N>& covarianceInv) {
return EXP(T(-0.5) * T(centered.adjoint() * covarianceInv * centered));
}
template <typename T, int N>
inline T MultiGaussUnnormalized(const Eigen::Matrix<T,N,1>& X, const Eigen::Matrix<T,N,1>& mu, const Eigen::Matrix<T,N,N>& covarianceInv) {
return MultiGaussUnnormalized<T,N>(X - mu, covarianceInv);
}
// decrease the quality of / remove all views in which the face's projection
// has a much different color than in the majority of views
bool MeshTexture::FaceOutlierDetection(FaceDataArr& faceDatas, float thOutlier) const
{
// reject all views whose gauss value is below this threshold
if (thOutlier <= 0)
thOutlier = 6e-2f;
const float minCovariance(1e-3f); // if all covariances drop below this the outlier detection aborted
const unsigned maxIterations(10);
const unsigned minInliers(4);
// init colors array
if (faceDatas.size() <= minInliers)
return false;
Eigen::Matrix3Xd colorsAll(3, faceDatas.size());
BoolArr inliers(faceDatas.size());
FOREACH(i, faceDatas) {
colorsAll.col(i) = ((const Color::EVec)faceDatas[i].color).cast<double>();
inliers[i] = true;
}
// perform outlier removal; abort if something goes wrong
// (number of inliers below threshold or can not invert the covariance)
size_t numInliers(faceDatas.size());
Eigen::Vector3d mean;
Eigen::Matrix3d covariance;
Eigen::Matrix3d covarianceInv;
for (unsigned iter = 0; iter < maxIterations; ++iter) {
// compute the mean color and color covariance only for inliers
const Eigen::Block<Eigen::Matrix3Xd,3,Eigen::Dynamic,!Eigen::Matrix3Xd::IsRowMajor> colors(colorsAll.leftCols(numInliers));
mean = colors.rowwise().mean();
const Eigen::Matrix3Xd centered(colors.colwise() - mean);
covariance = (centered * centered.transpose()) / double(colors.cols() - 1);
// stop if all covariances gets very small
if (covariance.array().abs().maxCoeff() < minCovariance) {
// remove the outliers
RFOREACH(i, faceDatas)
if (!inliers[i])
faceDatas.RemoveAt(i);
return true;
}
// invert the covariance matrix
// (FullPivLU not the fastest, but gives feedback about numerical stability during inversion)
const Eigen::FullPivLU<Eigen::Matrix3d> lu(covariance);
if (!lu.isInvertible())
return false;
covarianceInv = lu.inverse();
// filter inliers
// (all views with a gauss value above the threshold)
numInliers = 0;
bool bChanged(false);
FOREACH(i, faceDatas) {
const Eigen::Vector3d color(((const Color::EVec)faceDatas[i].color).cast<double>());
const double gaussValue(MultiGaussUnnormalized<double,3>(color, mean, covarianceInv));
bool& inlier = inliers[i];
if (gaussValue > thOutlier) {
// set as inlier
colorsAll.col(numInliers++) = color;
if (inlier != true) {
inlier = true;
bChanged = true;
}
} else {
// set as outlier
if (inlier != false) {
inlier = false;
bChanged = true;
}
}
}
if (numInliers == faceDatas.size())