-
Notifications
You must be signed in to change notification settings - Fork 11
/
faceshapefromshading_exp.cpp
2246 lines (1879 loc) · 97.9 KB
/
faceshapefromshading_exp.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
#ifndef FACE_SHAPE_FROM_SHADING_H
#define FACE_SHAPE_FROM_SHADING_H
#include "Geometry/geometryutils.hpp"
#include "Utils/utility.hpp"
#include <QApplication>
#include <QOpenGLContext>
#include <QOpenGLFramebufferObject>
#include <QOffscreenSurface>
#include <QDir>
#include <QFile>
#include <GL/freeglut_std.h>
#include <opencv2/opencv.hpp>
#include "common.h"
#include "ceres/ceres.h"
#include <MultilinearReconstruction/basicmesh.h>
#include <MultilinearReconstruction/costfunctions.h>
#include <MultilinearReconstruction/ioutilities.h>
#include <MultilinearReconstruction/multilinearmodel.h>
#include <MultilinearReconstruction/parameters.h>
#include <MultilinearReconstruction/OffscreenMeshVisualizer.h>
#include <MultilinearReconstruction/statsutils.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>
#include <boost/timer/timer.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;
#include "nlohmann/json.hpp"
using json = nlohmann::json;
#include "cost_functions.h"
#include "defs.h"
#include "utils.h"
po::variables_map ParseCommandlineOptions(int argc, char** argv) {
po::options_description desc("Options");
desc.add_options()
("help", "Print help messages")
("settings_file", po::value<string>()->required(), "Settings file.")
("blendshapes_path", po::value<string>()->required(), "Input blendshapes path.")
("init_recon_path", po::value<string>()->required(), "Initial reconstructions path.")
("iter", po::value<int>()->required(), "The iteration number.")
("subdivision", "Whether the input blendshapes are subdivided or not.")
("subdivision_depth", po::value<int>(), "The depth of subdivision.");
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if(vm.count("help")) {
cout << desc << endl;
exit(1);
}
return vm;
} catch(po::error& e) {
cerr << "Error: " << e.what() << endl;
cerr << desc << endl;
exit(1);
}
}
int main(int argc, char **argv) {
po::variables_map vm = ParseCommandlineOptions(argc, argv);
QApplication a(argc, argv);
glutInit(&argc, argv);
//google::InitGoogleLogging(argv[0]);
const string home_directory = QDir::homePath().toStdString();
cout << "Home dir: " << home_directory << endl;
// load the settings file
PhGUtils::message("Loading global settings ...");
json global_settings = json::parse(ifstream(home_directory + "/Codes/FaceShapeFromShading/settings.txt"));
PhGUtils::message("done.");
cout << setw(2) << global_settings << endl;
// Multilinear model related files
const string model_filename(home_directory + "/Data/Multilinear/blendshape_core.tensor");
const string id_prior_filename(home_directory + "/Data/Multilinear/blendshape_u_0_aug.tensor");
const string exp_prior_filename(home_directory + "/Data/Multilinear/blendshape_u_1_aug.tensor");
const string template_mesh_filename(home_directory + "/Data/Multilinear/template.obj");
const string contour_points_filename(home_directory + "/Data/Multilinear/contourpoints.txt");
const string landmarks_filename(home_directory + "/Data/Multilinear/landmarks_73.txt");
// The following files are related to the base template, i.e. the one before subdivision.
// TODO Need to create a set of index map and pixel map for different level of subdivisions.
// Maybe in the form of face indices mapping
const string albedo_index_map_filename(home_directory + "/Data/Multilinear/albedo_index.png");
const string albedo_pixel_map_filename(home_directory + "/Data/Multilinear/albedo_pixel.png");
const string mean_albedo_filename(home_directory + "/Data/Texture/mean_texture.png");
const string core_face_region_filename(home_directory + "/Data/Multilinear/albedos/core_face.png");
const string valid_faces_indices_filename(home_directory + "/Data/Multilinear/face_region_indices.txt");
const string face_boundary_indices_filename(home_directory + "/Data/Multilinear/face_boundary_indices.txt");
const string hair_region_filename(home_directory + "/Data/Multilinear/hair_region_indices.txt");
BasicMesh mesh(template_mesh_filename);
auto landmarks = LoadIndices(landmarks_filename);
auto contour_indices = LoadContourIndices(contour_points_filename);
auto valid_faces_indices_quad = LoadIndices(valid_faces_indices_filename);
// @HACK each quad face is triangulated, so the indices change from i to [2*i, 2*i+1]
vector<int> valid_faces_indices;
for(auto fidx : valid_faces_indices_quad) {
valid_faces_indices.push_back(fidx*2);
valid_faces_indices.push_back(fidx*2+1);
}
auto faces_boundary_indices_quad = LoadIndices(face_boundary_indices_filename);
// @HACK each quad face is triangulated, so the indices change from i to [2*i, 2*i+1]
unordered_set<int> face_boundary_indices;
for(auto fidx : faces_boundary_indices_quad) {
face_boundary_indices.insert(fidx*2);
face_boundary_indices.insert(fidx*2+1);
}
auto hair_region_indices_quad = LoadIndices(hair_region_filename);
// @HACK each quad face is triangulated, so the indices change from i to [2*i, 2*i+1]
unordered_set<int> hair_region_indices;
for(auto fidx : hair_region_indices_quad) {
hair_region_indices.insert(fidx*2);
hair_region_indices.insert(fidx*2+1);
}
const int tex_size = 2048;
if(vm.count("subdivision")) {
// HACK: subdivie the template mesh so it has the same topology as the input
// blendshapes
const int max_subdivisions = vm["subdivision_depth"].as<int>();
for(int i=0;i<max_subdivisions;++i) {
mesh.BuildHalfEdgeMesh();
cout << "Subdivision #" << i << endl;
mesh.Subdivide();
cout << "#faces = " << mesh.NumFaces() << endl;
}
// HACK: each valid face i becomes [4i, 4i+1, 4i+2, 4i+3] after the each
// subdivision. See BasicMesh::Subdivide for details
for(int i=0;i<max_subdivisions;++i) {
vector<int> valid_faces_indices_new;
for(auto fidx : valid_faces_indices) {
int fidx_base = fidx*4;
valid_faces_indices_new.push_back(fidx_base);
valid_faces_indices_new.push_back(fidx_base+1);
valid_faces_indices_new.push_back(fidx_base+2);
valid_faces_indices_new.push_back(fidx_base+3);
}
valid_faces_indices = valid_faces_indices_new;
}
}
// Generate index map for albedo
const bool gen_albedo_index_map = true;
QImage albedo_index_map = GetIndexMap(albedo_index_map_filename,
mesh,
gen_albedo_index_map,
tex_size);
// Compute the barycentric coordinates for each pixel
const bool gen_albedo_pixel_map = true;
vector<vector<PixelInfo>> albedo_pixel_map;
QImage pixel_map_image;
tie(pixel_map_image, albedo_pixel_map) = GetPixelCoordinatesMap(albedo_pixel_map_filename,
albedo_index_map,
mesh,
gen_albedo_pixel_map,
tex_size);
const string settings_filename = vm["settings_file"].as<string>();
int iteration_index = vm["iter"].as<int>();
const string recon_path = vm["init_recon_path"].as<string>();
const string blendshapes_path = vm["blendshapes_path"].as<string>();
// Parse the setting file and load image related resources
fs::path settings_filepath(settings_filename);
// Create SFS results directory
fs::path image_files_path = settings_filepath.parent_path();
fs::path results_path = image_files_path / fs::path("iteration_" + to_string(iteration_index)) / fs::path("SFS");
fs::create_directories(results_path);
// Load the settings file
cout << "Reading settings file " << settings_filename << endl;
vector<pair<string, string>> image_points_filenames = ParseSettingsFile(settings_filename);
cout << image_points_filenames.size() << " input images." << endl;
// Load the image bundles: image, points and its reconstruction result
vector<ImageBundle> image_bundles;
for(auto& p : image_points_filenames) {
fs::path image_filename = settings_filepath.parent_path() / fs::path(p.first);
fs::path pts_filename = settings_filepath.parent_path() / fs::path(p.second);
fs::path res_filename = fs::path(recon_path) / fs::path(p.first + ".res");
cout << "[" << image_filename << ", " << pts_filename << "]" << endl;
auto image_points_pair = LoadImageAndPoints(image_filename.string(), pts_filename.string(), false);
auto recon_results = LoadReconstructionResult(res_filename.string());
image_bundles.push_back(ImageBundle(p.first, image_points_pair.first, image_points_pair.second, recon_results));
}
cout << "Image bundles loaded." << endl;
// Load all the input blendshapes
const int num_blendshapes = 46;
vector<BasicMesh> blendshapes(num_blendshapes+1);
for(int i=0;i<=num_blendshapes;++i) {
blendshapes[i].LoadOBJMesh( blendshapes_path + "/" + "B_" + to_string(i) + ".obj" );
blendshapes[i].ComputeNormals();
}
MultilinearModel model(model_filename);
vector<vector<glm::dvec3>> mean_texture(tex_size, vector<glm::dvec3>(tex_size, glm::dvec3(0, 0, 0)));
cv::Mat mean_texture_mat(tex_size, tex_size, CV_64FC3);
vector<vector<double>> mean_texture_weight(tex_size, vector<double>(tex_size, 0));
// Collect texture information from each input (image, mesh) pair to obtain mean texture
QImage mean_texture_image;
vector<vector<int>> face_indices_maps;
json mean_texture_options = global_settings["mean_texture_options"];
mean_texture_options["use_blendshapes"] = true;
mean_texture_options["core_face_region_filename"] = core_face_region_filename;
mean_texture_options["symmetric_texture"] = true;
tie(mean_texture_image, face_indices_maps) = GenerateMeanTexture(
image_bundles,
model, // it is not used when use_blendshapes = true
blendshapes,
mesh,
tex_size,
albedo_pixel_map,
mean_texture,
mean_texture_weight,
mean_texture_mat,
mean_albedo_filename,
results_path,
mean_texture_options.dump()
);
// [Shape from shading]
{
// [Shape from shading] initialization
const int num_images = image_bundles.size();
vector<VectorXd> lighting_coeffs(num_images, VectorXd::Zero(9));
for(auto &lco : lighting_coeffs) lco[0] = 1.0;
vector<cv::Mat> normal_maps_ref(num_images);
vector<cv::Mat> normal_maps_ref_LoG(num_images);
vector<cv::Mat> normal_maps(num_images);
vector<cv::Mat> depth_maps_ref(num_images);
vector<cv::Mat> depth_maps_ref_LoG(num_images);
vector<cv::Mat> depth_maps(num_images);
vector<cv::Mat> zmaps(num_images);
vector<vector<int>> valie_pixels_map(num_images);
vector<cv::Mat> albedos_ref(num_images);
vector<cv::Mat> albedos_ref_LoG(num_images);
vector<cv::Mat> albedos(num_images);
vector<vector<glm::ivec2>> valid_depth_pixels(num_images);
// generate reference normal map and depth map
for(int i=0;i<num_images;++i) {
auto& bundle = image_bundles[i];
const int image_index = get_image_index(bundle.filename);
// get the geometry of the mesh, update normal
/*
model.ApplyWeights(bundle.params.params_model.Wid, bundle.params.params_model.Wexp);
mesh.UpdateVertices(model.GetTM());
mesh.ComputeNormals();
*/
ApplyWeights(mesh, blendshapes, bundle.params.params_model.Wexp_FACS);
// for each image bundle, render the mesh to FBO with culling to get the visible triangles
OffscreenMeshVisualizer visualizer(bundle.image.width(), bundle.image.height());
visualizer.SetMVPMode(OffscreenMeshVisualizer::CamPerspective);
visualizer.SetRenderMode(OffscreenMeshVisualizer::Normal);
visualizer.BindMesh(mesh);
visualizer.SetCameraParameters(bundle.params.params_cam);
visualizer.SetMeshRotationTranslation(bundle.params.params_model.R, bundle.params.params_model.T);
visualizer.SetFacesToRender(valid_faces_indices);
pair<QImage, vector<float>> img_and_depth = visualizer.RenderWithDepth();
QImage img = img_and_depth.first;
const vector<float>& depth = img_and_depth.second;
// get camera parameters for computing actual z values
const double aspect_ratio =
bundle.params.params_cam.image_size.x / bundle.params.params_cam.image_size.y;
const double far = bundle.params.params_cam.far;
// near is the focal length
const double near = bundle.params.params_cam.focal_length;
const double top = near * tan(0.5 * bundle.params.params_cam.fovy);
const double right = top * aspect_ratio;
glm::dmat4 Mproj = glm::dmat4(near/right, 0, 0, 0,
0, near/top, 0, 0,
0, 0, -(far+near)/(far-near), -1,
0, 0, -2.0 * far * near / (far - near), 0.0);
glm::ivec4 viewport(0, 0, bundle.image.width(), bundle.image.height());
glm::dmat4 Rmat = glm::eulerAngleYXZ(bundle.params.params_model.R[0],
bundle.params.params_model.R[1],
bundle.params.params_model.R[2]);
glm::dmat4 Tmat = glm::translate(glm::dmat4(1.0),
glm::dvec3(bundle.params.params_model.T[0],
bundle.params.params_model.T[1],
bundle.params.params_model.T[2]));
glm::dmat4 Mview = Tmat * Rmat;
// copy to normal maps and depth maps
normal_maps_ref[i] = cv::Mat(img.height(), img.width(), CV_64FC3);
depth_maps_ref[i] = cv::Mat(img.height(), img.width(), CV_64F);
depth_maps[i] = cv::Mat(img.height(), img.width(), CV_64FC3);
zmaps[i] = cv::Mat(img.height(), img.width(), CV_32F);
QImage depth_img = img;
vector<glm::dvec3> point_cloud;
vector<glm::dvec4> point_cloud_with_id;
vector<double> output_depth_map; output_depth_map.reserve(img.height()*img.width());
//#pragma omp parallel for
for(int y=0;y<img.height();++y) {
for(int x=0;x<img.width();++x) {
auto pix = img.pixel(x, y);
// 0~255 range
double nx = qRed(pix) / 255.0 * 2.0 - 1.0;
double ny = qGreen(pix) / 255.0 * 2.0 - 1.0;
double nz = max(0.0, qBlue(pix) / 255.0 * 2.0 - 1.0);
double theta, phi;
tie(theta, phi) = normal2sphericalcoords<double>(nx, ny, nz);
tie(nx, ny, nz) = sphericalcoords2normal<double>(theta, phi);
normal_maps_ref[i].at<cv::Vec3d>(y, x) = cv::Vec3d(nx, ny, nz);
// get the screen z-value
double dvalue = depth[(img.height()-1-y)*img.width()+x];
if(dvalue < 1) {
// unproject this point to obtain the actual z value
glm::dvec3 XYZ = glm::unProject(glm::dvec3(x, img.height()-1-y, dvalue), Mview, Mproj, viewport);
glm::dvec4 Rxyz = Rmat * glm::dvec4(XYZ.x, XYZ.y, XYZ.z, 1);
point_cloud.push_back(glm::dvec3(Rxyz.x, Rxyz.y, Rxyz.z));
point_cloud_with_id.push_back(glm::dvec4(Rxyz.x, Rxyz.y, Rxyz.z, y*img.width()+x));
depth_maps_ref[i].at<double>(y, x) = Rxyz.z;
depth_maps[i].at<cv::Vec3d>(y, x) = cv::Vec3d(Rxyz.x, Rxyz.y, Rxyz.z);
output_depth_map.push_back(Rxyz.x); output_depth_map.push_back(Rxyz.y); output_depth_map.push_back(Rxyz.z);
zmaps[i].at<float>(y, x) = Rxyz.z;
depth_img.setPixel(x, y, qRgb(dvalue*255, 0, (1-dvalue)*255));
valie_pixels_map[i].push_back(y * img.width() + x);
} else {
depth_img.setPixel(x, y, qRgb(255, 255, 255));
depth_maps_ref[i].at<double>(y, x) = -1e6;
depth_maps[i].at<cv::Vec3d>(y, x) = cv::Vec3d(0, 0, -1e6);
output_depth_map.push_back(0); output_depth_map.push_back(0); output_depth_map.push_back(-1e6);
zmaps[i].at<float>(y, x) = -1e6;
}
}
}
img.save( (results_path / fs::path("normal" + std::to_string(image_index) + ".png")).string().c_str() );
depth_img.save( (results_path / fs::path("depth" + std::to_string(image_index) + ".png")).string().c_str() );
// Write out the entire depth map
{
ofstream fout( (results_path / fs::path("depth_map" + std::to_string(image_index) + ".bin")).string(), ios::binary );
int depth_map_size[] = {img.height(), img.width()};
fout.write(reinterpret_cast<char*>(depth_map_size), sizeof(int)*2);
fout.write(reinterpret_cast<char*>(output_depth_map.data()), sizeof(double)*img.height()*img.width()*3);
fout.close();
}
// Write out the depth map as a per-pixel mesh
{
ofstream fout((results_path / fs::path("depth_mesh" + std::to_string(image_index) + ".obj")).string());
vector<int> depth_node_map(img.width()*img.height(), 0);
for(int j=0;j<point_cloud_with_id.size();++j) {
auto& p = point_cloud_with_id[j];
fout << "v " << p.x << ' ' << p.y << ' ' << p.z << '\n';
depth_node_map[static_cast<int>(p.w)] = j + 1;
}
for(int j=0;j<point_cloud_with_id.size();++j) {
int idx = point_cloud_with_id[j].w;
int r = idx / img.width(), c = idx % img.width();
int lidx = idx - 1;
int ridx = idx + 1;
int uidx = idx - img.width();
int didx = idx + img.width();
if(ridx < img.width()*img.height() && didx < img.width()*img.height()) {
if(depth_node_map[ridx] > 0 && depth_node_map[didx] > 0) {
fout << "f " << depth_node_map[idx] << " " << depth_node_map[didx] << " " << depth_node_map[ridx] << '\n';
}
}
if(lidx >= 0 && uidx >= 0) {
if(depth_node_map[lidx] > 0 && depth_node_map[uidx] > 0) {
fout << "f " << depth_node_map[idx] << " " << depth_node_map[uidx] << " " << depth_node_map[lidx] << '\n';
}
}
}
fout.close();
}
// Write out the initial point cloud
{
ofstream fout( (results_path / fs::path("point_cloud" + std::to_string(image_index) + ".txt")).string() );
for(auto p : point_cloud) {
fout << p.x << ' ' << p.y << ' ' << p.z << endl;
}
fout.close();
}
}
// make a copy, use it as initial value
normal_maps = normal_maps_ref;
// initialize albedos by rendering the mesh with texture
for(int i=0;i<num_images;++i) {
// copy to mean texture to albedos
auto& bundle = image_bundles[i];
const int image_index = get_image_index(bundle.filename);
// get the geometry of the mesh, update normal
/*
model.ApplyWeights(bundle.params.params_model.Wid, bundle.params.params_model.Wexp);
mesh.UpdateVertices(model.GetTM());
mesh.ComputeNormals();
*/
ApplyWeights(mesh, blendshapes, bundle.params.params_model.Wexp_FACS);
// for each image bundle, render the mesh to FBO with culling to get the visible triangles
OffscreenMeshVisualizer visualizer(bundle.image.width(), bundle.image.height());
visualizer.SetMVPMode(OffscreenMeshVisualizer::CamPerspective);
visualizer.SetRenderMode(OffscreenMeshVisualizer::TexturedMesh);
visualizer.BindMesh(mesh);
visualizer.BindTexture(mean_texture_image);
visualizer.SetCameraParameters(bundle.params.params_cam);
visualizer.SetMeshRotationTranslation(bundle.params.params_model.R, bundle.params.params_model.T);
visualizer.SetFacesToRender(valid_faces_indices);
QImage albedo_image = visualizer.Render(true);
albedos_ref[i] = cv::Mat(bundle.image.height(), bundle.image.width(), CV_64FC3);
//#pragma omp parallel for
for(int y=0;y<albedo_image.height();++y) {
for(int x=0;x<albedo_image.width();++x) {
QRgb pix = albedo_image.pixel(x, y);
unsigned char r = static_cast<unsigned char>(qRed(pix));
unsigned char g = static_cast<unsigned char>(qGreen(pix));
unsigned char b = static_cast<unsigned char>(qBlue(pix));
// convert from BGR to RGB
albedo_image.setPixel(x, y, qRgb(b, g, r));
}
}
albedo_image.save( (results_path / fs::path("albedo" + std::to_string(image_index) + ".png")).string().c_str() );
// color transfer from bundle.image to albedo_image, so the initial albedo
// is a better match
albedo_image = TransferColor(albedo_image, bundle.image, valie_pixels_map[i], valie_pixels_map[i]);
albedo_image.save( (results_path / fs::path("albedo_transferred_" + std::to_string(image_index) + ".png")).string().c_str() );
//#pragma omp parallel for
for(int y=0;y<albedo_image.height();++y) {
for(int x=0;x<albedo_image.width();++x) {
QRgb pix = albedo_image.pixel(x, y);
unsigned char r = static_cast<unsigned char>(qRed(pix));
unsigned char g = static_cast<unsigned char>(qGreen(pix));
unsigned char b = static_cast<unsigned char>(qBlue(pix));
// 0~255 range
albedos_ref[i].at<cv::Vec3d>(y, x) = cv::Vec3d(r, g, b);
}
}
// convert to [0, 1] range
albedos_ref[i] /= 255.0;
}
// HACK In preparation only mode, this program generates initial normal map,
// albedo, depth map and point clouds. The actual SFS is done in a separate
// program.
if (bool(global_settings["preparation_only"])) {
return 0;
}
// transfer the color from the input image to the reference albedo as initial albedo
albedos = albedos_ref;
for(int i=0;i<num_images;++i) {
auto &bundle = image_bundles[i];
// ====================================================================
// construct LoG matrix for this image
// ====================================================================
const int num_rows = bundle.image.height(), num_cols = bundle.image.width();
using Tripletd = Eigen::Triplet<double>;
using SparseMatrixd = Eigen::SparseMatrix<double, Eigen::RowMajor>;
const int kLoG = 2;
const double sigmaLoG = 1.0;
MatrixXd LoG = ComputeLoGKernel(kLoG, sigmaLoG);
vector<Tripletd> LoG_coeffs;
vector<vector<pair<int, double>>> LoG_coeffs_perpixel(num_rows*num_cols);
SparseMatrixd M_LoG(num_rows*num_cols, num_rows*num_cols);
{
boost::timer::auto_cpu_timer timer("[Shape from shading] M_LoG computation time = %w seconds.\n");
// collect the coefficients for each pixel
for (int r = 0; r < num_rows; ++r) {
for (int c = 0; c < num_cols; ++c) {
int pidx = r * num_cols + c;
for (int kr = -kLoG; kr <= kLoG; ++kr) {
int ri = r + kr;
if (ri < 0 || ri >= num_rows) continue;
for (int kc = -kLoG; kc <= kLoG; ++kc) {
int ci = c + kc;
if (ci < 0 || ci >= num_cols) continue;
int qidx = ri * num_cols + ci;
// add this element to the matrix
LoG_coeffs.push_back(Tripletd(pidx, qidx, LoG(kr+kLoG, kc+kLoG)));
LoG_coeffs_perpixel[pidx].push_back(make_pair(qidx, LoG(kr+kLoG, kc+kLoG)));
}
}
}
}
M_LoG.setFromTriplets(LoG_coeffs.begin(), LoG_coeffs.end());
}
// ====================================================================
// compute LoG filtered reference albedo and normal map
// ====================================================================
cv::Mat LoG_kernel(kLoG*2+1, kLoG*2+1, CV_64F);
for(int kr=0;kr<kLoG*2+1;++kr) {
for(int kc=0;kc<kLoG*2+1;++kc) {
LoG_kernel.at<double>(kr, kc) = LoG(kr, kc);
}
}
cv::filter2D(albedos_ref[i], albedos_ref_LoG[i], -1, LoG_kernel, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
cv::imwrite( (results_path / fs::path("albedo_LoG" + std::to_string(i) + ".png")).string(), (albedos_ref_LoG[i] + 0.5) * 255.0);
// store it in num_pixels-by-3 matrix
MatrixXd albedo_ref_LoG_i(num_rows*num_cols, 3);
for(int r=0, pidx=0;r<num_rows;++r) {
for(int c=0;c<num_cols;++c,++pidx) {
cv::Vec3d pix = albedos_ref_LoG[i].at<cv::Vec3d>(r, c);
albedo_ref_LoG_i(pidx, 0) = pix[0];
albedo_ref_LoG_i(pidx, 1) = pix[1];
albedo_ref_LoG_i(pidx, 2) = pix[2];
}
}
cv::filter2D(normal_maps_ref[i], normal_maps_ref_LoG[i], -1, LoG_kernel, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
cv::imwrite( (results_path / fs::path("normal_LoG" + std::to_string(i) + ".png")).string(), (normal_maps_ref_LoG[i] + 1.0) * 0.5 * 255.0);
// store it in num_pixels-by-3 matrix
MatrixXd normal_map_ref_LoG_i(num_rows*num_cols, 3);
for(int r=0, pidx=0;r<num_rows;++r) {
for(int c=0;c<num_cols;++c,++pidx) {
cv::Vec3d pix = normal_maps_ref_LoG[i].at<cv::Vec3d>(r, c);
normal_map_ref_LoG_i(pidx, 0) = pix[0];
normal_map_ref_LoG_i(pidx, 1) = pix[1];
normal_map_ref_LoG_i(pidx, 2) = pix[2];
}
}
cv::filter2D(depth_maps_ref[i], depth_maps_ref_LoG[i], -1, LoG_kernel, cv::Point(-1, -1), 0, cv::BORDER_REPLICATE);
VectorXd depth_map_ref_LoG_i(num_rows*num_cols);
for(int r=0, pidx=0;r<num_rows;++r) {
for(int c=0;c<num_cols;++c,++pidx) {
normal_map_ref_LoG_i(pidx) = depth_maps_ref_LoG[i].at<double>(r, c);
}
}
cv::Mat dzmapdx, dzmapdy;
cv::Sobel(zmaps[i], dzmapdx, -1, 1, 0);
cv::Sobel(zmaps[i], dzmapdy, -1, 0, 1);
cv::Mat dz_gradient(num_rows, num_cols, CV_32F);
for(int i=0;i<num_rows;++i) {
for(int j=0;j<num_cols;++j) {
float dzdx = dzmapdx.at<float>(i, j);
float dzdy = dzmapdy.at<float>(i, j);
dz_gradient.at<float>(i, j) = sqrt(dzdx * dzdx + dzdy * dzdy);
}
}
cv::threshold(dz_gradient, dz_gradient, 0.1, 255, cv::THRESH_BINARY);
cv::dilate(dz_gradient, dz_gradient, cv::Mat());
cv::imwrite( (results_path / fs::path("zmap_gradient" + std::to_string(i) + ".png")).string().c_str(), dz_gradient );
vector<bool> is_boundary(num_rows * num_cols, false);
cout << "Shape from shading ..." << endl;
const int max_iters = global_settings["max_iters"];
int iters = 0;
double second_order_weights = 0;
const double second_order_scale = 0.0;
// [Shape from shading] main loop
while(iters++ < max_iters){
cout << "iteration " << iters << endl;
// [Shape from shading] step 1: fix albedo and normal map, estimate lighting coefficients
{
second_order_weights = min((iters - 1) / static_cast<double>(max_iters - 1), 1.0) * second_order_scale;
// ====================================================================
// collect valid pixels
// ====================================================================
vector<glm::ivec2> pixel_indices_i;
for (int y = 0; y < normal_maps[i].rows; ++y) {
for (int x = 0; x < normal_maps[i].cols; ++x) {
float zval = zmaps[i].at<float>(y, x);
int pidx = y * num_cols + x;
bool is_good_pixel = true;
is_good_pixel &= (zval > -1e5);
is_good_pixel &= (hair_region_indices.count(face_indices_maps[i][pidx]) == 0);
is_good_pixel &= (face_boundary_indices.count(face_indices_maps[i][pidx]) == 0);
auto pix = bundle.image.pixel(x, y);
const int SATURATED_THRESHOLD = global_settings["lighting"]["saturated_pixels_threshold"];
if(qRed(pix) + qGreen(pix) + qBlue(pix) > SATURATED_THRESHOLD * 3) {
is_good_pixel = false;
}
const int DARK_PIXEL_THRESHOLD = global_settings["lighting"]["dark_pixels_threshold"];
if(qRed(pix) + qGreen(pix) + qBlue(pix) < DARK_PIXEL_THRESHOLD * 3) {
is_good_pixel = false;
}
if(is_good_pixel) pixel_indices_i.push_back(glm::ivec2(y, x));
}
}
// ====================================================================
// filter pixels
// ====================================================================
vector<double> albedo_distances_i(num_cols*num_rows);
vector<double> albedo_distances_i_vec;
for(int j = 0; j < pixel_indices_i.size(); ++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
cv::Vec3d pix_ref = albedos_ref[i].at<cv::Vec3d>(r, c);
cv::Vec3d pix = albedos[i].at<cv::Vec3d>(r, c);
cv::Vec3d pix_diff = pix_ref - pix_diff;
double d_j = pix_diff[0] * pix_diff[0] + pix_diff[1] * pix_diff[1] + pix_diff[2] * pix_diff[2];
albedo_distances_i[r*num_cols+c] = d_j;
albedo_distances_i_vec.push_back(d_j);
}
std::sort(pixel_indices_i.begin(), pixel_indices_i.end(), [&](glm::ivec2 p1, glm::ivec2 p2) {
return albedo_distances_i[p1.x*num_cols+p1.y] < albedo_distances_i[p2.x*num_cols+p2.y];
});
vector<double> albedo_distances_i_sorted = albedo_distances_i_vec;
std::sort(albedo_distances_i_sorted.begin(), albedo_distances_i_sorted.end());
const int nbins = global_settings["lighting"]["albedo_distance_bins"];
vector<int> counter(nbins, 0);
double max_albedo_distance = albedo_distances_i_sorted.back(), min_albedo_distance = albedo_distances_i_sorted.front();
double diff_albedo_distance = max(max_albedo_distance - min_albedo_distance, 1e-16);
cout << min_albedo_distance << ", " << max_albedo_distance << ", " << diff_albedo_distance << endl;
for(auto d_j : albedo_distances_i_sorted) {
int binidx = min(static_cast<int>((d_j - min_albedo_distance) / diff_albedo_distance * nbins), nbins-1);
++counter[binidx];
}
for(int j=1;j<nbins;++j) {
counter[j] += counter[j-1];
}
const double lighting_pixels_ratio_lower = global_settings["lighting"]["lighting_pixels_ratio_lower"];
const double lighting_pixels_ratio_upper = global_settings["lighting"]["lighting_pixels_ratio_upper"];
double lighting_pixels_ratio = iters / (double)max_iters * lighting_pixels_ratio_upper + (1.0 - iters / (double) max_iters) * lighting_pixels_ratio_lower;
const int cutoff_count = *std::lower_bound(counter.begin(), counter.end(), static_cast<int>(lighting_pixels_ratio*albedo_distances_i_sorted.size()));
cout << "num constraints [before]: " << pixel_indices_i.size() << endl;
pixel_indices_i.erase(pixel_indices_i.begin()+cutoff_count, pixel_indices_i.end());
cout << "num constraints [after]: " << pixel_indices_i.size() << endl;
QImage lighting_pixel_image(num_cols, num_rows, QImage::Format_ARGB32);
lighting_pixel_image.fill(0);
for(int j=0;j<pixel_indices_i.size();++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
lighting_pixel_image.setPixel(c, r, qRgb(255, 255, 255));
}
lighting_pixel_image.save( (results_path / fs::path("lighting_pixels" + std::to_string(i) + "_" + std::to_string(iters) + ".png")).string().c_str() );
// ====================================================================
// collect constraints from valid pixels
// ====================================================================
const int num_constraints = pixel_indices_i.size();
MatrixXd normals_i(num_constraints, 3);
MatrixXd albedos_i(num_constraints, 3);
MatrixXd pixels_i(num_constraints, 3);
for (int j = 0; j < num_constraints; ++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
cv::Vec3d pix = normal_maps[i].at<cv::Vec3d>(r, c);
normals_i(j, 0) = pix[0];
normals_i(j, 1) = pix[1];
normals_i(j, 2) = pix[2];
cv::Vec3d pix_albedo = albedos[i].at<cv::Vec3d>(r, c);
albedos_i(j, 0) = pix_albedo[0];
albedos_i(j, 1) = pix_albedo[1];
albedos_i(j, 2) = pix_albedo[2];
auto pix_i = bundle.image.pixel(c, r);
pixels_i(j, 0) = qRed(pix_i) / 255.0;
pixels_i(j, 1) = qGreen(pix_i) / 255.0;
pixels_i(j, 2) = qBlue(pix_i) / 255.0;
}
// ====================================================================
// assemble matrices
// ====================================================================
const int num_dof = global_settings["lighting"]["num_dof"];
MatrixXd Y(num_constraints, num_dof);
MatrixXd A;
VectorXd b;
VectorXd l_i;
bool use_Lab_color = false;
if(use_Lab_color) {
A = MatrixXd(num_constraints, num_dof);
b = VectorXd(num_constraints);
for(int j=0;j<num_constraints;++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
cv::Vec3d pix = normal_maps[i].at<cv::Vec3d>(r, c);
double nx, ny, nz;
nx = pix[0], ny = pix[1], nz = pix[2];
cv::Vec3d pix_albedo = albedos[i].at<cv::Vec3d>(r, c);
double ar = pix_albedo[0], ag = pix_albedo[1], ab = pix_albedo[2];
auto pix_i = bundle.image.pixel(c, r);
double Ir = qRed(pix_i) / 255.0;
double Ig = qGreen(pix_i) / 255.0;
double Ib = qBlue(pix_i) / 255.0;
Vector3d Lab = rgb2lab(Ir, Ig, Ib);
Vector3d a_Lab = rgb2lab(ar, ag, ab);
Y.row(j) = sphericalharmonics(nx, ny, nz).transpose();
A.row(j) = Y.row(j) * a_Lab[0]; b(j) = Lab[0];
}
// Lighting regularization
const double w_reg = 0.0001 * num_constraints;
MatrixXd Afinal(num_constraints+9, 9);
Afinal.topRows(num_constraints) = A;
Afinal.bottomRows(9) = MatrixXd::Identity(9, 9) * w_reg;
VectorXd bfinal(num_constraints+9);
bfinal.topRows(num_constraints) = b;
bfinal.bottomRows(9) = VectorXd::Zero(9);
// Apply weights to
Afinal.rightCols(5) *= second_order_weights;
// ====================================================================
// solve linear least squares
// ====================================================================
l_i = Afinal.colPivHouseholderQr().solve(bfinal);
} else {
A = MatrixXd(num_constraints * 3, num_dof);
b = VectorXd(num_constraints * 3);
#if 0
Y.col(0) = VectorXd::Ones(num_constraints);
Y.col(1) = normals_i.col(0);
Y.col(2) = normals_i.col(1);
Y.col(3) = normals_i.col(2);
Y.col(4) = normals_i.col(0).cwiseProduct(normals_i.col(1));
Y.col(5) = normals_i.col(0).cwiseProduct(normals_i.col(2));
Y.col(6) = normals_i.col(1).cwiseProduct(normals_i.col(2));
Y.col(7) = normals_i.col(0).cwiseProduct(normals_i.col(0)) - normals_i.col(1).cwiseProduct(normals_i.col(1));
Y.col(8) = 3 * normals_i.col(2).cwiseProduct(normals_i.col(2)) - VectorXd::Ones(num_constraints);
VectorXd a_vec(num_constraints * 3);
a_vec.topRows(num_constraints) = albedos_i.col(0);
a_vec.middleRows(num_constraints, num_constraints) = albedos_i.col(1);
a_vec.bottomRows(num_constraints) = albedos_i.col(2);
A.topRows(num_constraints) = Y;
A.middleRows(num_constraints, num_constraints) = Y;
A.bottomRows(num_constraints) = Y;
for (int k = 0; k < num_dof; ++k) {
A.col(k) = A.col(k).cwiseProduct(a_vec);
}
b.topRows(num_constraints) = pixels_i.col(0);
b.middleRows(num_constraints, num_constraints) = pixels_i.col(1);
b.bottomRows(num_constraints) = pixels_i.col(2);
#else
for(int j=0;j<num_constraints;++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
cv::Vec3d pix = normal_maps[i].at<cv::Vec3d>(r, c);
double nx, ny, nz;
nx = pix[0], ny = pix[1], nz = pix[2];
cv::Vec3d pix_albedo = albedos[i].at<cv::Vec3d>(r, c);
double ar = pix_albedo[0], ag = pix_albedo[1], ab = pix_albedo[2];
auto pix_i = bundle.image.pixel(c, r);
double Ir = qRed(pix_i) / 255.0;
double Ig = qGreen(pix_i) / 255.0;
double Ib = qBlue(pix_i) / 255.0;
Y.row(j) = sphericalharmonics(nx, ny, nz).transpose();
A.row(j*3) = Y.row(j) * ar; b(j*3) = Ir;
A.row(j*3+1) = Y.row(j) * ag; b(j*3+1) = Ig;
A.row(j*3+2) = Y.row(j) * ab; b(j*3+2) = Ib;
}
#endif
// Lighting regularization
const double w_reg = double(global_settings["lighting"]["w_reg"]) * num_constraints;
MatrixXd Afinal(num_constraints*3+9, 9);
Afinal.topRows(num_constraints*3) = A;
Afinal.bottomRows(9) = MatrixXd::Identity(9, 9) * w_reg;
VectorXd bfinal(num_constraints*3+9);
bfinal.topRows(num_constraints*3) = b;
bfinal.bottomRows(9) = VectorXd::Zero(9);
// Apply weights to
Afinal.rightCols(5) *= second_order_weights;
// ====================================================================
// solve linear least squares
// ====================================================================
l_i = Afinal.colPivHouseholderQr().solve(bfinal);
}
const double relax_factor = global_settings["lighting"]["relaxation"];
lighting_coeffs[i] = (1.0 - relax_factor) * lighting_coeffs[i] + relax_factor * l_i;
cout << l_i.transpose() << endl;
// ====================================================================
// [Optional] output result of estimated lighting
// ====================================================================
QImage image_with_lighting(num_cols, num_rows, QImage::Format_ARGB32);
image_with_lighting.fill(0);
for (int y = 0; y < normal_maps[i].rows; ++y) {
for (int x = 0; x < normal_maps[i].cols; ++x) {
float zval = zmaps[i].at<float>(y, x);
if (zval < -1e5) continue;
else {
cv::Vec3d pix = normal_maps[i].at<cv::Vec3d>(y, x);
double nx = pix[0], ny = pix[1], nz = pix[2];
VectorXd Y_ij = sphericalharmonics(nx, ny, nz);
double LdotY = l_i.transpose() * Y_ij;
cv::Vec3d rho(0.5, 0.5, 0.5);
rho *= 255.0 * LdotY;
image_with_lighting.setPixel(x, y, qRgb(clamp<double>(rho[0], 0, 255),
clamp<double>(rho[1], 0, 255),
clamp<double>(rho[2], 0, 255)));
}
}
}
image_with_lighting.save( (results_path / fs::path("lighting_" + std::to_string(i) + "_" + std::to_string(iters) + ".png")).string().c_str() );
QImage lighting_coeffs_image(256, 256, QImage::Format_ARGB32);
lighting_coeffs_image.fill(0);
for(int r=0;r<256;++r) {
double y = (127 - r)/127.0;
for(int c=0;c<256;++c) {
double x = (c - 127)/127.0;
if(x*x + y*y <= 1.0) {
// x = sin(theta)*sin(phi)
// y = sin(theta)*cos(phi)
// z = cos(theta)
double z = sqrt(1 - x*x - y*y);
VectorXd Y = sphericalharmonics(x, y, z);
double LdotY = l_i.transpose() * Y;
lighting_coeffs_image.setPixel(c, r, jet_color_QRgb(clamp<double>(LdotY / 1.5, 0.0, 1.0)));
}
}
}
lighting_coeffs_image.save( (results_path / fs::path("lighting_coeffs" + std::to_string(i) + "_" + std::to_string(iters) + ".png")).string().c_str() );
}
// [Shape from shading] step 2: fix depth and lighting, estimate albedo
// @NOTE Construct the problem for whole image, then solve for valid pixels only
{
const double lambda2 = double(global_settings["albedo"]["lambda"]) / pow(2, (iters - 1));
// ====================================================================
// collect valid pixels
// ====================================================================
vector<glm::ivec2> pixel_indices_i;
for (int y = 0; y < num_rows; ++y) {
for (int x = 0; x < num_cols; ++x) {
float zval = zmaps[i].at<float>(y, x);
if (zval < -1e5) continue;
else {
pixel_indices_i.push_back(glm::ivec2(y, x));
}
}
}
// ====================================================================
// collect constraints from valid pixels
// ====================================================================
const int num_constraints = pixel_indices_i.size();
cout << num_constraints << endl;
MatrixXd normals_i(num_constraints, 3);
MatrixXd pixels_i(num_constraints, 3);
QImage albedo_texture_image(num_cols, num_rows, QImage::Format_ARGB32);
QImage albedo_normal_image(num_cols, num_rows, QImage::Format_ARGB32);
for (int j = 0; j < num_constraints; ++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
cv::Vec3d pix = normal_maps[i].at<cv::Vec3d>(r, c);
normals_i(j, 0) = pix[0];
normals_i(j, 1) = pix[1];
normals_i(j, 2) = pix[2];
auto pix_i = bundle.image.pixel(c, r);
pixels_i(j, 0) = qRed(pix_i) / 255.0;
pixels_i(j, 1) = qGreen(pix_i) / 255.0;
pixels_i(j, 2) = qBlue(pix_i) / 255.0;
albedo_normal_image.setPixel(c, r, qRgb((pix[0]+1.0)*0.5*255,
(pix[1]+1.0)*0.5*255,
(pix[2]+1.0)*0.5*255));
albedo_texture_image.setPixel(c, r, pix_i);
}
albedo_normal_image.save("albedo_normal_image.png");
albedo_texture_image.save("albedo_texture_image.png");
// ====================================================================
// assemble matrices
// ====================================================================
const int num_dof = 9; // use first order approximation
MatrixXd Y(num_constraints, num_dof);
#if 0
Y.col(0) = VectorXd::Ones(num_constraints);
Y.col(1) = normals_i.col(0);
Y.col(2) = normals_i.col(1);
Y.col(3) = normals_i.col(2);
Y.col(4) = normals_i.col(0).cwiseProduct(normals_i.col(1));
Y.col(5) = normals_i.col(0).cwiseProduct(normals_i.col(2));
Y.col(6) = normals_i.col(1).cwiseProduct(normals_i.col(2));
Y.col(7) = normals_i.col(0).cwiseProduct(normals_i.col(0)) - normals_i.col(1).cwiseProduct(normals_i.col(1));
Y.col(8) = 3 * normals_i.col(2).cwiseProduct(normals_i.col(2)) - VectorXd::Ones(num_constraints);
#else
for(int j=0;j<num_constraints;++j) {
int r = pixel_indices_i[j].x, c = pixel_indices_i[j].y;
cv::Vec3d pix = normal_maps[i].at<cv::Vec3d>(r, c);
double nx, ny, nz;
nx = pix[0], ny = pix[1], nz = pix[2];
Y.row(j) = sphericalharmonics(nx, ny, nz).transpose();
}
#endif