-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathReconstruction.cpp
1533 lines (1340 loc) · 65.2 KB
/
Reconstruction.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
#include <cstdlib>
#include <vtkKdTreePointLocator.h>
#include <vtkProbeFilter.h>
#include <vtkFloatArray.h>
#include <vtkDoubleArray.h>
#include <vtkPointData.h>
#include <vtkContourFilter.h>
#include <vtkSmoothPolyDataFilter.h>
#include <vtkPolyDataConnectivityFilter.h>
#include <vtkDecimatePro.h>
#include <FEVTKImport.h>
#include <FEVTKExport.h>
#include <FEFixMesh.h>
#include <FEMeshSmoothingModifier.h>
#include <FECVDDecimationModifier.h>
#include <vtkPolyDataReader.h>
#include <vtkPLYWriter.h>
#include <vtkPolyDataWriter.h>
#include <array>
#include <itkImageFileReader.h>
#include "itkNrrdImageIOFactory.h"
#include "itkMetaImageIOFactory.h"
#include "Reconstruction.h"
#include <vtkLoopSubdivisionFilter.h>
#include <vtkButterflySubdivisionFilter.h>
#include <itkImageFileWriter.h>
#include <Utils.h>
#include <math.h>
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
Reconstruction<TTransformType, TInterpolatorType, TCoordRep, PixelType, ImageType>::Reconstruction(std::string out_prefix,
float decimationPercent, double maxAngleDegrees,
size_t numClusters,
bool fixWinding,
bool doLaplacianSmoothingBeforeDecimation,
bool doLaplacianSmoothingAfterDecimation,
float smoothingLambda,
int smoothingIterations,
bool usePairwiseNormalsDifferencesForGoodBad):
sparseDone_(false), denseDone_(false),
decimationPercent_(decimationPercent),
maxAngleDegrees_(maxAngleDegrees),
numClusters_(numClusters),
fixWinding_(fixWinding),
doLaplacianSmoothingBeforeDecimation_(doLaplacianSmoothingBeforeDecimation),
smoothingLambda_(smoothingLambda),
smoothingIterations_(smoothingIterations),
out_prefix_(out_prefix), use_origin(false), usePairwiseNormalsDifferencesForGoodBad_(usePairwiseNormalsDifferencesForGoodBad)
{}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::~Reconstruction() {
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
vtkSmartPointer<vtkPolyData> Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::getDenseMean(
std::vector< PointArrayType > local_pts,
std::vector< PointArrayType > global_pts,
std::vector<std::string> distance_transform) {
if (!this->denseDone_ || !local_pts.empty() ||
!distance_transform.empty() || !global_pts.empty()) {
this->denseDone_ = false;
if (local_pts.empty() || distance_transform.empty() ||
global_pts.empty() || local_pts.size() != distance_transform.size()) {
throw std::runtime_error("Invalid input for reconstruction!");
}
this->computeDenseMean(local_pts, global_pts, distance_transform);
}
return this->denseMean_;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::reset() {
this->sparseDone_ = false;
this->denseDone_ = false;
this->goodPoints_.clear();
this->denseMean_ = NULL;
this->sparseMean_ = NULL;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setDecimation(float dec) {
this->decimationPercent_ = dec;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setMaxAngle(double angleDegrees) {
this->maxAngleDegrees_ = angleDegrees;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setNumClusters(int num) {
this->numClusters_ = num;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setFixWinding(bool fixWinding){
fixWinding_ = fixWinding;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setLaplacianSmoothingBeforeDecimation(bool doLaplacianSmoothingBeforeDecimation){
doLaplacianSmoothingBeforeDecimation_ = doLaplacianSmoothingBeforeDecimation;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setLaplacianSmoothingAfterDecimation(bool doLaplacianSmoothingAfterDecimation){
doLaplacianSmoothingAfterDecimation_ = doLaplacianSmoothingAfterDecimation;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setSmoothingLambda(float smoothingLambda){
smoothingLambda_= smoothingLambda;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setOutputEnabled(bool enabled){
this->output_enabled_ = enabled;
#ifdef WIN32
this->out_prefix_ = std::string(std::getenv("TEMP")) + "/";
#else
this->out_prefix_ = "/tmp/";
#endif
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setMeanBeforeWarpEnabled(bool enabled) {
this->mean_before_warp_enabled_ = enabled;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::setSmoothingIterations(int smoothingIterations){
smoothingIterations_ = smoothingIterations;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
vtkSmartPointer<vtkPolyData> Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::getMesh(
PointArrayType local_pts) {
//default reconstruction if no warping to dense mean has occurred yet
if (!this->denseDone_) {
return vtkSmartPointer<vtkPolyData>::New();
}
//we have a dense mean, so lets warp to subject space
std::vector<int> particles_indices;
for (int i = 0; i < this->goodPoints_.size(); i++) {
if (this->goodPoints_[i]) {
particles_indices.push_back(i);
}
}
vtkSmartPointer< vtkPoints > subjectPts = vtkSmartPointer<vtkPoints>::New();
for (auto &a : local_pts) {
subjectPts->InsertNextPoint(a[0], a[1], a[2]);
}
double sigma = this->computeAverageDistanceToNeighbors(subjectPts,
particles_indices);
// (3) set up the common source points for all warps
PointIdType id;
// NOTE that, since we are not resampling images, this warping is a
// forward warping from mean space to subject space
// Define container for source landmarks that corresponds to the mean space, this is
// the moving mesh which will be warped to each individual subject
typename PointSetType::Pointer sourceLandMarks = PointSetType::New();
typename PointSetType::PointsContainer::Pointer sourceLandMarkContainer =
sourceLandMarks->GetPoints();
PointType ps;
id = itk::NumericTraits< PointIdType >::Zero;
int ns = 0;
for (unsigned int ii = 0; ii < local_pts.size(); ii++) {
if (std::find(particles_indices.begin(),
particles_indices.end(), ii) != particles_indices.end()) {
double p[3];
this->sparseMean_->GetPoint(ii, p);
ps[0] = p[0];
ps[1] = p[1];
ps[2] = p[2];
sourceLandMarkContainer->InsertElement(id++, ps);
ns++;
}
}
typename TransformType::Pointer transform = TransformType::New();
transform->SetSigma(sigma); // smaller means more sparse
transform->SetStiffness(1e-10);
transform->SetSourceLandmarks(sourceLandMarks);
// Define container for target landmarks corresponds to the subject shape
typename PointSetType::Pointer targetLandMarks = PointSetType::New();
PointType pt;
typename PointSetType::PointsContainer::Pointer targetLandMarkContainer =
targetLandMarks->GetPoints();
id = itk::NumericTraits< PointIdType >::Zero;
int nt = 0;
for (unsigned int ii = 0; ii < local_pts.size(); ii++) {
if (std::find(particles_indices.begin(),
particles_indices.end(), ii) != particles_indices.end()) {
double p[3];
subjectPts->GetPoint(ii, p);
pt[0] = p[0];
pt[1] = p[1];
pt[2] = p[2];
targetLandMarkContainer->InsertElement(id++, pt);
nt++;
}
}
transform->SetTargetLandmarks(targetLandMarks);
// check the mapping (inverse here)
// this means source points (current sample's space) should
// be warped to the target (mean space)
vtkSmartPointer<vtkPoints> mappedCorrespondences =
vtkSmartPointer<vtkPoints>::New();
double rms;
double rms_wo_mapping;
double maxmDist;
this->CheckMapping(this->sparseMean_, subjectPts,
transform, mappedCorrespondences, rms, rms_wo_mapping, maxmDist);
vtkSmartPointer<vtkPolyData> denseShape = vtkSmartPointer<vtkPolyData>::New();
denseShape->DeepCopy(this->denseMean_);
this->generateWarpedMeshes(transform, denseShape);
return denseShape;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::readMeanInfo(std::string dense,
std::string sparse, std::string goodPoints) {
//read out dense mean
vtkSmartPointer<vtkPolyDataReader> reader1 = vtkPolyDataReader::New();
reader1->SetFileName(dense.c_str());
reader1->Update();
this->denseMean_ = reader1->GetOutput();
//read out sparse mean
int nPoints = 0;
std::ifstream ptsIn0(sparse.c_str());
this->sparseMean_ = vtkSmartPointer<vtkPoints>::New();
while (ptsIn0.good()) {
double x, y, z;
ptsIn0 >> x >> y >> z;
if (ptsIn0.good()) {
this->sparseMean_->InsertNextPoint(x, y, z);
nPoints++;
}
}
ptsIn0.close();
//read out good points
std::ifstream ptsIn(goodPoints.c_str());
this->goodPoints_.clear();
if(ptsIn.good()){
while (ptsIn.good()) {
int i;
ptsIn >> i;
if (ptsIn.good()) {
this->goodPoints_.push_back(i == 0 ? false : true);
}
}
}
else {
// good point file is not given if a template mesh is used instead of a mean
// just assume all are good
for(size_t i = 0 ; i < nPoints; i++)
this->goodPoints_.push_back(true);
}
ptsIn.close();
this->sparseDone_ = true;
this->denseDone_ = true;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
std::vector< std::vector<itk::Point<TCoordRep> > > Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::computeSparseMean(std::vector< PointArrayType > local_pts,
itk::Point<TCoordRep>& common_center, bool do_procrustes, bool do_procrustes_scaling)
{
// (1) define mean sparse shape:
// run generalized procrustes on the local points to align all shapes to a common coordinate frame
Procrustes3D::ShapeListType shapelist;
Procrustes3D::ShapeType shapevector;
Procrustes3D::ShapeType meanSparseShape;
Procrustes3D::PointType point;
// fill the shape list
for (unsigned int shapeNo = 0; shapeNo < local_pts.size(); shapeNo++)
{
shapevector.clear();
PointArrayType curShape = local_pts[shapeNo];
for(unsigned int ii = 0 ; ii < curShape.size(); ii++)
{
itk::Point<float> p = curShape[ii];
point(0) = double(p[0]);
point(1) = double(p[1]);
point(2) = double(p[2]);
shapevector.push_back(point);
}
shapelist.push_back(shapevector);
}
Procrustes3D procrustes;
Procrustes3D::PointType commonCenter;
Procrustes3D::SimilarityTransformListType transforms;
if(do_procrustes_scaling)
procrustes.ScalingOn();
else
procrustes.ScalingOff();
if(do_procrustes)
{
// Run alignment
procrustes.AlignShapes(transforms, shapelist); // shapes are actually aligned (modified) and transforms are returned
// Construct transform matrices for each particle system.
// Procrustes3D::TransformMatrixListType transformMatrices;
// procrustes.ConstructTransformMatrices(transforms,transformMatrices, do_procrustes_scaling); // note that tranforms scale is updated here if do_scaling ==1
}
else
{
// remove translation to compute the common center
procrustes.RemoveTranslation(transforms, shapelist); // shapes are actually aligned (modified) and transforms are returned
}
// this is the center which needed for translation of the shapes to coincide on the image origin
// so that the whole object is in the image and won't go outside
procrustes.ComputeCommonCenter(transforms, commonCenter);
common_center[0] = commonCenter[0];
common_center[1] = commonCenter[1];
common_center[2] = commonCenter[2];
std::cout << "commonCenter(0) = " << commonCenter[0] << ", "
<< "commonCenter(1) = " << commonCenter[1] << ", "
<< "commonCenter(2) = " << commonCenter[2] << std::endl;
// compute the average sparse shape
procrustes.ComputeMeanShape(meanSparseShape , shapelist);
medianShapeIndex_ = procrustes.ComputeMedianShape(shapelist);
sparseMean_= vtkSmartPointer< vtkPoints >::New(); // for visualization and estimating kernel support
double center[3] = {0,0,0};
for(unsigned int ii = 0 ; ii < meanSparseShape.size(); ii++)
{
double pt[3];
pt[0] = meanSparseShape[ii](0) - commonCenter(0);
pt[1] = meanSparseShape[ii](1) - commonCenter(1);
pt[2] = meanSparseShape[ii](2) - commonCenter(2);
center[0] += pt[0]; center[1] += pt[1]; center[2] += pt[2];
sparseMean_->InsertNextPoint(pt[0], pt[1], pt[2]);
}
center[0] /= meanSparseShape.size();
center[1] /= meanSparseShape.size();
center[2] /= meanSparseShape.size();
std::cout << "center(0) = " << center[0] << ", "
<< "center(1) = " << center[1] << ", "
<< "center(2) = " << center[2] << std::endl;
std::vector< PointArrayType > global_pts;
global_pts.clear();
// prep aligned shapes for subsequent statistical analysis
for (unsigned int shapeNo = 0; shapeNo < local_pts.size(); shapeNo++)
{
shapevector = shapelist[shapeNo];
PointArrayType curShape;
curShape.clear();
for(unsigned int ii = 0 ; ii < shapevector.size(); ii++)
{
itk::Point<float> pt;
pt[0] = shapevector[ii](0) - commonCenter(0);
pt[1] = shapevector[ii](1) - commonCenter(1);
pt[2] = shapevector[ii](2) - commonCenter(2);
curShape.push_back(pt);
}
global_pts.push_back(curShape);
}
sparseDone_ = true;
return global_pts;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
bool Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::sparseDone() {
return this->sparseDone_;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
bool Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::denseDone() {
return this->denseDone_;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::computeDenseMean(
std::vector< PointArrayType > local_pts,
std::vector< PointArrayType > global_pts,
std::vector<std::string> distance_transform) {
try {
//turn the sets of global points to one sparse global mean.
float init[] = { 0.f,0.f,0.f };
PointArrayType sparseMean =
PointArrayType(global_pts[0].size(), itk::Point<float>(init));
for (auto &a : global_pts) {
for (size_t i = 0; i < a.size(); i++) {
init[0] = a[i][0]; init[1] = a[i][1]; init[2] = a[i][2];
itk::Vector<float> vec(init);
sparseMean[i] = sparseMean[i] + vec;
}
}
auto div = static_cast<float>(global_pts.size());
for (size_t i = 0; i < sparseMean.size(); i++) {
init[0] = sparseMean[i][0] / div;
init[1] = sparseMean[i][1] / div;
init[2] = sparseMean[i][2] / div;
sparseMean[i] = itk::Point<float>(init);
}
std::vector<vnl_matrix<double> > normals;
std::vector<vtkSmartPointer< vtkPoints > > subjectPts;
this->sparseMean_ = vtkSmartPointer<vtkPoints>::New();
for (auto &a : sparseMean) {
this->sparseMean_->InsertNextPoint(a[0], a[1], a[2]);
}
for (size_t shape = 0; shape < local_pts.size(); shape++) {
subjectPts.push_back(vtkSmartPointer<vtkPoints>::New());
for (auto &a : local_pts[shape]) {
subjectPts[shape]->InsertNextPoint(a[0], a[1], a[2]);
}
//calculate the normals from the DT
normals.push_back(this->computeParticlesNormals(
subjectPts[shape], loadImage(distance_transform[shape])));
}
// now decide whether each particle is a good based on dispersion from mean
// (it normals are in the same direction accross shapes) or
// bad (there is discrepency in the normal directions across shapes)
this->goodPoints_.resize(local_pts[0].size(), true);
if(usePairwiseNormalsDifferencesForGoodBad_){
for (unsigned int ii = 0; ii < local_pts[0].size(); ii++) {
bool isGood = true;
// the normal of the first shape
double nx_jj = normals[0](ii, 0);
double ny_jj = normals[0](ii, 1);
double nz_jj = normals[0](ii, 2);
// start from the second
for (unsigned int shapeNo_kk = 1; shapeNo_kk <
local_pts.size(); shapeNo_kk++) {
double nx_kk = normals[shapeNo_kk](ii, 0);
double ny_kk = normals[shapeNo_kk](ii, 1);
double nz_kk = normals[shapeNo_kk](ii, 2);
this->goodPoints_[ii] = this->goodPoints_[ii] &&
((nx_jj*nx_kk + ny_jj*ny_kk + nz_jj*nz_kk) >
std::cos(this->maxAngleDegrees_ * M_PI / 180.));
}
}
}
else {
// here use the angle to the average normal
// spherical coordinates of normal vector per particle per shape sample to compute average normals
std::vector< std::vector< double > > thetas ; thetas.clear();
std::vector< std::vector< double > > phis; phis.clear();
thetas.resize(sparseMean.size());
phis.resize(sparseMean.size());
for (size_t j = 0; j < sparseMean.size(); j++) {
thetas[j].resize(local_pts.size());
phis[j].resize(local_pts.size());
}
for (int i = 0; i < local_pts.size(); i++){
for (size_t j = 0; j < sparseMean.size(); j++) {
double curNormal[3];
double curNormalSph[3];
curNormal[0] = normals[i](j,0);
curNormal[1] = normals[i](j,1);
curNormal[2] = normals[i](j,2);
Utils::cartesian2spherical(curNormal, curNormalSph);
phis[j][i] = curNormalSph[1];
thetas[j][i] = curNormalSph[2];
}
}
// compute mean normal for every particle
vnl_matrix<double> average_normals(sparseMean.size(), 3);
for (size_t j = 0; j < sparseMean.size(); j++) {
double avgNormal_sph[3];
double avgNormal_cart[3];
avgNormal_sph[0] = 1;
avgNormal_sph[1] = Utils::averageThetaArc(phis[j]);
avgNormal_sph[2] = Utils::averageThetaArc(thetas[j]);
Utils::spherical2cartesian(avgNormal_sph, avgNormal_cart);
average_normals(j,0) = avgNormal_cart[0];
average_normals(j,1) = avgNormal_cart[1];
average_normals(j,2) = avgNormal_cart[2];
}
for (size_t j = 0; j < sparseMean.size(); j++) {
double cur_cos_appex = 0;
// the mean normal of the current particle index
double nx_jj = average_normals(j,0);
double ny_jj = average_normals(j,1);
double nz_jj = average_normals(j,2);
for (unsigned int shapeNo_kk = 0; shapeNo_kk < local_pts.size(); shapeNo_kk++) {
double nx_kk = normals[shapeNo_kk](j, 0);
double ny_kk = normals[shapeNo_kk](j, 1);
double nz_kk = normals[shapeNo_kk](j, 2);
cur_cos_appex += (nx_jj*nx_kk + ny_jj*ny_kk + nz_jj*nz_kk);
}
cur_cos_appex /= local_pts.size();
cur_cos_appex *= 2.0; // due to symmetry about the mean normal
this->goodPoints_[j] = cur_cos_appex > std::cos(this->maxAngleDegrees_ * M_PI / 180.);
}
}
// decide which correspondences will be used to build the warp
std::vector<int> particles_indices;
particles_indices.clear();
for (unsigned int kk = 0; kk < this->goodPoints_.size(); kk++) {
if (this->goodPoints_[kk]) {
particles_indices.push_back(int(kk));
}
}
std::cout << "maxAngleDegrees_ = " << maxAngleDegrees_ << "\n";
std::cout << "There are " << particles_indices.size() << " / " << this->goodPoints_.size() <<
" good points." << std::endl;
// The parameters of the output image are taken from the input image.
// NOTE: all distance transforms were generated throughout shapeworks pipeline
// as such they have the same parameters
typename ImageType::Pointer image = loadImage(distance_transform[0]);
const typename ImageType::SpacingType& spacing = image->GetSpacing();
const typename ImageType::PointType& origin = image->GetOrigin();
const typename ImageType::DirectionType& direction = image->GetDirection();
typename ImageType::SizeType size = image->GetLargestPossibleRegion().GetSize();
typename ImageType::RegionType region = image->GetBufferedRegion();
// define the mean dense shape (mean distance transform)
typename ImageType::Pointer meanDistanceTransform = ImageType::New();
if(use_origin)
meanDistanceTransform->SetOrigin(origin_);
else
meanDistanceTransform->SetOrigin(origin);
meanDistanceTransform->SetSpacing(spacing);
meanDistanceTransform->SetDirection(direction);
meanDistanceTransform->SetLargestPossibleRegion(size);
typename ImageType::Pointer meanDistanceTransformBeforeWarp = ImageType::New();
if(use_origin)
meanDistanceTransformBeforeWarp->SetOrigin(origin_);
else
meanDistanceTransformBeforeWarp->SetOrigin(origin);
meanDistanceTransformBeforeWarp->SetSpacing(spacing);
meanDistanceTransformBeforeWarp->SetDirection(direction);
meanDistanceTransformBeforeWarp->SetLargestPossibleRegion(size);
typename AddImageFilterType::Pointer sumfilter = AddImageFilterType::New();
typename AddImageFilterType::Pointer sumfilterBeforeWarp = AddImageFilterType::New();
// Define container for source landmarks that corresponds to the mean space, this is
// fixed where the target (each individual shape) will be warped to
// NOTE that this is inverse warping to avoid holes in the warped distance transforms
typename PointSetType::Pointer sourceLandMarks = PointSetType::New();
typename PointSetType::PointsContainer::Pointer sourceLandMarkContainer = sourceLandMarks->GetPoints();
PointType ps;
PointIdType id = itk::NumericTraits< PointIdType >::Zero;
int ns = 0;
for (unsigned int ii = 0; ii < local_pts[0].size(); ii++) {
if (std::find(particles_indices.begin(),
particles_indices.end(), ii) != particles_indices.end()) {
double p[3];
this->sparseMean_->GetPoint(ii, p);
ps[0] = p[0];
ps[1] = p[1];
ps[2] = p[2];
sourceLandMarkContainer->InsertElement(id++, ps);
ns++;
}
}
double sigma = computeAverageDistanceToNeighbors(
this->sparseMean_, particles_indices);
// the roles of the source and target are reversed to simulate a reverse warping
// without explicitly invert the warp in order to avoid holes in the warping result
typename TransformType::Pointer transform = TransformType::New();
transform->SetSigma(sigma); // smaller means more sparse
//transform->SetStiffness(0.25*sigma);
transform->SetStiffness(1e-10);
transform->SetSourceLandmarks(sourceLandMarks);
//////////////////////////////////////////////////////////////////
//Praful - get the shape indices corresponding to cetroids of
//kmeans clusters and run the following loop on only those shapes
// Read input shapes from file list
std::vector<int> centroidIndices;
if (this->numClusters_ > 0 && this->numClusters_ < global_pts.size()) {
this->performKMeansClustering(global_pts, global_pts[0].size(), centroidIndices);
} else {
this->numClusters_ = distance_transform.size();
centroidIndices.resize(distance_transform.size());
for (size_t shapeNo = 0; shapeNo < distance_transform.size(); shapeNo++) {
centroidIndices[shapeNo] = int(shapeNo);
std::cout << centroidIndices[shapeNo] << std::endl;
}
}
//////////////////////////////////////////////////////////////////
//Praful - clustering
for (unsigned int cnt = 0; cnt < centroidIndices.size(); cnt++) {
size_t shape = size_t(centroidIndices[cnt]);
typename ImageType::Pointer dt = loadImage(distance_transform[shape]);
typename PointSetType::Pointer targetLandMarks = PointSetType::New();
PointType pt;
typename PointSetType::PointsContainer::Pointer
targetLandMarkContainer = targetLandMarks->GetPoints();
id = itk::NumericTraits< PointIdType >::Zero;
int nt = 0;
for (unsigned int ii = 0; ii < local_pts[0].size(); ii++) {
if (std::find(particles_indices.begin(),
particles_indices.end(), ii) != particles_indices.end()) {
double p[3];
subjectPts[shape]->GetPoint(ii, p);
pt[0] = p[0];
pt[1] = p[1];
pt[2] = p[2];
targetLandMarkContainer->InsertElement(id++, pt);
nt++;
}
}
transform->SetTargetLandmarks(targetLandMarks);
// check the mapping (inverse here)
// this mean source points (mean space) should
// be warped to the target (current sample's space)
vtkSmartPointer<vtkPoints> mappedCorrespondences = vtkSmartPointer<vtkPoints>::New();
double rms;
double rms_wo_mapping;
double maxmDist;
this->CheckMapping(this->sparseMean_, subjectPts[shape], transform,
mappedCorrespondences, rms, rms_wo_mapping, maxmDist);
// Set the resampler params
typename ResampleFilterType::Pointer resampler = ResampleFilterType::New();
typename InterpolatorType::Pointer interpolator = InterpolatorType::New();
//interpolator->SetSplineOrder(3); // itk has a default bspline order = 3
resampler->SetInterpolator(interpolator);
resampler->SetOutputSpacing(spacing);
resampler->SetOutputDirection(direction);
if(use_origin)
resampler->SetOutputOrigin(origin_);
else
resampler->SetOutputOrigin(origin);
resampler->SetSize(size);
resampler->SetTransform(transform);
resampler->SetDefaultPixelValue((PixelType)-100.0);
resampler->SetOutputStartIndex(region.GetIndex());
resampler->SetInput(dt);
resampler->Update();
if (cnt == 0) {
// after warp
typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage(resampler->GetOutput());
duplicator->Update();
meanDistanceTransform = duplicator->GetOutput();
// before warp
typename DuplicatorType::Pointer duplicator2 = DuplicatorType::New();
duplicator2->SetInputImage(dt);
duplicator2->Update();
meanDistanceTransformBeforeWarp = duplicator2->GetOutput();
} else {
// after warp
sumfilter->SetInput1(meanDistanceTransform);
sumfilter->SetInput2(resampler->GetOutput());
sumfilter->Update();
typename DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage(sumfilter->GetOutput());
duplicator->Update();
meanDistanceTransform = duplicator->GetOutput();
if (this->mean_before_warp_enabled_) {
// before warp
sumfilterBeforeWarp->SetInput1(meanDistanceTransformBeforeWarp);
sumfilterBeforeWarp->SetInput2(dt);
sumfilterBeforeWarp->Update();
typename DuplicatorType::Pointer duplicator2 = DuplicatorType::New();
duplicator2->SetInputImage(sumfilterBeforeWarp->GetOutput());
duplicator2->Update();
meanDistanceTransformBeforeWarp = duplicator2->GetOutput();
}
}
}
typename MultiplyByConstantImageFilterType::Pointer multiplyImageFilter =
MultiplyByConstantImageFilterType::New();
multiplyImageFilter->SetInput(meanDistanceTransform);
multiplyImageFilter->SetConstant(1.0 /
static_cast<double>(this->numClusters_));
multiplyImageFilter->Update();
typename MultiplyByConstantImageFilterType::Pointer multiplyImageFilterBeforeWarp =
MultiplyByConstantImageFilterType::New();
multiplyImageFilterBeforeWarp->SetInput(meanDistanceTransformBeforeWarp);
multiplyImageFilterBeforeWarp->SetConstant(1.0 /
static_cast<double>(this->numClusters_));
multiplyImageFilterBeforeWarp->Update();
std::string meanDT_filename = out_prefix_ + "/" + "_meanDT.nrrd" ;;
std::string meanDTBeforeWarp_filename = out_prefix_ + "/" + "_meanDT_beforeWarp.nrrd" ;;
if (this->output_enabled_)
{
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( meanDT_filename.c_str());
writer->SetInput( multiplyImageFilter->GetOutput() );
writer->Update();
if (this->mean_before_warp_enabled_) {
writer->SetFileName(meanDTBeforeWarp_filename.c_str());
writer->SetInput(multiplyImageFilterBeforeWarp->GetOutput());
writer->Update();
}
}
// going to vtk to extract the template mesh (mean dense shape)
// to be deformed for each sparse shape
typename ITK2VTKConnectorType::Pointer itk2vtkConnector = ITK2VTKConnectorType::New();
itk2vtkConnector->SetInput(multiplyImageFilter->GetOutput());
itk2vtkConnector->Update();
this->denseMean_ =
this->extractIsosurface(itk2vtkConnector->GetOutput());
this->denseMean_ = this->MeshQC(this->denseMean_);
} catch (std::runtime_error e) {
if (this->denseMean_ != NULL) {
this->denseDone_ = true;
throw std::runtime_error("Warning! MeshQC failed, but a dense mean was computed by VTK.");
}
} catch (itk::ExceptionObject& excep) {
throw std::runtime_error(excep.what());
} catch (...) {
throw std::runtime_error("Reconstruction failed!");
}
this->denseDone_ = true;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
vnl_matrix<double> Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::computeParticlesNormals(
vtkSmartPointer< vtkPoints > particles,
typename ImageType::Pointer distance_transform)
{
const typename ImageType::SpacingType& spacing = distance_transform->GetSpacing();
const typename ImageType::PointType& origin = distance_transform->GetOrigin();
// (2) get normals at each voxel from the implicit representation
// Create and setup a gradient filter
typename GradientFilterType::Pointer gradientFilter = GradientFilterType::New();
gradientFilter->SetInput(distance_transform);
gradientFilter->Update();
typename GradientMagnitudeFilterType::Pointer gradientMagFilter = GradientMagnitudeFilterType::New();
gradientMagFilter->SetInput(distance_transform);
gradientMagFilter->Update();
typename ImageType::Pointer gradMagImage = ImageType::New();
gradMagImage = gradientMagFilter->GetOutput();
typename GradientImageType::Pointer gradientImage = GradientImageType::New();
gradientImage = gradientFilter->GetOutput();
// iterate through the gradient to convert it to normal = -gradient/mag(gradient)
GradientImageIteratorType gradIter(gradientImage, gradientImage->GetRequestedRegion());
ImageIteratorType magIter(gradMagImage, gradMagImage->GetRequestedRegion());
// initialize the images that will hold the normal components
typename ImageType::Pointer nxImage = ImageType::New();
nxImage->SetRegions(distance_transform->GetLargestPossibleRegion());
nxImage->Allocate();
ImageIteratorType nxIter(nxImage, nxImage->GetRequestedRegion());
typename ImageType::Pointer nyImage = ImageType::New();
nyImage->SetRegions(distance_transform->GetLargestPossibleRegion());
nyImage->Allocate();
ImageIteratorType nyIter(nyImage, nyImage->GetRequestedRegion());
typename ImageType::Pointer nzImage = ImageType::New();
nzImage->SetRegions(distance_transform->GetLargestPossibleRegion());
nzImage->Allocate();
ImageIteratorType nzIter(nzImage, nzImage->GetRequestedRegion());
for (gradIter.GoToBegin(), magIter.GoToBegin(), nxIter.GoToBegin(),
nyIter.GoToBegin(), nzIter.GoToBegin(); !gradIter.IsAtEnd();
++gradIter, ++magIter, ++nxIter, ++nyIter, ++nzIter) {
itk::CovariantVector<float, 3> grad = gradIter.Get();
float gradMag = magIter.Get();
float nx = -1.0f*grad[0] / (1e-10f + gradMag);
float ny = -1.0f*grad[1] / (1e-10f + gradMag);
float nz = -1.0f*grad[2] / (1e-10f + gradMag);
nxIter.Set(nx);
nyIter.Set(ny);
nzIter.Set(nz);
}
// going to vtk for probing ...
typename ITK2VTKConnectorType::Pointer connector_x = ITK2VTKConnectorType::New();
connector_x->SetInput(nxImage);
connector_x->Update();
vtkSmartPointer<vtkImageData> Nx = vtkSmartPointer<vtkImageData>::New();
Nx = connector_x->GetOutput();
typename ITK2VTKConnectorType::Pointer connector_y = ITK2VTKConnectorType::New();
connector_y->SetInput(nyImage);
connector_y->Update();
vtkSmartPointer<vtkImageData> Ny = vtkSmartPointer<vtkImageData>::New();
Ny = connector_y->GetOutput();
typename ITK2VTKConnectorType::Pointer connector_z = ITK2VTKConnectorType::New();
connector_z->SetInput(nzImage);
connector_z->Update();
vtkSmartPointer<vtkImageData> Nz = vtkSmartPointer<vtkImageData>::New();
Nz = connector_z->GetOutput();
vtkSmartPointer<vtkPolyData> particlesData =
vtkSmartPointer<vtkPolyData>::New();
particlesData->SetPoints(particles);
vtkSmartPointer<vtkPoints> pts =
this->convertToImageCoordinates(particlesData->GetPoints(),
particlesData->GetPoints()->GetNumberOfPoints(), spacing, origin);
particlesData->SetPoints(pts);
// (4) get the normals by probing the DT-based normal computation
vtkSmartPointer<vtkProbeFilter> probe_x = vtkSmartPointer<vtkProbeFilter>::New();
#if (VTK_MAJOR_VERSION < 6)
probe_x->SetInput(particlesData);
probe_x->SetSource(Nx);
#else
probe_x->SetInputData(particlesData);
probe_x->SetSourceData(Nx);
#endif
probe_x->Update();
vtkSmartPointer<vtkProbeFilter> probe_y = vtkSmartPointer<vtkProbeFilter>::New();
#if (VTK_MAJOR_VERSION < 6)
probe_y->SetInput(particlesData);
probe_y->SetSource(Ny);
#else
probe_y->SetInputData(particlesData);
probe_y->SetSourceData(Ny);
#endif
probe_y->Update();
vtkSmartPointer<vtkProbeFilter> probe_z = vtkSmartPointer<vtkProbeFilter>::New();
#if (VTK_MAJOR_VERSION < 6)
probe_z->SetInput(particlesData);
probe_z->SetSource(Nz);
#else
probe_z->SetInputData(particlesData);
probe_z->SetSourceData(Nz);
#endif
probe_z->Update();
vtkFloatArray* nx = vtkFloatArray::SafeDownCast(
probe_x->GetOutput()->GetPointData()->GetScalars());
vtkFloatArray* ny = vtkFloatArray::SafeDownCast(
probe_y->GetOutput()->GetPointData()->GetScalars());
vtkFloatArray* nz = vtkFloatArray::SafeDownCast(
probe_z->GetOutput()->GetPointData()->GetScalars());
// Set point normals
vtkSmartPointer<vtkDoubleArray> pointNormalsArray =
vtkSmartPointer<vtkDoubleArray>::New();
pointNormalsArray->SetNumberOfComponents(3); //3d normals (ie x,y,z)
pointNormalsArray->SetNumberOfTuples(particlesData->GetNumberOfPoints());
vnl_matrix<double> particlesNormals(particles->GetNumberOfPoints(), 3);
for (unsigned int ii = 0; ii < particlesData->GetNumberOfPoints(); ii++) {
double pN[3];
// getting the normals at particles
pN[0] = double(nx->GetValue(ii));
pN[1] = double(ny->GetValue(ii));
pN[2] = double(nz->GetValue(ii));
// making sure this is a unit vector
double norm = sqrt(pN[0] * pN[0] + pN[1] * pN[1] + pN[2] * pN[2]);
pN[0] = pN[0] / norm;
pN[1] = pN[1] / norm;
pN[2] = pN[2] / norm;
particlesNormals(ii, 0) = pN[0];
particlesNormals(ii, 1) = pN[1];
particlesNormals(ii, 2) = pN[2];
double p[3];
particlesData->GetPoint(ii, p);
// Add the data to the normals array
pointNormalsArray->SetTuple(ii, pN);
}
// Add the normals to the points in the polydata
particlesData->GetPointData()->SetNormals(pointNormalsArray);
vtkSmartPointer<vtkPoints> pts2 =
this->convertToPhysicalCoordinates(particlesData->GetPoints(),
particlesData->GetPoints()->GetNumberOfPoints(), spacing, origin);
particlesData->SetPoints(pts2);
return particlesNormals;
}
template < template < typename TCoordRep, unsigned > class TTransformType,
template < typename ImageType, typename TCoordRep > class TInterpolatorType,
typename TCoordRep, typename PixelType, typename ImageType>
void Reconstruction<TTransformType,TInterpolatorType, TCoordRep, PixelType, ImageType>::generateWarpedMeshes(
typename TransformType::Pointer transform,
vtkSmartPointer<vtkPolyData>& outputMesh) {
// generate warped meshes
vtkSmartPointer<vtkPoints> vertices = vtkSmartPointer<vtkPoints>::New();
vertices->DeepCopy(outputMesh->GetPoints());
unsigned int numPointsToTransform = vertices->GetNumberOfPoints();
for (unsigned int i = 0; i < numPointsToTransform; i++)
{
double meshPoint[3];
vertices->GetPoint(i, meshPoint);
itk::Point<double, 3> pm_;
itk::Point<double, 3> pw_;
pm_[0] = meshPoint[0]; pm_[1] = meshPoint[1]; pm_[2] = meshPoint[2];
pw_ = transform->TransformPoint(pm_);
vertices->SetPoint(i, pw_[0], pw_[1], pw_[2]);
}
outputMesh->SetPoints(vertices);
outputMesh->Modified();