-
Notifications
You must be signed in to change notification settings - Fork 7
/
HistogramMeanThreshold.h
1144 lines (926 loc) · 38.3 KB
/
HistogramMeanThreshold.h
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
//////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2013 Carlos Becker //
// Ecole Polytechnique Federale de Lausanne //
// Contact <carlos.becker@epfl.ch> for comments & bug reports //
// //
// This program is free software: you can redistribute it and/or modify //
// it under the terms of the version 3 of the GNU General Public License //
// as published by the Free Software Foundation. //
// //
// This program is distributed in the hope that it will be useful, but //
// WITHOUT ANY WARRANTY; without even the implied warranty of //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //
// General Public License for more details. //
// //
// You should have received a copy of the GNU General Public License //
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
//////////////////////////////////////////////////////////////////////////////////
#ifndef HISTOGRAMMEANTHRESHOLD_H
#define HISTOGRAMMEANTHRESHOLD_H
#include <vector>
#include <algorithm>
#include <Eigen/Dense>
#include <cstdio>
#include "IntegralImage.h"
#include <libconfig.hh>
// a single box for each location
typedef BoxPosition BoxPositionType;
// for a list of samples, we need a list of BoxPositionType elements, one for each
typedef std::vector<BoxPositionType> BoxPositionVector;
typedef double AdaBoostErrorType;
#define USE_DIFFERENCE_SPLIT 0
struct HistogramMeanThresholdData
{
// number of weak learners to explore (train)
unsigned int numWLToExplore;
const std::vector<UIntPoint3D> &svCentroid; // SV centroids
const std::vector< Eigen::Matrix3f > &rotMatrices;
const std::vector<IntegralImage<IntegralImageType> * > &pixIntImages; // list of integral images of features
float distMin, distMax;
unsigned int distSteps;
float angThMin, angThMax;
unsigned int angThSteps;
float angPhMin, angPhMax;
unsigned int angPhSteps;
float zAnisotropyFactor;
float invZAnisotropyFactor; // a cached version of 1.0 / zAnisotropyFactor
unsigned int rMin;
unsigned int rMax;
unsigned int rSteps;
Eigen::Matrix< float, 3, Eigen::Dynamic > possibleOffsets;
std::vector<unsigned int> possibleOffsetsRadius;
const Matrix3D<unsigned int> &pixToSV; //pixel to supervoxel map
#if APPLY_PATCH_VARNORM
// inverse std dev (1/stddev) and mean for every channel, per supervoxel
const std::vector< std::vector<float> > &svoxWindowInvStd;
const std::vector< std::vector<float> > &svoxWindowMean;
#endif
inline HistogramMeanThresholdData( const std::vector<UIntPoint3D> ¢roids,
const std::vector< Eigen::Matrix3f > &rMatrices,
const std::vector<IntegralImage<IntegralImageType> * > &iimgs,
const Matrix3D<unsigned int> &pixtosv,
const double _zAnisotropyFactor
#if APPLY_PATCH_VARNORM
,
const std::vector< std::vector<float> > &_svoxWindowInvStd,
const std::vector< std::vector<float> > &_svoxWindowMean
#endif
)
: svCentroid(centroids), rotMatrices(rMatrices), pixIntImages(iimgs), pixToSV(pixtosv),
zAnisotropyFactor(_zAnisotropyFactor)
#if APPLY_PATCH_VARNORM
,svoxWindowInvStd(_svoxWindowInvStd), svoxWindowMean(_svoxWindowMean)
#endif
{
invZAnisotropyFactor = 1.0 / zAnisotropyFactor;
numWLToExplore = 4000;
#if !LOCAL_ONLY
#pragma message("Using remote cubes")
distMin = -20;
distMax = 20;
distSteps = 11;
rMin = 0;
rMax = 20;
rSteps = 11;
angThMin = 0;
angThMax = M_PI/2 - 0.1;
angThSteps = 6;
//angThSteps = 3;
angPhMin = 0.0;
angPhMax = 2*M_PI;
angPhSteps = 10;
//angPhSteps = 5;
#else
#pragma message("Using local cubes only")
distMin = 0;
distMax = 0;
distSteps = 1;
rMin = 0;
rMax = 20;
rSteps = 11;
angThMin = 0;
angThMax = 0;
angThSteps = 1;
//angThSteps = 3;
angPhMin = 0.0;
angPhMax = 0.0;
angPhSteps = 1;
#endif
#if 0
rMin = 0;
rMax = 20;
rSteps = 11;
distMin = distMax = 0;
distSteps = 1;
angThMin = 0;
angThMax = 0;
angThSteps = 1;
angPhMin = 0;
angPhMax = 0;
angPhSteps = 1;
#endif
precomputeOrients();
}
void precomputeOrients()
{
possibleOffsetsRadius.clear();
unsigned rStep = 2;
possibleOffsets.resize( 3, distSteps * angThSteps * angPhSteps * rSteps );
possibleOffsetsRadius.resize( possibleOffsets.size() );
double dStep = (distMax - distMin) / std::max( (distSteps - 1), 1U );
double angThStep = (angThMax - angThMin) / std::max( (angThSteps - 1), 1U );
double angPhStep = (angPhMax - angPhMin) / std::max( (angPhSteps - 1), 1U );
qDebug("dStep: %f", dStep);
qDebug("angThStep: %f", angThStep);
qDebug("angPhStep: %f", angPhStep);
unsigned ii = 0;
for (unsigned ths=0; ths < angThSteps; ths++)
{
double theta = angThMin + angThStep * ths;
for (unsigned phs=0; phs < angPhSteps; phs++)
{
double phi = angPhMin + angPhStep * phs;
Eigen::Vector3f angleVec;
angleVec(0) = cos(phi)*sin(theta);
angleVec(1) = sin(phi)*sin(theta);
angleVec(2) = cos(theta);
std::cout << "Angvec: " << angleVec << std::endl;
for (unsigned ds=0; ds < distSteps; ds++)
{
float d = distMin + dStep*ds;
for (unsigned r = rMin; r <= rMax; r += rStep)
{
possibleOffsets.col(ii) = d * angleVec;
possibleOffsetsRadius[ii] = r;
ii++;
}
}
}
}
qDebug("---> Number of pose indexes: %d (%d)", (int) possibleOffsets.cols(), (int)ii );
if (possibleOffsets.cols() != ii)
qFatal("error here, fix: %d %d!", (int)possibleOffsets.cols(), (int)ii );
}
float poseIndexMagnitude( unsigned poseIdx ) const
{
if (poseIdx >= possibleOffsets.cols())
qFatal("Poseidx exceed possible value");
return possibleOffsets.col(poseIdx).norm();
}
float poseIndexTheta( unsigned poseIdx ) const
{
if (poseIdx >= possibleOffsets.cols())
qFatal("Poseidx exceed possible value");
return 180.0 * acos( possibleOffsets.col(poseIdx)(2) / possibleOffsets.col(poseIdx).norm() ) / M_PI;
}
float poseIndexPhi( unsigned poseIdx ) const
{
if (poseIdx >= possibleOffsets.cols())
qFatal("Poseidx exceed possible value");
return 180.0 * atan2( possibleOffsets.col(poseIdx)(1), possibleOffsets.col(poseIdx)(0) ) / M_PI;
}
unsigned poseIndexRadius( unsigned poseIdx ) const
{
if (poseIdx >= possibleOffsetsRadius.size())
qFatal("Poseidx exceed possible value");
return possibleOffsetsRadius[poseIdx];
}
inline void setDistanceLimits( float min, float max ) {
distMin = min;
distMax = max;
}
// returns number of pose idxs
inline unsigned numPosIdx() const
{
return possibleOffsets.cols();
}
void poseIndexedFeature( const unsigned poseIdx, const unsigned sampleIdx, BoxPositionType *box ) const
{
/*if (poseIdx >= possibleOffsetsRadius.size())
qFatal("Poseidx exceed possible value");*/
const unsigned int Vwidth = pixToSV.width();
const unsigned int Vheight = pixToSV.height();
const unsigned int Vdepth = pixToSV.depth();
const float radius = possibleOffsetsRadius[poseIdx];
//for (unsigned int s=0; s < sampleIdxs.size(); s++)
{
UIntPoint3D pt = svCentroid[ sampleIdx ];
// resize first
Eigen::Vector3f orient = rotMatrices[sampleIdx] * possibleOffsets.col(poseIdx);
FloatPoint3D newPt;
newPt.x = round(pt.x + orient.coeff(0));
newPt.y = round(pt.y + orient.coeff(1));
newPt.z = round(pt.z + invZAnisotropyFactor * orient.coeff(2));
//FIXME //TODO quick bug patch
if (std::isnan(newPt.x)) newPt.x = 1;
if (std::isnan(newPt.y)) newPt.y = 1;
if (std::isnan(newPt.z)) newPt.z = 1;
if (newPt.x < 1) newPt.x = 1;
if (newPt.y < 1) newPt.y = 1;
if (newPt.z < 1) newPt.z = 1;
if (newPt.x >= Vwidth) newPt.x = Vwidth - 1;
if (newPt.y >= Vheight) newPt.y = Vheight - 1;
if (newPt.z >= Vdepth) newPt.z = Vdepth - 1;
float rx = radius;
float ry = radius;
float rz = invZAnisotropyFactor * radius;
// check image borders
if ( newPt.x - rx <= 1 ) rx = newPt.x - 2;
if ( newPt.y - ry <= 1 ) ry = newPt.y - 2;
if ( newPt.z - rz <= 1 ) rz = newPt.z - 2;
if ( newPt.x + rx >= Vwidth ) rx = newPt.x - Vwidth - 1;
if ( newPt.y + ry >= Vheight) ry = newPt.y - Vheight - 1;
if ( newPt.z + rz >= Vdepth ) rz = newPt.z - Vdepth - 1;
rx = (rx >= 0)? rx : 0;
ry = (ry >= 0)? ry : 0;
rz = (rz >= 0)? rz : 0;
box->x = newPt.x;
box->y = newPt.y;
box->z = newPt.z;
box->rx = rx;
box->ry = ry;
box->rz = rz;
}
}
};
#if 0 // needs to be fixed
template<typename ParamsType, typename WeightsType, bool cacheValues = true>
struct FeatureSubtractorOperator
{
const unsigned mPoseIdxA, mPoseIdxB;
const WeightsType &mWeights;
const std::vector<unsigned int> &mClassLabels;
const unsigned int mCol;
const ParamsType &mParams;
std::vector< IntegralImageType > mCachedValues;
inline FeatureSubtractorOperator( const unsigned poseIdxA, const unsigned poseIdxB,
const WeightsType &weights, const std::vector<unsigned int> classLabels,
unsigned int numCol, const ParamsType ¶ms ):
mPoseIdxA(poseIdxA), mPoseIdxB(poseIdxB), mWeights(weights), mClassLabels(classLabels),
mCol(numCol), mParams(params)
{
if (cacheValues)
{
mCachedValues.resize( mWeights.size() );
for (unsigned i=0; i < mWeights.size(); i++)
mCachedValues[i] = nonCachedValue(i);
}
}
inline IntegralImageType nonCachedValue( unsigned int idx ) const
{
BoxPositionType boxA, boxB;
mParams.poseIndexedFeature( mPoseIdxA, mSampleIdxs
return mParams.pixIntImages[mCol]->centeredSum( boxA ) - mParams.pixIntImages[mCol]->centeredSum( boxB );
}
inline IntegralImageType value( unsigned int idx ) const {
if (cacheValues)
return mCachedValues[idx];
else
return nonCachedValue(idx);
}
inline typename WeightsType::Scalar weight( unsigned int idx ) const {
return mWeights.coeff( idx );
}
inline unsigned int label( unsigned int idx ) const {
return mClassLabels[idx];
}
inline unsigned int count() const { return mWeights.size(); }
};
#endif
template<typename ParamsType, typename WeightsType, bool cacheValues = true>
struct FeatureRawOperator
{
const unsigned mPoseIdx;
const WeightsType &mWeights;
const std::vector<unsigned int> &mClassLabels;
const unsigned int mCol;
const ParamsType &mParams;
const std::vector<unsigned int> &sampleIdxs;
std::vector< IntegralImageType > mCachedValues;
inline FeatureRawOperator( const unsigned poseIdx, const WeightsType &weights, const std::vector<unsigned int> classLabels,
unsigned int numCol, const ParamsType ¶ms,
const std::vector<unsigned int> &_sampleIdxs ):
mPoseIdx(poseIdx), mWeights(weights), mClassLabels(classLabels),
mCol(numCol), mParams(params),
sampleIdxs(_sampleIdxs)
{
if (cacheValues)
{
mCachedValues.resize( mWeights.size() );
for (unsigned i=0; i < mWeights.size(); i++)
mCachedValues[i] = nonCachedValue(i);
}
}
inline IntegralImageType nonCachedValue( unsigned int idx ) const
{
BoxPositionType box;
mParams.poseIndexedFeature( mPoseIdx, sampleIdxs[idx], &box );
#if APPLY_PATCH_VARNORM
return mParams.pixIntImages[mCol]->centeredSumNormalized( box, mParams.svoxWindowMean[mCol][sampleIdxs[idx]], mParams.svoxWindowInvStd[mCol][sampleIdxs[idx]]);
#else
return mParams.pixIntImages[mCol]->centeredSum( box );
#endif
}
inline IntegralImageType value( unsigned int idx ) const
{
if (cacheValues)
return mCachedValues[idx];
else
return nonCachedValue(idx);
}
inline typename WeightsType::Scalar weight( unsigned int idx ) const {
return mWeights.coeff( idx );
}
inline unsigned int label( unsigned int idx ) const {
return mClassLabels[idx];
}
inline unsigned int count() const { return mWeights.size(); }
};
template<typename ValuesArrayType, typename WeightsType>
struct FeatureOperatorPrecomputedValues
{
const WeightsType &mWeights;
const std::vector<unsigned int> &mClassLabels;
const std::vector<unsigned int> &sampleIdxs;
const ValuesArrayType &mCachedValues;
typedef typename ValuesArrayType::Scalar ValueScalarType;
inline FeatureOperatorPrecomputedValues(
const ValuesArrayType &cachedValues,
const WeightsType &weights, const std::vector<unsigned int> classLabels,
const std::vector<unsigned int> &_sampleIdxs ):
mCachedValues(cachedValues), mWeights(weights), mClassLabels(classLabels),
sampleIdxs(_sampleIdxs)
{
}
inline ValueScalarType value( unsigned int idx ) const
{
return mCachedValues.coeff(idx);
}
inline typename WeightsType::Scalar weight( unsigned int idx ) const {
return mWeights.coeff( idx );
}
inline unsigned int label( unsigned int idx ) const {
return mClassLabels[idx];
}
inline unsigned int count() const { return mWeights.size(); }
};
template<typename FeatureOperatorType>
class SortFeature
{
private:
const FeatureOperatorType &mFop;
public:
inline SortFeature( const FeatureOperatorType &fop ) : mFop(fop) {}
inline bool operator()(unsigned int l, unsigned int r) const
{
return mFop.value(l) < mFop.value(r);
}
};
template<typename T2>
class SortMatrixByColumnOnlyIndex
{
private:
const T2 &mData;
const unsigned int mCol;
public:
SortMatrixByColumnOnlyIndex( const T2 &data, unsigned int col ) : mData(data), mCol(col) {}
inline bool operator()(unsigned int l, unsigned int r) const
{
return mData(l, mCol) < mData(r,mCol);
}
};
template<typename T>
static std::vector<T> genIndexSequence( T N )
{
std::vector<T> vec(N);
for (unsigned int i=0; i < N; i++)
vec[i] = i;
return vec;
}
class ThresholdSplit
{
private:
IntegralImageType mThreshold;
bool mInvert;
unsigned int mColumn;
unsigned int mPoseIdx;
std::string mDescription;
public:
ThresholdSplit() {}
ThresholdSplit( unsigned int column, IntegralImageType threshold, bool invert, unsigned int poseIdx ) {
mThreshold = threshold;
mInvert = invert;
mColumn = column;
mPoseIdx = poseIdx;
}
unsigned int poseIdx() const { return mPoseIdx; }
void save( libconfig::Setting &s ) const
{
s.add("threshold", libconfig::Setting::TypeFloat) = mThreshold;
s.add("invert", libconfig::Setting::TypeBoolean) = mInvert;
s.add("column", libconfig::Setting::TypeInt) = (int)mColumn;
s.add("poseIdx", libconfig::Setting::TypeInt) = (int)mPoseIdx;
s.add("description", libconfig::Setting::TypeString) = mDescription;
}
void load( const libconfig::Setting &s )
{
mThreshold = s["threshold"];
mInvert = s["invert"];
mColumn = (int) s["column"];
mPoseIdx = (int) s["poseIdx"];
mDescription = (const char *) s["description"];
/*s.add("invert", libconfig::Setting::TypeBool) = mInvert;
s.add("column", libconfig::Setting::TypeInt) = mColumn;
s.add("poseIdx", libconfig::Setting::TypeInt) = mPoseIdx;
s.add("description", libconfig::Setting::TypeString) = mDescription;*/
}
IntegralImageType threshold() const { return mThreshold; }
bool invert() const { return mInvert; }
unsigned int column() const { return mColumn; }
void invertClassifier() { mInvert = !mInvert; }
void setInvert( bool yes ) { mInvert = yes; }
void setThreshold( IntegralImageType thr ) { mThreshold = thr; }
inline void setStringDescrption( const std::string &descr )
{
mDescription = descr;
}
inline const std::string &getStringDescription() const
{
return mDescription;
}
template<typename SampleIdxVector, typename MatrixType>
void exportFeat( const SampleIdxVector &sampleIdxs, const HistogramMeanThresholdData ¶ms, MatrixType &destMat, unsigned int col )
{
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (unsigned int i=0; i < sampleIdxs.size(); i++)
{
BoxPositionType box;
params.poseIndexedFeature( mPoseIdx, sampleIdxs[i], &box );
#if APPLY_PATCH_VARNORM
destMat.coeffRef( i, col ) = params.pixIntImages[mColumn]->centeredSumNormalized( box, params.svoxWindowMean[mColumn][sampleIdxs[i]], params.svoxWindowInvStd[mColumn][sampleIdxs[i]] );
#else
destMat.coeffRef( i, col ) = params.pixIntImages[mColumn]->centeredSum( box );
#endif
}
}
template<typename SampleIdxVector, typename PredType>
void classify( const SampleIdxVector &sampleIdxs, const HistogramMeanThresholdData ¶ms, std::vector<PredType> &prediction, const unsigned numThreads = 1 )
{
prediction.resize( sampleIdxs.size() );
classifyLowLevel<SampleIdxVector, PredType, 0>( sampleIdxs, params, prediction.data(), numThreads );
}
template<typename SampleIdxVector, int negativeValue>
void classify( const SampleIdxVector &sampleIdxs, const HistogramMeanThresholdData ¶ms, Eigen::ArrayXf &prediction, const unsigned numThreads = 1 )
{
prediction.resize( sampleIdxs.size() );
classifyLowLevel<SampleIdxVector, float, negativeValue>( sampleIdxs, params, prediction.data(), numThreads );
}
template<typename SampleIdxVector, typename PredType, int negativeValue>
void classifyLowLevel( const SampleIdxVector &sampleIdxs, const HistogramMeanThresholdData ¶ms, PredType *prediction, const unsigned numThreads = 1 )
{
if (mInvert == false)
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(numThreads)
#endif
for (unsigned int i=0; i < sampleIdxs.size(); i++)
{
BoxPositionType box;
params.poseIndexedFeature( mPoseIdx, sampleIdxs[i], &box );
#if APPLY_PATCH_VARNORM
if ( params.pixIntImages[mColumn]->centeredSumNormalized( box, params.svoxWindowMean[mColumn][sampleIdxs[i]], params.svoxWindowInvStd[mColumn][sampleIdxs[i]] ) >= mThreshold )
#else
if ( params.pixIntImages[mColumn]->centeredSum( box ) >= mThreshold )
#endif
prediction[i] = 1;
else
prediction[i] = negativeValue;
}
} else {
#ifdef _OPENMP
#pragma omp parallel for num_threads(numThreads)
#endif
for (unsigned int i=0; i < sampleIdxs.size(); i++)
{
BoxPositionType box;
params.poseIndexedFeature( mPoseIdx, sampleIdxs[i], &box );
#if APPLY_PATCH_VARNORM
if ( params.pixIntImages[mColumn]->centeredSumNormalized( box, params.svoxWindowMean[mColumn][sampleIdxs[i]], params.svoxWindowInvStd[mColumn][sampleIdxs[i]] ) < mThreshold ) {
#else
if ( params.pixIntImages[mColumn]->centeredSum( box ) < mThreshold ) {
#endif
prediction[i] = 1;
} else {
prediction[i] = negativeValue;
}
}
}
}
};
class ThresholdSplitSubtract
{
private:
IntegralImageType mThreshold;
bool mInvert;
unsigned int mColumn;
unsigned int mPoseIdxA, mPoseIdxB;
std::string mDescription;
public:
ThresholdSplitSubtract() {}
ThresholdSplitSubtract( unsigned int column, IntegralImageType threshold, bool invert, unsigned int poseIdxA, unsigned int poseIdxB ) {
mThreshold = threshold;
mInvert = invert;
mColumn = column;
mPoseIdxA = poseIdxA;
mPoseIdxB = poseIdxB;
}
inline void setStringDescrption( const std::string &descr )
{
mDescription = descr;
}
inline const std::string &getStringDescription() const
{
return mDescription;
}
IntegralImageType threshold() const { return mThreshold; }
bool invert() const { return mInvert; }
unsigned int column() const { return mColumn; }
template<typename SampleIdxVector, typename MatrixType>
void exportFeat( const SampleIdxVector &sampleIdxs, const HistogramMeanThresholdData ¶ms, MatrixType &destMat, unsigned int col )
{
for (unsigned int i=0; i < sampleIdxs.size(); i++)
{
BoxPositionType boxA, boxB;
params.poseIndexedFeature( mPoseIdxA, sampleIdxs[i], &boxA );
params.poseIndexedFeature( mPoseIdxB, sampleIdxs[i], &boxB );
destMat.coeffRef( i, col ) = params.pixIntImages[mColumn]->centeredSum( boxA ) - params.pixIntImages[mColumn]->centeredSum( boxB );
}
}
template<typename SampleIdxVector, typename PredType>
void classify( const SampleIdxVector &sampleIdxs, const HistogramMeanThresholdData ¶ms, std::vector<PredType> &prediction )
{
prediction.resize( sampleIdxs.size() );
if (mInvert == false)
{
for (unsigned int i=0; i < sampleIdxs.size(); i++)
{
BoxPositionType boxA, boxB;
params.poseIndexedFeature( mPoseIdxA, sampleIdxs[i], &boxA );
params.poseIndexedFeature( mPoseIdxB, sampleIdxs[i], &boxB );
if ( params.pixIntImages[mColumn]->centeredSum( boxA ) - params.pixIntImages[mColumn]->centeredSum( boxB ) >= mThreshold )
prediction[i] = 1;
else
prediction[i] = 0;
}
} else {
for (unsigned int i=0; i < sampleIdxs.size(); i++)
{
BoxPositionType boxA, boxB;
params.poseIndexedFeature( mPoseIdxA, sampleIdxs[i], &boxA );
params.poseIndexedFeature( mPoseIdxB, sampleIdxs[i], &boxB );
if ( params.pixIntImages[mColumn]->centeredSum( boxA ) - params.pixIntImages[mColumn]->centeredSum( boxB ) < mThreshold ) {
prediction[i] = 1;
} else {
prediction[i] = 0;
}
}
}
}
};
template<typename FeatureOperatorType>
AdaBoostErrorType computeError( const FeatureOperatorType &fOp,
IntegralImageType threshold, bool inverted )
{
AdaBoostErrorType err = 0;
if (inverted == false)
{
for (unsigned int i=0; i < fOp.count(); i++)
{
if ( fOp.value(i) >= threshold ) {
if ( fOp.label(i) == 0 )
err += fOp.weight(i);
} else {
if ( fOp.label(i) != 0 )
err += fOp.weight(i);
}
}
} else {
for (unsigned int i=0; i < fOp.count(); i++)
{
if ( fOp.value(i) < threshold ) {
if ( fOp.label(i) == 0 )
err += fOp.weight(i);
} else {
if ( fOp.label(i) != 0 )
err += fOp.weight(i);
}
}
}
return err;
}
// if forcePolarity = true, then it will use the polarity found in 'inv'
template<typename FeatureOperatorType, bool TForcePolarity>
inline AdaBoostErrorType findBestThreshold( const FeatureOperatorType &fOp,
IntegralImageType &retThr, bool &inv )
{
const unsigned int N = fOp.count();
std::vector<unsigned int> sortedIdx(N); //alloc
for (unsigned int i=0; i < N; i++)
sortedIdx[i] = i;
std::sort( sortedIdx.begin(), sortedIdx.end(),
SortFeature<FeatureOperatorType>( fOp ) );
// find out the error if we put threshold on zero
AdaBoostErrorType minErr = 1e6;
IntegralImageType bestThr = 0;
bool bestInv = false;
unsigned int bestIdx = 0;
// pre-compute errors with threshold on first element
IntegralImageType firstThr = fOp.value( sortedIdx[0] );
AdaBoostErrorType errInv = computeError( fOp, firstThr, true );
AdaBoostErrorType err = computeError( fOp, firstThr, false );
bestInv = errInv < err;
bestThr = firstThr;
if (TForcePolarity)
{
bestInv = inv;
}
if (bestInv)
minErr = errInv;
else
minErr = err;
#if 0
if (fOp.mBoxes[0].r == 0) {
qDebug("Val %d: %f", (int)fOp.mCol, fOp.value(12));
}
#endif
//qDebug("St: %f %f %f", err, errInv, firstThr);
std::vector<IntegralImageType> uniqueThresholds;
uniqueThresholds.push_back( firstThr );
for (unsigned int i=1; i < N; i++)
{
const unsigned int sIdxThis = sortedIdx[i];
const unsigned int sIdxPrev = sortedIdx[i-1];
IntegralImageType thr = fOp.value( sIdxThis );
IntegralImageType prevThr = fOp.value( sIdxPrev );
// not inv => changes if
#if 1
if ( fOp.label(sIdxPrev) == 1 ) {
err += fOp.weight(sIdxPrev);
errInv -= fOp.weight(sIdxPrev);
}
else if ( fOp.label(sIdxPrev) == 0 ) {
err -= fOp.weight(sIdxPrev);
errInv += fOp.weight(sIdxPrev);
}
#else
errInv = computeError( sampleIdxs, sampleClass, mat, column, weights, thr, true );
err = computeError( sampleIdxs, sampleClass, mat, column, weights, thr, false );
#endif
if ( (thr == prevThr) )
continue;
uniqueThresholds.push_back( thr );
if (!TForcePolarity)
{
// normal
if ( err < minErr ) {
bestThr = thr;
minErr = err;
bestIdx = uniqueThresholds.size() - 1;
bestInv = false;
}
if ( errInv < minErr ) {
bestThr = thr;
minErr = errInv;
bestIdx = uniqueThresholds.size() - 1;
bestInv = true;
}
}
else
{
// polarity forced
if (!inv)
{
if ( err < minErr ) {
bestThr = thr;
minErr = err;
bestIdx = uniqueThresholds.size() - 1;
bestInv = false;
}
}
else
{
if ( errInv < minErr ) {
bestThr = thr;
minErr = errInv;
bestIdx = uniqueThresholds.size() - 1;
bestInv = true;
}
}
}
}
if ( bestIdx == 0 )
retThr = uniqueThresholds[bestIdx];
else
retThr = ( uniqueThresholds[bestIdx] + uniqueThresholds[bestIdx-1] )/2;
inv = bestInv;
// compare errors
if (false)
{
AdaBoostErrorType goodErr = computeError( fOp, retThr, inv );
if (abs(minErr - goodErr) > 0.001)
qDebug("Err: %.2f -> %f / %f", abs(minErr - goodErr), minErr, goodErr);
//qDebug(" Thr: %f %f", bestThr, retThr );
}
#if 0
if ( column == 1 ) {
qDebug("thr: %f %d %d %d %f", thr, inv, bestIdx, uniqueThresholds.size(), minErr);
for (unsigned int i=0; i < uniqueThresholds.size(); i++)
qDebug("T %d: %f", i, uniqueThresholds[i]);
}
#endif
minErr = computeError( fOp, retThr, inv );
return minErr;
}
class HistogramMeanThreshold
{
public:
typedef HistogramMeanThresholdData ParamType;
typedef unsigned int SampleIdxType;
typedef std::vector<unsigned int> SampleClassVector;
typedef Eigen::ArrayXd WeightsType;
#if USE_DIFFERENCE_SPLIT
typedef ThresholdSplitSubtract SplitType;
#else
typedef ThresholdSplit SplitType;
#endif
private:
const ParamType &mParams;
public:
const ParamType & params() const {
return mParams;
}
// trick from http://cplusplus.co.il/2009/09/04/implementing-assignment-operator-using-copy-constructor/
HistogramMeanThreshold &operator= (const HistogramMeanThreshold &a)
{
if (this != &a)
{
this->HistogramMeanThreshold::~HistogramMeanThreshold();
new (this) HistogramMeanThreshold(a);
}
return *this;
}
HistogramMeanThreshold( ) : mParams( *((ParamType *)0) ) {}
HistogramMeanThreshold( const ParamType& param ) : mParams(param) {}
// returns error
// if prevSplit != null => works by refining the threshold, everything else is kept the same
IntegralImageType learn( const std::vector<SampleIdxType> &sampleIdxs, const std::vector<unsigned int> &sampleClass, const WeightsType &weights, SplitType &tSplit,
const ThresholdSplit *prevSplit = 0 )
{
typedef FeatureRawOperator<HistogramMeanThresholdData, WeightsType> RawOperatorType;
//typedef FeatureSubtractorOperator<HistogramMeanThresholdData, WeightsType> SubtractorOperatorType;
const bool refineThreshold = prevSplit != 0;
qDebug("Total number of pose Idxs: %d\n", (int)mParams.numPosIdx());
//const unsigned int N = sampleIdxs.size();
const unsigned int numII = mParams.pixIntImages.size();
AdaBoostErrorType minErr = 1e6;
unsigned int bestBin = 0;
unsigned bestPoseIdx = 0;
bool bestInvert = false;
IntegralImageType bestThr = 0;
#if USE_DIFFERENCE_SPLIT
unsigned int bestPoseIdxB = 0;
#endif
unsigned numExploredPoses = 0;
unsigned numExploredWeakLearners = 0;
//#warning learning 2k instead of 4k
const unsigned numTotalWeakLearnersToExplore = mParams.numWLToExplore;
const unsigned totalCombinations = numII * mParams.numPosIdx();
const double combinationDivisor = sqrt(totalCombinations / numTotalWeakLearnersToExplore);
unsigned numIIToExplore = numII;
unsigned numPosesToExplore = std::min( (unsigned) ceil( numTotalWeakLearnersToExplore / numII ), (unsigned) mParams.numPosIdx() );
std::vector<unsigned> poseIdxs( mParams.numPosIdx() );
for (unsigned i=0; i < poseIdxs.size(); i++)
poseIdxs[i] = i;
std::random_shuffle( poseIdxs.begin(), poseIdxs.end() );
unsigned int progressStep = numPosesToExplore / 200;