-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGenerateSyntheticData.cpp
More file actions
executable file
·4529 lines (3598 loc) · 145 KB
/
Copy pathGenerateSyntheticData.cpp
File metadata and controls
executable file
·4529 lines (3598 loc) · 145 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
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Plugins *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#define SOFA_RGBDTRACKING_GENERATESYNTHETICDATA_CPP
#include <sofa/core/ObjectFactory.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/core/behavior/ForceField.inl>
#include <sofa/core/objectmodel/BaseContext.h>
#include <sofa/core/Mapping.inl>
#include <sofa/simulation/common/Simulation.h>
#include <sofa/core/topology/BaseMeshTopology.h>
#include <sofa/gui/BaseGUI.h>
#include <sofa/gui/BaseViewer.h>
#include <sofa/gui/GUIManager.h>
#include <iostream>
#include <map>
#ifdef USING_OMP_PRAGMAS
#include <omp.h>
#endif
#include <sofa/component/loader/MeshObjLoader.h>
#include <sofa/component/engine/NormalsFromPoints.h>
#include <limits>
#include <set>
#include <iterator>
#include <sofa/helper/gl/Color.h>
#include <sofa/core/ObjectFactory.h>
#include <sofa/component/visualmodel/InteractiveCamera.h>
#ifdef Success
#undef Success
#endif
#include <pcl-1.7/pcl/common/common_headers.h>
#include <pcl-1.7/pcl/point_cloud.h>
#include <pcl-1.7/pcl/filters/extract_indices.h>
#include <pcl-1.7/pcl/point_types.h>
#include <pcl-1.7/pcl/impl/point_types.hpp>
#include <pcl-1.7/pcl/features/normal_3d.h>
#include <pcl-1.7/pcl/PointIndices.h>
#include <pcl-1.7/pcl/PolygonMesh.h>
#include <pcl-1.7/pcl/visualization/common/actor_map.h>
#include <pcl-1.7/pcl/visualization/common/common.h>
#include <pcl-1.7/pcl/visualization/point_cloud_geometry_handlers.h>
#include <pcl-1.7/pcl/visualization/point_cloud_color_handlers.h>
#include <pcl-1.7/pcl/visualization/point_picking_event.h>
#include <pcl-1.7/pcl/visualization/area_picking_event.h>
#include <pcl-1.7/pcl/visualization/interactor_style.h>
#include <pcl-1.7/pcl/visualization/pcl_visualizer.h>
#include <pcl-1.7/pcl/visualization/keyboard_event.h>
#include <pcl-1.7/pcl/correspondence.h>
#include <pcl-1.7/pcl/features/normal_3d_omp.h>
#include <pcl-1.7/pcl/features/shot_omp.h>
#include <pcl-1.7/pcl/features/board.h>
#include <pcl-1.7/pcl/console/parse.h>
#include <pcl-1.7/pcl/common/projection_matrix.h>
#include <pcl-1.7/pcl/common/pca.h>
#include <pcl-1.7/pcl/surface/reconstruction.h>
#include <pcl-1.7/pcl/io/pcd_io.h>
#include <pcl-1.7/pcl/common/io.h>
#include <pcl-1.7/pcl/registration/transforms.h>
#include <pcl-1.7/pcl/keypoints/sift_keypoint.h>
#include <pcl-1.7/pcl/keypoints/harris_3d.h>
#include <pcl-1.7/pcl/ModelCoefficients.h>
#include <pcl-1.7/pcl/sample_consensus/method_types.h>
#include <pcl-1.7/pcl/sample_consensus/model_types.h>
#include <pcl-1.7/pcl/segmentation/sac_segmentation.h>
#include <pcl-1.7/pcl/search/kdtree.h>
#include <pcl-1.7/pcl/segmentation/extract_clusters.h>
#include <pcl-1.7/pcl/features/fpfh_omp.h>
#include <pcl-1.7/pcl/features/feature.h>
#include <pcl-1.7/pcl/features/pfh.h>
#include <pcl-1.7/pcl/features/pfhrgb.h>
#include <pcl-1.7/pcl/features/3dsc.h>
#include <pcl-1.7/pcl/features/shot_omp.h>
#include <pcl-1.7/pcl/filters/filter.h>
#include <pcl-1.7/pcl/registration/transformation_estimation_svd.h>
#include <pcl-1.7/pcl/registration/icp.h>
#include <pcl-1.7/pcl/registration/correspondence_rejection_sample_consensus.h>
#include <pcl-1.7/pcl/search/kdtree.h>
#include <pcl-1.7/pcl/common/transforms.h>
#include <pcl-1.7/pcl/range_image/range_image.h>
#include "GenerateSyntheticData.h"
using std::cerr;
using std::endl;
namespace sofa
{
namespace component
{
namespace forcefield
{
using namespace sofa::defaulttype;
SOFA_DECL_CLASS(GenerateSyntheticData)
// Register in the Factory
int GenerateSyntheticDataClass = core::RegisterObject("Compute forces based on closest points from/to a target surface/point set")
#ifndef SOFA_FLOAT
.add< GenerateSyntheticData<Vec3dTypes,ImageUC> >()
.add< GenerateSyntheticData<Vec3dTypes,ImageUS> >()
.add< GenerateSyntheticData<Vec3dTypes,ImageF> >()
#endif
#ifndef SOFA_DOUBLE
.add< GenerateSyntheticData<Vec3fTypes,ImageUC> >()
.add< GenerateSyntheticData<Vec3fTypes,ImageUS> >()
.add< GenerateSyntheticData<Vec3fTypes,ImageF> >()
#endif
;
#ifndef SOFA_FLOAT
template class SOFA_RGBDTRACKING_API GenerateSyntheticData<Vec3dTypes,ImageUC>;
template class SOFA_RGBDTRACKING_API GenerateSyntheticData<Vec3dTypes,ImageUS>;
template class SOFA_RGBDTRACKING_API GenerateSyntheticData<Vec3dTypes,ImageF>;
#endif
#ifndef SOFA_DOUBLE
template class SOFA_RGBDTRACKING_API GenerateSyntheticData<Vec3fTypes,ImageUC>;
template class SOFA_RGBDTRACKING_API GenerateSyntheticData<Vec3fTypes,ImageUS>;
template class SOFA_RGBDTRACKING_API GenerateSyntheticData<Vec3fTypes,ImageF>;
#endif
using namespace helper;
template <class DataTypes, class DepthTypes>
GenerateSyntheticData<DataTypes, DepthTypes>::GenerateSyntheticData(core::behavior::MechanicalState<DataTypes> *mm )
: Inherit(mm)
, depthImage(initData(&depthImage,DepthTypes(),"depthImage","depth map"))
//, depthTransform(initData(&depthTransform, TransformType(), "depthTransform" , ""))
, image(initData(&image,ImageTypes(),"image","image"))
//, transform(initData(&transform, TransformType(), "transform" , ""))
, ks(initData(&ks,(Real)0.0,"stiffness","uniform stiffness for the all springs."))
, kd(initData(&kd,(Real)0.0,"damping","uniform damping for the all springs."))
, cacheSize(initData(&cacheSize,(unsigned int)10,"cacheSize","number of closest points used in the cache to speed up closest point computation."))
, blendingFactor(initData(&blendingFactor,(Real)1,"blendingFactor","blending between projection (=0) and attraction (=1) forces."))
, outlierThreshold(initData(&outlierThreshold,(Real)7,"outlierThreshold","suppress outliers when distance > (meandistance + threshold*stddev)."))
, normalThreshold(initData(&normalThreshold,(Real)0,"normalThreshold","suppress outliers when normal.closestPointNormal < threshold."))
, projectToPlane(initData(&projectToPlane,false,"projectToPlane","project closest points in the plane defined by the normal."))
, rejectBorders(initData(&rejectBorders,false,"rejectBorders","ignore border vertices."))
, rejectOutsideBbox(initData(&rejectOutsideBbox,false,"rejectOutsideBbox","ignore source points outside bounding box of target points."))
, springs(initData(&springs,"spring","index, stiffness, damping"))
, sourceSurfacePositions(initData(&sourceSurfacePositions,"sourceSurface","Points of the surface of the source mesh."))
, sourceTriangles(initData(&sourceTriangles,"sourceTriangles","Triangles of the source mesh."))
, sourceNormals(initData(&sourceNormals,"sourceNormals","Normals of the source mesh."))
, sourceSurfaceNormals(initData(&sourceSurfaceNormals,"sourceSurfaceNormals","Normals of the surface of the source mesh."))
, showArrowSize(initData(&showArrowSize,0.01f,"showArrowSize","size of the axis."))
, drawMode(initData(&drawMode,0,"drawMode","The way springs will be drawn:\n- 0: Line\n- 1:Cylinder\n- 2: Arrow."))
, drawColorMap(initData(&drawColorMap,true,"drawColorMap","Hue mapping of distances to closest point"))
, useVisible(initData(&useVisible,true,"useVisible","Use the vertices of the visible surface of the source mesh"))
, useGroundTruth(initData(&useGroundTruth,true,"useGroundTruth","Use the vertices of the visible surface of the source mesh")) , generateSynthData(initData(generateSynthData&, false,"generateSynthData","Generate synthetic data"))
, niterations(initData(niterations&,3,"nIterations","Number of iterations in the tracking process"))
, nimages(initData(nimages&,400,"nImages","Number of images to read"))
{
this->addAlias(&depthImage, "depthImage");
depthImage.setGroup("depthImage");
depthImage.setReadOnly(true);
this->addAlias(&image, "image");
image.setGroup("image");
image.setReadOnly(true);
pcl = false;
disp = false;
iter_im = 0;
timeTotal = 0;
color = cv::Mat::zeros(240,320, CV_8UC3);
listimg.resize(0);
listimgseg.resize(0);
listdepth.resize(0);
listrtt.resize(0);
listpcd.resize(0);
listvisible.resize(0);
paramSoft.sigma_p2 = 0.005f; // default parameters
paramSoft.sigma_inf = 0.00001f;
paramSoft.sigma_factor = 0.9f;
paramSoft.d_02 = 0.01f;
//
// initialize paramters
//
sigma_p2 = paramSoft.sigma_p2;
sigma_inf = paramSoft.sigma_inf;
sigma_factor = paramSoft.sigma_factor;
d_02 = paramSoft.d_02;
}
template <class DataTypes, class DepthTypes>
GenerateSyntheticData<DataTypes, DepthTypes>::~GenerateSyntheticData()
{
}
template <class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::initCamera()
{
//softk.init();
}
template <class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::reinit()
{
for (unsigned int i=0;i<springs.getValue().size();++i)
{
(*springs.beginEdit())[i].ks = (Real) ks.getValue();
(*springs.beginEdit())[i].kd = (Real) kd.getValue();
}
}
template <class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::init()
{
this->Inherit::init();
core::objectmodel::BaseContext* context = this->getContext();
if(!(this->mstate)) this->mstate = dynamic_cast<sofa::core::behavior::MechanicalState<DataTypes> *>(context->getMechanicalState());
// Get source triangles
if(!sourceTriangles.getValue().size()) {
sofa::component::loader::MeshObjLoader *meshobjLoader;
this->getContext()->get( meshobjLoader, core::objectmodel::BaseContext::Local);
if (meshobjLoader) {sourceTriangles.virtualSetLink(meshobjLoader->triangles); sout<<"imported triangles from "<<meshobjLoader->getName()<<sendl;
}
}
// Get source normals
if(!sourceNormals.getValue().size()) serr<<"normals of the source model not found"<<sendl;
// add a spring for every input point
const VecCoord& x = *this->mstate->getX(); //RDataRefVecCoord x(*this->getMState()->read(core::ConstVecCoordId::position()));
this->clearSprings(x.size());
for(unsigned int i=0;i<x.size();i++) this->addSpring(i, (Real) ks.getValue(),(Real) kd.getValue());
//initCamera();
std::string configFile;
bool opt_device = false;
bool opt_display = true;
bool use_cuda = true;
bool opt_click_allowed = true;
int start_image = 0;
if (!useRealData.getValue()) useGroundTruth.setValue(true);
if (configFile.empty())
configFile = vpIoTools::path("param/pizza.lua");
/*listimg.resize(0);
listimgseg.resize(0);
listdepth.resize(0);*/
}
template <class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::resetSprings()
{
this->clearSprings(sourceVisiblePositions.getValue().size());
for(unsigned int i=0;i<sourceVisiblePositions.getValue().size();i++) this->addSpring(i, (Real) ks.getValue(),(Real) kd.getValue());
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::detectBorder(vector<bool> &border,const helper::vector< tri > &triangles)
{
unsigned int nbp=border.size();
unsigned int nbt=triangles.size();
for(unsigned int i=0;i<nbp;i++) border[i]=false;
if(!nbt) return;
vector<vector< unsigned int> > ngbTriangles((int)nbp);
for(unsigned int i=0;i<nbt;i++) for(unsigned int j=0;j<3;j++) ngbTriangles[triangles[i][j]].push_back(i);
for(unsigned int i=0;i<nbp;i++) if(ngbTriangles[i].size()==0) border[i]=true;
for(unsigned int i=0;i<nbt;i++)
for(unsigned int j=0;j<3;j++)
{
unsigned int id1=triangles[i][j],id2=triangles[i][(j==2)?0:j+1];
if(!border[id1] || !border[id2]) {
bool bd=true;
for(unsigned int i1=0;i1<ngbTriangles[id1].size() && bd;i1++)
for(unsigned int i2=0;i2<ngbTriangles[id2].size() && bd;i2++)
if(ngbTriangles[id1][i1]!=i)
if(ngbTriangles[id1][i1]==ngbTriangles[id2][i2])
bd=false;
if(bd) border[id1]=border[id2]=true;
}
}
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::initSourceSurface()
{
// build k-d tree
const VecCoord& p = *this->mstate->getX();
ReadAccessor< Data< VecCoord > > pSurface(sourceSurfacePositions);
ReadAccessor< Data< VecCoord > > nSurface(sourceSurfaceNormals);
//const VecCoord& pSurface = sourceSurfacePositions.getValue();
//for (unsigned int i=0; i < sourceNormals.getValue().size(); i++)
//std::cout << " source surface position " << sourceSurfaceNormals.getValue()[1][0] << std::endl;
//std::cout << " source normals " << sourceT.getValue()[1][0] << std::endl;
VecCoord nSurfaceM;
sourceSurface.resize(p.size());
Vector3 pos;
Vector3 col;
//sourceSurfaceMapping.resize(pSurface.size());
nSurfaceM.resize(p.size());
for (unsigned int i=0; i<p.size(); i++)
{
sourceSurface[i] = false;
for (unsigned int j=0; j<pSurface.size(); j++)
{
Real dist=(p[i]-pSurface[j]).norm();
if ((float)dist < 0.001)
{
//std::cout << " i " << i << " j " << j << "dist " << dist << std::endl;
sourceSurface[i] = true;
nSurfaceM[i] = nSurface[j];
}
}
//std::cout << " i " << (int)sourceSurface[i] << std::endl;
}
sourceSurfaceNormalsM.setValue(nSurfaceM);
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::updateSourceSurface()
{
// build k-d tree
const VecCoord& p = *this->mstate->getX();
const VecCoord& pSurface = sourceSurfacePositions.getValue();
sourceSurface.resize(p.size());
Vector3 pos;
Vector3 col;
for (unsigned int i=0; i<p.size(); i++)
{
sourceSurface[i] = false;
for (unsigned int j=0; j<pSurface.size(); j++)
{
Real dist=(p[i]-pSurface[j]).norm();
if (dist < 10e-3f)
{
sourceSurface[i] = true;
}
}
}
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::initSourceVisible()
{
// build k-d tree
//const VecCoord& p = *this->mstate->getX();
const VecCoord& p = sourceVisiblePositions.getValue();
sourceKdTree.build(p);
// detect border
if(sourceBorder.size()!=p.size())
{ sourceBorder.resize(p.size());
//detectBorder(sourceBorder,sourceTriangles.getValue());
}
}
void writePCDToFile(string path, std::vector<Vec3d>& pcd, std::vector<bool>& visible)
{
//create the file stream
ofstream file(path.c_str(), ios::out | ios::binary );
double dvalue0,dvalue1,dvalue2;
for (int k = 0; k < pcd.size(); k++)
{
dvalue0 = pcd[k][0];
dvalue1 = pcd[k][1];
dvalue2 = pcd[k][2];
file << dvalue0;
file << "\t";
file << dvalue1;
file << "\t";
file << dvalue2;
file << "\t";
if (visible[k])
file << 1;
else file << 0;
file << "\n";
}
file.close();
}
int writeMatToFile(const cv::Mat &I, string path) {
//load the matrix size
int matWidth = I.size().width, matHeight = I.size().height;
//read type from Mat
int type = I.type();
//declare values to be written
float fvalue;
double dvalue;
Vec3f vfvalue;
Vec3d vdvalue;
//create the file stream
ofstream file(path.c_str(), ios::out | ios::binary );
if (!file)
return -1;
//write type and size of the matrix first
file.write((const char*) &type, sizeof(type));
file.write((const char*) &matWidth, sizeof(matWidth));
file.write((const char*) &matHeight, sizeof(matHeight));
//write data depending on the image's type
switch (type)
{
default:
cout << "Error: wrong Mat type: must be CV_32F, CV_64F, CV_32FC3 or CV_64FC3" << endl;
break;
// FLOAT ONE CHANNEL
case CV_32F:
//cout << "Writing CV_32F image" << endl;
for (int i=0; i < matWidth*matHeight; ++i) {
fvalue = I.at<float>(i);
file.write((const char*) &fvalue, sizeof(fvalue));
}
break;
// DOUBLE ONE CHANNEL
case CV_64F:
cout << "Writing CV_64F image" << endl;
for (int i=0; i < matWidth*matHeight; ++i) {
dvalue = I.at<double>(i);
file.write((const char*) &dvalue, sizeof(dvalue));
}
break;
// FLOAT THREE CHANNELS
case CV_32FC3:
cout << "Writing CV_32FC3 image" << endl;
for (int i=0; i < matWidth*matHeight; ++i) {
vfvalue = I.at<Vec3f>(i);
file.write((const char*) &vfvalue, sizeof(vfvalue));
}
break;
// DOUBLE THREE CHANNELS
case CV_64FC3:
cout << "Writing CV_64FC3 image" << endl;
for (int i=0; i < matWidth*matHeight; ++i) {
vdvalue = I.at<Vec3d>(i);
file.write((const char*) &vdvalue, sizeof(vdvalue));
}
break;
}
//close file
file.close();
return 0;
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::writeImagesSynth()
{
std::string opath3 = "out/imagesSynth30_S3_CoRot/rtt%06d.png";
cv::Mat rtt,rtt1;
//for (int frame_count = 1 ;frame_count < nimages*niterations; frame_count++)
for (int frame_count = 1 ;frame_count < nimages-4; frame_count++)
{
std::cout << " ok write rtt " << frame_count << std::endl;
rtt = *listrtt[frame_count];
cvtColor(rtt,rtt1 ,CV_RGB2BGR);
char buf4[FILENAME_MAX];
sprintf(buf4, opath3.c_str(), frame_count-1);
std::string filename4(buf4);
cv::imwrite(filename4,rtt1);
//delete listrtt[frame_count];
}
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::writeData()
{
std::string opath = "in/images4/img1%06d.png";
std::string opath1 = "in/images4/depthfile%06d.txt";
std::string extensionfile = "in/images4/extension.txt";
std::vector<Vec3d> pcd1;
std::vector<bool> visible1;
ofstream extfile(extensionfile.c_str(), ios::out | ios::binary );
double extension;
double pos = 0;
double pos0;
cv::Mat rtt,rtt1,rtt2;
for (int frame_count = 0 ;frame_count < listpcd.size(); frame_count++)
{
std::cout << " ok write " << frame_count << std::endl;
pcd1 = *listpcd[frame_count];
pos = pcd1[132][1];
if (frame_count == 0) pos0 = pos;
extension = pos - pos0;
extfile << pos;
extfile << "\t";
extfile << extension;
extfile << "\n";
visible1 = *listvisible[frame_count];
char buf1[FILENAME_MAX];
sprintf(buf1, opath1.c_str(), frame_count);
std::string filename1(buf1);
writePCDToFile(filename1,pcd1,visible1);
/*delete listimg[frame_count];
delete listimgseg[frame_count];
delete listdepth[frame_count];*/
}
extfile.close();
//for (int frame_count = 1 ;frame_count < nimages*niterations; frame_count++)
for (int frame_count = 1 ;frame_count < listrtt.size(); frame_count++)
{
std::cout << " ok write rtt " << frame_count << std::endl;
rtt = *listrtt[frame_count];
cvtColor(rtt,rtt1 ,CV_RGB2BGR);
cv::flip(rtt1,rtt2,0);
char buf4[FILENAME_MAX];
sprintf(buf4, opath.c_str(), frame_count-1);
std::string filename4(buf4);
cv::imwrite(filename4,rtt2);
//delete listrtt[frame_count];
}
}
void renderToTexture(cv::Mat &_rtt)
{
_rtt.create(480,640, CV_8UC3);
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
//img.init(viewport[2], viewport[3], 1, 1, io::Image::UNORM8, io::Image::RGB);
glReadBuffer(GL_FRONT);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(viewport[0], viewport[1], viewport[2], viewport[3], GL_RGB, GL_UNSIGNED_BYTE, _rtt.data);
glReadBuffer(GL_BACK);
//cv::imwrite("rtt.png",_rtt);
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::renderToTextureD(cv::Mat &_rtt)
{
_rtt.create(480,640, CV_8UC3);
cv::Mat _rttd,_dd,_rttd_;
_rttd.create(240,320, CV_8UC3);
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT,viewport);
//img.init(viewport[2], viewport[3], 1, 1, io::Image::UNORM8, io::Image::RGB);
glReadBuffer(GL_FRONT);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(viewport[0], viewport[1], viewport[2], viewport[3], GL_RGB, GL_UNSIGNED_BYTE, _rtt.data);
glReadBuffer(GL_BACK);
//cv::imwrite("rtt.png",_rtt);
int hght = 480;
int wdth = 640;
//_rttd = _rtt;
cv::resize(_rtt, _rttd_,_rttd.size());
cv::flip( _rttd_,_rttd,0);
//cv::namedWindow("rttd");
//cv::imshow("rttd",_rtt);
cv::Mat _rtd,_rtd0;
_rtd.create(hght, wdth, CV_32F);
_rtd0.create(hght,wdth, CV_8UC1);
_dd.create(240,320, CV_8UC1);
GLfloat depths[hght * wdth ];
//depths = new GLfloat[240 * 320 ];
glReadBuffer(GL_FRONT);
glEnable(GL_DEPTH_TEST);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
std::cout << " no viewer 1" << std::endl;
glReadPixels(viewport[0], viewport[1], viewport[2], viewport[3], GL_DEPTH_COMPONENT, GL_FLOAT, &depths);
glReadBuffer(GL_BACK);
int offset = 5;
std::cout << " ok read " << std::endl;
for (int j = 0; j < wdth; j++)
for (int i = 0; i< hght; i++)
{
if ((double)(float)depths[j+i*wdth] < 1)
{
_rtd0.at<uchar>(hght-i-1,j) = 255;
}
else _rtd0.at<uchar>(hght-i-1,j) = 0;
}
cv::resize(_rtd0, _dd, Size(320, 240));
std::cout << " ok read 1 " << std::endl;
for (int j = 0; j < 320; j++)
for (int i = 0; i< 240; i++)
{
if (_dd.at<uchar>(i,j) == 0)
{
_rttd.at<Vec3b>(i,j)[0] = color_1.at<Vec3b>(i,j)[2];
_rttd.at<Vec3b>(i,j)[2] = color_1.at<Vec3b>(i,j)[0];
_rttd.at<Vec3b>(i,j)[1] = color_1.at<Vec3b>(i,j)[1];
}
}
cv::namedWindow("dd");
cv::imshow("dd",_rttd);
_rtt = _rttd;
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::initSegmentation()
{
cv::Mat mask,maskimg,mask0,roimask,mask1; // segmentation result (4 possible values)
cv::Mat bgModel,fgModel; // the models (internally used)
//cv::imwrite("color.png",color);
cv::Mat downsampledbox,downsampled;
//cv::pyrDown(color, downsampledbox, cv::Size(color.cols/2, color.rows/2));
downsampledbox = color;
IplImage temp;
IplImage tempgs;
cv::Mat imgs,imgklt;
temp = downsampledbox;
IplImage* temp1 = cvCloneImage(&temp);
cout << "init seg" << endl;
const char* name = "image";
cv::namedWindow(name);
box = cvRect(0,0,1,1);
//cv::imshow("image", color);
//tempm.resize(image.step1());
// Set up the callback
cv::setMouseCallback(name, my_mouse_callback, (void*) &temp);
/*for (int i = 0; i<color.rows; i++)
for (int j = 0; j<color.cols; j++)
std::cout << (int)color.at<Vec3b>(i,j)[0] << std::endl;*/
std::cout << " Time " << (int)this->getContext()->getTime() << std::endl;
// Main loop
while(1)
{
if (destroy)
{
cvDestroyWindow(name); break;
}
cvCopyImage(&temp, temp1);
if (drawing_box)
draw_box(temp1, box);
cv::moveWindow(name, 200, 100);
cvShowImage(name, temp1);
//tempm.resize(image.step1());
int key=cvWaitKey(10);
if ((char)key == 27) break;
}
cvReleaseImage(&temp1);
cv::setMouseCallback(name, NULL, NULL);
//cvDestroyWindow(name);
cv::Rect rectangle(69,47,198,171);
cv::Rect recttemp = rectangle;
rectangle = box;
seg.setRectangle(rectangle);
int width = downsampled.cols;
int height = downsampled.rows;
foreground = cv::Mat(downsampled.size(),CV_8UC3,cv::Scalar(255,255,255));
// GrabCut segmentation
if (useSensor.getValue())
getImages();
else readImages();
//cv::pyrDown(color, downsampled, cv::Size(color.cols/2, color.rows/2));
downsampled = color;
seg.segmentationFromRect(downsampled,foreground);
// draw rectangle on original image
//cv::rectangle(image, rectangle, cv::Scalar(255,255,255),1);
//cv::namedWindow("Image");
//cv::imshow("Image",downsampled);
// display result
cv::namedWindow("Segmented Image");
cv::imshow("Segmented Image",foreground);
if (waitKey(20) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
}
/*imglsg = new cv::Mat;
*imglsg = foreground;
listimgseg.push_back(imglsg);
delete imglsg;*/
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::segment()
{
cv::Mat downsampled;
//cv::pyrDown(color, downsampled, cv::Size(color.cols/2, color.rows/2));
downsampled = color;
//cv::imwrite("downsampled.png",downsampled);
int width = downsampled.cols;
int height = downsampled.rows;
//cv::imwrite("foreground0.png",foreground);
seg.updateMask(foreground);
seg.updateSegmentation(downsampled,foreground);
//seg.updateSegmentationCrop(downsampled,foreground);
//cv::imwrite("foreground1.png",foreground);
/*cv::namedWindow("Image");
cv::imshow("Image",downsampled);*/
// display result
cv::namedWindow("Segmented Image");
cv::imshow("Segmented Image",foreground);
//cv::imwrite("color.png",color);
imglsg = new cv::Mat;
*imglsg = foreground;
listimgseg.push_back(imglsg);
//delete imglsg;
imgl = new cv::Mat;
//*imgl = color;
*imgl = downsampled;
depthl = new cv::Mat;
*depthl = depth;
listimg.push_back(imgl);
listdepth.push_back(depthl);
//delete depthl;
//delete imgl;
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::segmentSynth()
{
cv::Mat downsampled;
//cv::pyrDown(color, downsampled, cv::Size(color.cols/2, color.rows/2));
downsampled = color;
foreground = cv::Mat(downsampled.size(),CV_8UC4,cv::Scalar(255,255,255,0));
cv::imwrite("downsampled0.png",downsampled);
int width = downsampled.cols;
int height = downsampled.rows;
//cv::imwrite("foreground0.png",foreground);
std::cout << " ok seg synth " << std::endl;
for (int j = 0; j < width; j++)
for (int i = 0; i < height; i++)
{
foreground.at<cv::Vec4b>(i,j)[0] = color.at<cv::Vec3b>(i,j)[0];
foreground.at<cv::Vec4b>(i,j)[1] = color.at<cv::Vec3b>(i,j)[1];
foreground.at<cv::Vec4b>(i,j)[2] = color.at<cv::Vec3b>(i,j)[2];
if (color.at<cv::Vec3b>(i,j)[0] == 0 && color.at<cv::Vec3b>(i,j)[1] == 1 && color.at<cv::Vec3b>(i,j)[2] == 2)
{
foreground.at<cv::Vec4b>(i,j)[3] = 0;
}
else foreground.at<cv::Vec4b>(i,j)[3] = 255;
}
cv::Mat distanceMap(foreground.size(),CV_8U,cv::Scalar(255));
cv::Mat dot(foreground.size(),CV_8U,cv::Scalar(0));
//std::cout << " ok seg synth 1 " << std::endl;
seg.filter(foreground,distanceMap,dot);
//cv::imwrite("downsampled1.png",distanceMap);
//distImage = distanceMap;
//dotImage = dot;
/*cv::namedWindow("Image");
cv::imshow("Image",downsampled);*/
// display result
cv::namedWindow("Segmented Image");
cv::imshow("Segmented Image",foreground);
cv::imwrite("color.png",color);
imglsg = new cv::Mat;
*imglsg = foreground;
listimgseg.push_back(imglsg);
//delete imglsg;
imgl = new cv::Mat;
//*imgl = color;
*imgl = downsampled;
listimg.push_back(imgl);
//delete depthl;
//delete imgl;
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::extractTargetContour()
{
cv::Mat distImage, contourImage;
targetContour.reset(new pcl::PointCloud<pcl::PointXYZRGB>);
//pcl::PointCloud<pcl::PointXYZRGB> target;
//cv::imwrite("dist_image.png",seg.distImage);
//cv::imwrite("dot_image.png",seg.dotImage);
targetContour = PCDContour(depth,seg.distImage,seg.dotImage);
/*cv::namedWindow("dist_image");
cv::imshow("dist_image",seg.distImage);
cv::namedWindow("dot_image");
cv::imshow("dot_image",seg.dotImage);*/
VecCoord targetpos;
targetpos.resize(targetContour->size());
std::cout << " target contour size " << targetContour->size() << std::endl;
Vector3 pos;
Vector3 col;
for (unsigned int i=0; i<targetContour->size(); i++)
{
pos[0] = (double)targetContour->points[i].x;
pos[1] = (double)targetContour->points[i].y;
pos[2] = (double)targetContour->points[i].z;
targetpos[i]=pos;
//std::cout << " x " << pos[0] << " y " << pos[1] << " z " << pos[2] << std::endl;
}
const VecCoord& p = targetpos;
targetContourPositions.setValue(p);
}
template<class DataTypes, class DepthTypes>
void GenerateSyntheticData<DataTypes, DepthTypes>::setViewPoint()
{
Eigen::Affine3f scene_sensor_pose (Eigen::Affine3f::Identity ());
pcl::PointCloud<pcl::PointXYZRGB>& point_cloud = *target;
scene_sensor_pose = Eigen::Affine3f (Eigen::Translation3f (point_cloud.sensor_origin_[0],
point_cloud.sensor_origin_[1],
point_cloud.sensor_origin_[2])) *
Eigen::Affine3f (point_cloud.sensor_orientation_);
Eigen::Affine3f viewer_pose = scene_sensor_pose;
Eigen::Vector3f pos_vector = viewer_pose * Eigen::Vector3f(0, 0, 0);
Eigen::Vector3f look_at_vector = viewer_pose.rotation () * Eigen::Vector3f(0, 0, 1) + pos_vector;
Eigen::Vector3f up_vector = viewer_pose.rotation () * Eigen::Vector3f(0, -1, 0);
/*viewer.setCameraPosition (pos_vector[0], pos_vector[1], pos_vector[2],
look_at_vector[0], look_at_vector[1], look_at_vector[2],
up_vector[0], up_vector[1], up_vector[2]);*/
int hght = 480;
int wdth = 640;
sofa::gui::GUIManager::SetDimension(wdth,hght);
sofa::gui::BaseGUI *gui = sofa::gui::GUIManager::getGUI();
if (!gui)
{
std::cout << " no gui " << std::endl;
}
sofa::gui::BaseViewer * viewer = gui->getViewer();
if (!viewer)
{
std::cout << " no viewer " << std::endl;
}
//viewer->getView(pos,orient);
{
Vec3d position;
Quat orientation;
orientation[0] = point_cloud.sensor_orientation_.w ();
orientation[1] = point_cloud.sensor_orientation_.x ();