-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathModel.cpp
More file actions
923 lines (745 loc) · 26.2 KB
/
Model.cpp
File metadata and controls
923 lines (745 loc) · 26.2 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
//--------------------------------------------------------------------------------------------------
// Implementation of the papers "Exact Acceleration of Linear Object Detectors", 12th European
// Conference on Computer Vision, 2012 and "Deformable Part Models with Individual Part Scaling",
// 24th British Machine Vision Conference, 2013.
//
// Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/>
// Written by Charles Dubout <charles.dubout@idiap.ch>
//
// This file is part of FFLDv2 (the Fast Fourier Linear Detector version 2)
//
// FFLDv2 is free software: you can redistribute it and/or modify it under the terms of the GNU
// Affero General Public License version 3 as published by the Free Software Foundation.
//
// FFLDv2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
// General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with FFLDv2. If
// not, see <http://www.gnu.org/licenses/>.
//--------------------------------------------------------------------------------------------------
#include "Model.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <limits>
#include <iostream>
using namespace Eigen;
using namespace FFLD;
using namespace std;
Model::Model() : parts_(1), bias_(0.0)
{
parts_[0].offset.setZero();
parts_[0].deformation.setZero();
}
Model::Model(pair<int, int> rootSize, int nbParts, pair<int, int> partSize) : parts_(1), bias_(0.0)
{
parts_[0].offset.setZero();
parts_[0].deformation.setZero();
// Create an empty model if any of the given parameters is invalid
if ((rootSize.first <= 0) || (rootSize.second <= 0) || (nbParts < 0) ||
(nbParts && ((partSize.first <= 0) || (partSize.second <= 0)))) {
cerr << "Attempting to create an empty model" << endl;
return;
}
parts_.resize(nbParts + 1);
parts_[0].filter = HOGPyramid::Level::Constant(rootSize.first, rootSize.second,
HOGPyramid::Cell::Zero());
for (int i = 0; i < nbParts; ++i) {
parts_[i + 1].filter = HOGPyramid::Level::Constant(partSize.first, partSize.second,
HOGPyramid::Cell::Zero());
parts_[i + 1].offset.setZero();
parts_[i + 1].deformation.setZero();
}
}
Model::Model(const vector<Part> & parts, double bias) : parts_(parts), bias_(bias)
{
// Create an empty model if the parts are empty
if (parts.empty()) {
parts_.resize(1);
parts_[0].offset.setZero();
parts_[0].deformation.setZero();
}
}
bool Model::empty() const
{
return !parts_[0].filter.size() && (parts_.size() == 1);
}
const vector<Model::Part> & Model::parts() const
{
return parts_;
}
vector<Model::Part> & Model::parts()
{
return parts_;
}
double Model::bias() const
{
return bias_;
}
double & Model::bias()
{
return bias_;
}
pair<int, int> Model::rootSize() const
{
return pair<int, int>(static_cast<int>(parts_[0].filter.rows()),
static_cast<int>(parts_[0].filter.cols()));
}
pair<int, int> Model::partSize() const
{
if (parts_.size() > 1)
return pair<int, int>(static_cast<int>(parts_[1].filter.rows()),
static_cast<int>(parts_[1].filter.cols()));
else
return pair<int, int>(0, 0);
}
void Model::initializeParts(int nbParts, pair<int, int> partSize)
{
// The model stay unmodified if any of the parameter is invalid
if (empty() || (nbParts <= 0) || (partSize.first <= 0) || (partSize.second <= 0)) {
cerr << "Attempting to initialize parts in an empty model" << endl;
return;
}
// Upsample the root filter by a factor 2 using bicubic interpolation
const HOGPyramid::Level & root = parts_[0].filter;
HOGPyramid::Level root2x = HOGPyramid::Level::Constant(2 * root.rows(), 2 * root.cols(),
HOGPyramid::Cell::Zero());
// Bicubic interpolation matrix for x = y = 0.25
const double bicubic[4][4] =
{
{ 0.004943847656,-0.060974121094,-0.015930175781, 0.001647949219},
{-0.060974121094, 0.752014160156, 0.196472167969,-0.020324707031},
{-0.015930175781, 0.196472167969, 0.051330566406,-0.005310058594},
{ 0.001647949219,-0.020324707031,-0.005310058594, 0.000549316406}
};
for (int y = 0; y < root.rows(); ++y) {
for (int x = 0; x < root.cols(); ++x) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
const int y2 = min(max(y + i - 2, 0), static_cast<int>(root.rows()) - 1);
const int y1 = min(max(y + i - 1, 0), static_cast<int>(root.rows()) - 1);
const int x2 = min(max(x + j - 2, 0), static_cast<int>(root.cols()) - 1);
const int x1 = min(max(x + j - 1, 0), static_cast<int>(root.cols()) - 1);
root2x(y * 2 , x * 2 ) += bicubic[3 - i][3 - j] * root(y2, x2);
root2x(y * 2 , x * 2 + 1) += bicubic[3 - i][ j] * root(y2, x1);
root2x(y * 2 + 1, x * 2 ) += bicubic[ i][3 - j] * root(y1, x2);
root2x(y * 2 + 1, x * 2 + 1) += bicubic[ i][ j] * root(y1, x1);
}
}
}
}
// Compute the energy of each cell
HOGPyramid::Matrix energy(root2x.rows(), root2x.cols());
for (int y = 0; y < root2x.rows(); ++y) {
for (int x = 0; x < root2x.cols(); ++x) {
root2x(y, x).cwiseMax(0);
energy(y, x) = 0;
for (int i = 0; i < HOGPyramid::NbFeatures; ++i)
energy(y, x) += root2x(y, x)(i) * root2x(y, x)(i);
}
}
// Assign each part greedily to the region of maximum energy
parts_.resize(nbParts + 1);
for (int i = 0; i < nbParts; ++i) {
double maxEnergy = 0.0;
int argX = 0;
int argY = 0;
for (int y = 0; y <= energy.rows() - partSize.first; ++y) {
for (int x = 0; x <= energy.cols() - partSize.second; ++x) {
const double e = energy.block(y, x, partSize.first, partSize.second).sum();
if (e > maxEnergy) {
maxEnergy = e;
argX = x;
argY = y;
}
}
}
// Initialize the part
parts_[i + 1].filter = root2x.block(argY, argX, partSize.first, partSize.second);
parts_[i + 1].offset(0) = argX;
parts_[i + 1].offset(1) = argY;
parts_[i + 1].offset(2) = 0;
// Set the energy of the part to zero
energy.block(argY, argX, partSize.first, partSize.second).setZero();
}
// Retry 10 times from randomized starting points
double bestCover = 0.0;
vector<Part> best(parts_); // The best so far is the current one
for (int i = 0; i < 10; ++i) {
vector<Part> tmp(parts_); // Try from the current one
// Remove a part at random and look for the best place to put it
for (int j = 0; j < 100 * nbParts; ++j) {
// Recompute the energy
for (int y = 0; y < root2x.rows(); ++y) {
for (int x = 0; x < root2x.cols(); ++x) {
energy(y, x) = 0;
for (int i = 0; i < HOGPyramid::NbFeatures; ++i)
energy(y, x) += root2x(y, x)(i) * root2x(y, x)(i);
}
}
// Select a part at random
const int part = rand() % nbParts;
// Zero out the energy covered by the other parts
for (int k = 0; k < nbParts; ++k)
if (k != part)
energy.block(tmp[k + 1].offset(1), tmp[k + 1].offset(0), partSize.first,
partSize.second).setZero();
// Find the region of maximum energy
double maxEnergy = 0.0;
int argX = 0;
int argY = 0;
for (int y = 0; y <= energy.rows() - partSize.first; ++y) {
for (int x = 0; x <= energy.cols() - partSize.second; ++x) {
const double e = energy.block(y, x, partSize.first, partSize.second).sum();
if (e > maxEnergy) {
maxEnergy = e;
argX = x;
argY = y;
}
}
}
// Initialize the part
tmp[part + 1].filter = root2x.block(argY, argX, partSize.first, partSize.second);
tmp[part + 1].offset(0) = argX;
tmp[part + 1].offset(1) = argY;
tmp[part + 1].offset(2) = 0;
}
// Compute the energy covered by this part arrangement
double cover = 0.0;
// Recompute the energy
for (int y = 0; y < root2x.rows(); ++y) {
for (int x = 0; x < root2x.cols(); ++x) {
energy(y, x) = 0;
for (int i = 0; i < HOGPyramid::NbFeatures; ++i)
energy(y, x) += root2x(y, x)(i) * root2x(y, x)(i);
}
}
for (int j = 0; j < nbParts; ++j) {
// Add the energy of the part
cover += energy.block(tmp[j + 1].offset(1), tmp[j + 1].offset(0), partSize.first,
partSize.second).sum();
// Set the energy of the part to zero
energy.block(tmp[j + 1].offset(1), tmp[j + 1].offset(0), partSize.first,
partSize.second).setZero();
}
if (cover > bestCover) {
bestCover = cover;
best = tmp;
}
}
parts_.swap(best);
// Initialize the deformations
for (int i = 0; i < nbParts; ++i)
parts_[i + 1].deformation << -0.01, 0.0, -0.01, 0.0, -0.01, 0.0;
}
void Model::initializeSample(const HOGPyramid & pyramid, int x, int y, int z, Model & sample,
const vector<vector<Positions> > * positions) const
{
// All the constants relative to the model and the pyramid
const int nbFilters = static_cast<int>(parts_.size());
const int nbParts = nbFilters - 1;
const int padx = pyramid.padx();
const int pady = pyramid.pady();
const int interval = pyramid.interval();
const int nbLevels = static_cast<int>(pyramid.levels().size());
// Invalid parameters
if (empty() || (x < 0) || (y < 0) || (z < 0) || (z >= nbLevels) ||
(x + rootSize().second > pyramid.levels()[z].cols()) ||
(y + rootSize().first > pyramid.levels()[z].rows()) ||
(nbParts && (!positions || (positions->size() != nbParts)))) {
sample = Model();
cerr << "Attempting to initialize an empty sample" << endl;
return;
}
// Resize the sample to have the same number of filters as the model
sample.parts_.resize(nbFilters);
// Extract the root filter
sample.parts_[0].filter = pyramid.levels()[z].block(y, x, rootSize().first, rootSize().second);
sample.parts_[0].offset.setZero();
sample.parts_[0].deformation.setZero();
for (int i = 0; i < nbParts; ++i) {
// Position of the part
if ((z >= (*positions)[i].size()) || (x >= (*positions)[i][z].cols()) ||
(y >= (*positions)[i][z].rows())) {
sample = Model();
cerr << "Attempting to initialize an empty sample" << endl;
return;
}
const Position position = (*positions)[i][z](y, x);
// Level of the part
if ((position(2) < 0) || (position(2) >= nbLevels)) {
sample = Model();
cerr << "Attempting to initialize an empty sample" << endl;
return;
}
const HOGPyramid::Level & level = pyramid.levels()[position(2)];
if ((position(0) < 0) || (position(1) < 0) ||
(position(0) + partSize().second > level.cols()) ||
(position(1) + partSize().first > level.rows())) {
sample = Model();
cerr << "Attempting to initialize an empty sample" << endl;
return;
}
// Extract the part filter
sample.parts_[i + 1].filter = level.block(position(1), position(0), partSize().first,
partSize().second);
// Set the part offset to the position
sample.parts_[i + 1].offset = position;
// Compute the deformation gradient at the level of the part
const double scale = pow(2.0, static_cast<double>(z - position(2)) / interval);
const double xr = (x + (parts_[i + 1].offset(0) + partSize().second * 0.5) * 0.5 - padx) *
scale + padx - partSize().second * 0.5;
const double yr = (y + (parts_[i + 1].offset(1) + partSize().first * 0.5) * 0.5 - pady) *
scale + pady - partSize().first * 0.5;
const double dx = xr - position(0);
const double dy = yr - position(1);
const int dz = z - interval - position(2);
sample.parts_[i + 1].deformation(0) = dx * dx;
sample.parts_[i + 1].deformation(1) = dx;
sample.parts_[i + 1].deformation(2) = dy * dy;
sample.parts_[i + 1].deformation(3) = dy;
sample.parts_[i + 1].deformation(4) = dz * dz;
sample.parts_[i + 1].deformation(5) = dz;
}
sample.bias_ = 1.0;
}
void Model::convolve(const HOGPyramid & pyramid, vector<HOGPyramid::Matrix> & scores,
vector<vector<Positions> > * positions,
vector<vector<HOGPyramid::Matrix> > * convolutions) const
{
// Invalid parameters
if (empty() || pyramid.empty() ||
#ifdef FFLD_MODEL_3D
!positions ||
#endif
(convolutions && (convolutions->size() != parts_.size()))) {
scores.clear();
if (positions)
positions->clear();
return;
}
// All the constants relative to the model and the pyramid
const int nbFilters = static_cast<int>(parts_.size());
const int nbParts = nbFilters - 1;
const int padx = pyramid.padx();
const int pady = pyramid.pady();
const int interval = pyramid.interval();
const int nbLevels = static_cast<int>(pyramid.levels().size());
// Convolve the pyramid with all the filters
vector<vector<HOGPyramid::Matrix> > tmpConvolutions;
if (convolutions) {
for (int i = 0; i < nbFilters; ++i) {
if ((*convolutions)[i].size() != nbLevels) {
scores.clear();
if (positions)
positions->clear();
return;
}
}
}
else {
tmpConvolutions.resize(nbFilters);
#pragma omp parallel for
for (int i = 0; i < nbFilters; ++i)
pyramid.convolve(parts_[i].filter, tmpConvolutions[i]);
convolutions = &tmpConvolutions;
}
// Resize the positions
if (positions) {
positions->resize(nbParts);
for (int i = 0; i < nbParts; ++i)
(*positions)[i].resize(nbLevels);
}
// Temporary data needed by the distance transforms
HOGPyramid::Matrix tmp;
#ifndef FFLD_MODEL_3D
// For each root level in reverse order
for (int z = nbLevels - 1; z >= interval; --z) {
// For each part
for (int i = 0; i < nbParts; ++i) {
// Transform the part one octave below
DT2D((*convolutions)[i + 1][z - interval], parts_[i + 1], tmp,
positions ? &(*positions)[i][z - interval] : 0);
if (positions)
(*positions)[i][z] = Positions::Constant((*convolutions)[0][z].rows(),
(*convolutions)[0][z].cols(),
Position::Zero());
// Add the distance transforms of the part one octave below
for (int y = 0; y < (*convolutions)[0][z].rows(); ++y) {
for (int x = 0; x < (*convolutions)[0][z].cols(); ++x) {
const int xr = 2 * x - padx + parts_[i + 1].offset(0);
const int yr = 2 * y - pady + parts_[i + 1].offset(1);
if ((xr >= 0) && (yr >= 0) &&
(xr < (*convolutions)[i + 1][z - interval].cols()) &&
(yr < (*convolutions)[i + 1][z - interval].rows())) {
(*convolutions)[0][z](y, x) += (*convolutions)[i + 1][z - interval](yr, xr);
if (positions)
(*positions)[i][z](y, x) << (*positions)[i][z - interval](yr, xr)(0),
(*positions)[i][z - interval](yr, xr)(1),
z - interval;
}
else {
(*convolutions)[0][z](y, x) =
-numeric_limits<HOGPyramid::Scalar>::infinity();
}
}
}
if (positions)
(*positions)[i][z - interval] = Positions();
}
}
scores.swap((*convolutions)[0]);
for (int i = 0; i < interval; ++i) {
scores[i] = HOGPyramid::Matrix();
if (positions)
for (int j = 0; j < nbParts; ++j)
(*positions)[j][i] = Positions();
}
// Add the bias if necessary
if (bias_) {
#pragma omp parallel for
for (int i = interval; i < nbLevels; ++i)
scores[i].array() += bias_;
}
#else
// Range of scales to consider
const int interval2 = (interval + 1) / 2;
// Precompute all the necessary distance transforms
for (int i = 0; i < nbLevels - interval + interval2; ++i) {
for (int j = 0; j < nbParts; ++j) {
HOGPyramid::Matrix copy = (*convolutions)[j + 1][i];
DT2D(copy, parts_[j + 1], tmp, positions ? &(*positions)[j][i] : 0);
}
}
// Precompute the scale ratios
vector<double> scales(2 * interval);
for (int i = 0; i < 2 * interval; ++i)
scales[i] = pow(2.0, static_cast<double>(i) / interval);
// Half part size
const double hpx = 0.5 * partSize().second;
const double hpy = 0.5 * partSize().first;
// Resize the scores
scores.resize(nbLevels);
// For each root level in reverse order
for (int i = nbLevels - 1; i >= interval - interval2; --i) {
// Set the scores to those of the root + bias
scores[i].swap((*convolutions)[0][i]);
for (int j = 0; j < nbParts; ++j)
(*positions)[j][i] = Model::Positions::Constant(scores[i].rows(), scores[i].cols(),
Model::Position::Zero());
// Add the scores of each part
for (int j = 0; j < nbParts; ++j) {
const Deformation & d = parts_[j + 1].deformation;
for (int y = 0; y < scores[i].rows(); ++y) {
for (int x = 0; x < scores[i].cols(); ++x) {
// Score of the best part position across scales
HOGPyramid::Scalar best = -numeric_limits<HOGPyramid::Scalar>::infinity();
// Coordinates of the center of the part at the root level
const double cxr = x - padx + 0.5 * (parts_[j + 1].offset(0) + hpx);
const double cyr = y - pady + 0.5 * (parts_[j + 1].offset(1) + hpy);
for (int zp = max(i - interval - interval2, 0);
zp <= i - interval + interval2; ++zp) {
const double xr = scales[i - zp] * cxr + padx - hpx;
const double yr = scales[i - zp] * cyr + pady - hpy;
const int ixr = xr + 0.5;
const int iyr = yr + 0.5;
if ((ixr >= 0) && (iyr >= 0) && (ixr < (*convolutions)[j + 1][zp].cols()) &&
(iyr < (*convolutions)[j + 1][zp].rows())) {
const int xp = (*positions)[j][zp](iyr, ixr)(0);
const int yp = (*positions)[j][zp](iyr, ixr)(1);
const double dx = xr - xp;
const double dy = yr - yp;
const double dz = i - interval - zp;
const double cost = (d(0) * dx + d(1)) * dx +
(d(2) * dy + d(3)) * dy +
(d(4) * dz + d(5)) * dz;
if ((*convolutions)[j + 1][zp](yp, xp) + cost > best) {
best = (*convolutions)[j + 1][zp](yp, xp) + cost;
(*positions)[j][i](y, x) << xp, yp, zp;
}
}
}
scores[i](y, x) += best;
}
}
}
}
for (int i = 0; i < interval - interval2; ++i)
for (int j = 0; j < nbParts; ++j)
(*positions)[j][i] = Positions();
// Add the bias if necessary
if (bias_) {
#pragma omp parallel for
for (int i = interval - interval2; i < nbLevels; ++i)
scores[i].array() += bias_;
}
#endif
}
double Model::dot(const Model & sample) const
{
double d = bias_ * sample.bias_;
if (parts_.size() != sample.parts_.size())
return numeric_limits<double>::quiet_NaN();
for (int i = 0; i < parts_.size(); ++i) {
if ((parts_[i].filter.rows() != sample.parts_[i].filter.rows()) ||
(parts_[i].filter.cols() != sample.parts_[i].filter.cols()))
return numeric_limits<double>::quiet_NaN();
for (int y = 0; y < parts_[i].filter.rows(); ++y)
d += HOGPyramid::Map(parts_[i].filter).row(y).dot(
HOGPyramid::Map(sample.parts_[i].filter).row(y));
if (i)
d += parts_[i].deformation.dot(sample.parts_[i].deformation);
}
return d;
}
double Model::norm() const
{
double n = 0.0;
for (int i = 0; i < parts_.size(); ++i) {
n += HOGPyramid::Map(parts_[i].filter).squaredNorm();
if (i)
n += 10.0 * parts_[i].deformation.squaredNorm();
}
return sqrt(n);
}
Model & Model::operator+=(const Model & sample)
{
if (parts_.size() != sample.parts_.size())
return *this;
Model copy(*this);
for (int i = 0; i < parts_.size(); ++i) {
if ((parts_[i].filter.rows() != sample.parts_[i].filter.rows()) ||
(parts_[i].filter.cols() != sample.parts_[i].filter.cols())) {
*this = copy; // Restore the copy
return *this;
}
parts_[i].filter += sample.parts_[i].filter;
parts_[i].deformation += sample.parts_[i].deformation;
}
bias_ += sample.bias_;
return *this;
}
Model & Model::operator-=(const Model & sample)
{
if (parts_.size() != sample.parts_.size())
return *this;
Model copy(*this);
for (int i = 0; i < parts_.size(); ++i) {
if ((parts_[i].filter.rows() != sample.parts_[i].filter.rows()) ||
(parts_[i].filter.cols() != sample.parts_[i].filter.cols())) {
*this = copy; // Restore the copy
return *this;
}
parts_[i].filter -= sample.parts_[i].filter;
parts_[i].deformation -= sample.parts_[i].deformation;
}
bias_ -= sample.bias_;
return *this;
}
Model & Model::operator*=(double a)
{
for (int i = 0; i < parts_.size(); ++i) {
HOGPyramid::Map(parts_[i].filter) *= a;
parts_[i].deformation *= a;
}
bias_ *= a;
return *this;
}
Model Model::flip() const
{
Model model;
if (!empty()) {
model.parts_.resize(parts_.size());
// Flip the root
model.parts_[0].filter = HOGPyramid::Flip(parts_[0].filter);
model.parts_[0].offset = parts_[0].offset;
model.parts_[0].deformation = parts_[0].deformation;
// Flip the parts
for (int i = 1; i < parts_.size(); ++i) {
model.parts_[i].filter = HOGPyramid::Flip(parts_[i].filter);
model.parts_[i].offset(0) = 2 * static_cast<int>(parts_[0].filter.cols()) -
static_cast<int>(parts_[i].filter.cols()) -
parts_[i].offset(0);
model.parts_[i].offset(1) = parts_[i].offset(1);
model.parts_[i].offset(2) = parts_[i].offset(2);
model.parts_[i].deformation = parts_[i].deformation;
model.parts_[i].deformation(1) = -model.parts_[i].deformation(1);
}
}
model.bias_ = bias_;
return model;
}
template <typename Scalar>
static void dt1d(const Scalar * x, int n, Scalar a, Scalar b, Scalar * z, int * v, Scalar * y,
int * m, const Scalar * t, int incx, int incy, int incm)
{
assert(x && (y || m));
assert(n > 0);
assert(a < 0);
assert(z && v);
assert(t);
assert(incx && incy && (m ? incm : true));
z[0] =-numeric_limits<Scalar>::infinity();
z[1] = numeric_limits<Scalar>::infinity();
v[0] = 0;
// Use a lookup table to replace the division by (a * (i - v[k]))
int k = 0;
Scalar xvk = x[0];
for (int i = 1; i < n;) {
const Scalar s = (x[i * incx] - xvk) * t[i - v[k]] + (i + v[k]) - b / a;
if (s <= z[k]) {
--k;
xvk = x[v[k] * incx];
}
else {
++k;
v[k] = i;
z[k] = s;
xvk = x[i * incx];
++i;
}
}
z[k + 1] = numeric_limits<Scalar>::infinity();
if (y && m) {
for (int i = 0, k = 0; i < n; ++i) {
while (z[k + 1] < 2 * i)
++k;
y[i * incy] = x[v[k] * incx] + (a * (i - v[k]) + b) * (i - v[k]);
m[i * incm] = v[k];
}
}
else if (y) {
for (int i = 0, k = 0; i < n; ++i) {
while (z[k + 1] < 2 * i)
++k;
y[i * incy] = x[v[k] * incx] + (a * (i - v[k]) + b) * (i - v[k]);
}
}
else {
for (int i = 0, k = 0; i < n; ++i) {
while (z[k + 1] < 2 * i)
++k;
m[i * incm] = v[k];
}
}
}
void Model::DT2D(HOGPyramid::Matrix & matrix, const Part & part, HOGPyramid::Matrix & tmp,
Positions * positions)
{
// Nothing to do if the matrix is empty
if (!matrix.size())
return;
const int rows = static_cast<int>(matrix.rows());
const int cols = static_cast<int>(matrix.cols());
if (positions)
positions->resize(rows, cols);
tmp.resize(rows, cols);
// Temporary vectors
vector<HOGPyramid::Scalar> z(max(rows, cols) + 1);
vector<int> v(max(rows, cols) + 1);
vector<HOGPyramid::Scalar> t(max(rows, cols));
t[0] = numeric_limits<HOGPyramid::Scalar>::infinity();
for (int x = 1; x < cols; ++x)
t[x] = 1 / (part.deformation(0) * x);
// Filter the rows in tmp
for (int y = 0; y < rows; ++y)
dt1d<HOGPyramid::Scalar>(matrix.row(y).data(), cols, part.deformation(0),
part.deformation(1), &z[0], &v[0], tmp.row(y).data(),
positions ? positions->row(y).data()->data() : 0, &t[0], 1, 1, 3);
for (int y = 1; y < rows; ++y)
t[y] = 1 / (part.deformation(2) * y);
// Filter the columns back to the original matrix
for (int x = 0; x < cols; ++x)
dt1d<HOGPyramid::Scalar>(tmp.data() + x, rows, part.deformation(2), part.deformation(3),
&z[0], &v[0],
#ifndef FFLD_MODEL_3D
matrix.data() + x,
#else
0,
#endif
positions ? ((positions->data() + x)->data() + 1) : 0, &t[0], cols,
cols, 3 * cols);
// Re-index the best x positions now that the best y changed
if (positions) {
for (int y = 0; y < rows; ++y)
for (int x = 0; x < cols; ++x)
tmp(y, x) = (*positions)(y, x)(0);
for (int y = 0; y < rows; ++y)
for (int x = 0; x < cols; ++x)
(*positions)(y, x)(0) = tmp((*positions)(y, x)(1), x);
}
}
ostream & FFLD::operator<<(ostream & os, const Model & model)
{
// Save the number of parts and the bias
os << model.parts().size() << ' ' << model.bias() << endl;
// Save the parts themselves
for (int i = 0; i < model.parts().size(); ++i) {
os << model.parts()[i].filter.rows() << ' ' << model.parts()[i].filter.cols() << ' '
<< HOGPyramid::NbFeatures << ' ' << model.parts()[i].offset(0) << ' '
<< model.parts()[i].offset(1) << ' ' << model.parts()[i].offset(2) << ' '
<< model.parts()[i].deformation(0) << ' ' << model.parts()[i].deformation(1) << ' '
<< model.parts()[i].deformation(2) << ' ' << model.parts()[i].deformation(3) << ' '
<< model.parts()[i].deformation(4) << ' ' << model.parts()[i].deformation(5)
<< endl;
for (int y = 0; y < model.parts()[i].filter.rows(); ++y) {
os << model.parts()[i].filter(y, 0)(0);
for (int j = 1; j < HOGPyramid::NbFeatures; ++j)
os << ' ' << model.parts()[i].filter(y, 0)(j);
for (int x = 1; x < model.parts()[i].filter.cols(); ++x)
for (int j = 0; j < HOGPyramid::NbFeatures; ++j)
os << ' ' << model.parts()[i].filter(y, x)(j);
os << endl;
}
}
return os;
}
istream & FFLD::operator>>(istream & is, Model & model)
{
int nbParts;
double bias;
is >> nbParts >> bias;
if (!is) {
model = Model();
return is;
}
vector<Model::Part> parts(nbParts);
for (int i = 0; i < nbParts; ++i) {
int rows, cols, nbFeatures;
is >> rows >> cols >> nbFeatures >> parts[i].offset(0) >> parts[i].offset(1)
>> parts[i].offset(2) >> parts[i].deformation(0) >> parts[i].deformation(1)
>> parts[i].deformation(2) >> parts[i].deformation(3) >> parts[i].deformation(4)
>> parts[i].deformation(5);
if (!is || (nbFeatures > HOGPyramid::NbFeatures)) {
model = Model();
return is;
}
// Always set the offset and deformation of the root to zero
if (!i) {
parts[0].offset.setZero();
parts[0].deformation.setZero();
}
// Always set the z offset of a part to zero
else {
parts[i].offset(2) = 0;
}
parts[i].filter = HOGPyramid::Level::Constant(rows, cols, HOGPyramid::Cell::Zero());
for (int y = 0; y < rows; ++y) {
for (int x = 0; x < cols; ++x) {
for (int j = 0; j < nbFeatures; ++j)
is >> parts[i].filter(y, x)(j);
// Always put the truncation feature at the end
if (nbFeatures < HOGPyramid::NbFeatures)
swap(parts[i].filter(y, x)(nbFeatures - 1),
parts[i].filter(y, x)(HOGPyramid::NbFeatures - 1));
}
}
if (!is) {
model = Model();
return is;
}
}
model = Model(parts, bias);
return is;
}