-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracker.cpp
1232 lines (1013 loc) · 35.5 KB
/
tracker.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 "tracker.h"
#include "condensation/condensation.h"
#include "condensation/data_types.h"
#include "condensation/model_parameters.h"
#include "spatiotemporaldef.h"
#include "aralclustering.h"
#include <QtGlobal>
#include <QElapsedTimer>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iostream>
#include <opencv2/core/version.hpp>
#include <QDebug>
void plot(cv::Mat& img, std::vector<cv::Point3f>& points, cv::Mat& labels)
{
int total = points.size();
if (total < 1)
return;
static cv::Scalar colors[] = {
cv::Scalar(255, 0, 0), cv::Scalar(0, 255, 0), cv::Scalar(0, 0, 255),
cv::Scalar(255, 255, 0), cv::Scalar(255, 0, 255), cv::Scalar(0, 255, 255)
};
int *labels_ptr = labels.ptr<int>(0);
for (int i = 0; i < total; i++)
{
cv::Point2f p(points.at(i).x, points.at(i).y);
cv::circle(img, p, 2, colors[labels_ptr[i]], 2);
}
}
/**
* Create a degree matrix out from the given adjacency matrix
**/
cv::Mat degreeMatrix(cv::Mat& adjacency)
{
int cols = adjacency.cols;
cv::Mat degree(1, cols, CV_32FC1);
for (int col = 0; col < cols; col++)
degree.at<float>(0, col) = cv::sum(adjacency.col( col ))[0];
return degree;
}
/* The following are some utility routines. */
/* This is the worst random number routine in the known universe, but
I use it for portability. Feel free to replace it. */
double uniform_random(void)
{
return (double) rand() / (double) RAND_MAX;
}
/* This Gaussian routine is stolen from Numerical Recipes and is their
copyright. */
double gaussian_random(void)
{
static int next_gaussian = 0;
static double saved_gaussian_value;
double fac, rsq, v1, v2;
if (next_gaussian == 0) {
do {
v1 = 2.0*uniform_random()-1.0;
v2 = 2.0*uniform_random()-1.0;
rsq = v1*v1+v2*v2;
} while (rsq >= 1.0 || rsq == 0.0);
fac = sqrt(-2.0*log(rsq)/rsq);
saved_gaussian_value=v1*fac;
next_gaussian=1;
return v2*fac;
} else {
next_gaussian=0;
return saved_gaussian_value;
}
}
double evaluate_gaussian(double val, double sigma)
{
/* This private definition is used for portability */
static const double Condense_PI = 3.14159265358979323846;
return exp(-0.5 * (val*val / (sigma*sigma)));
return 1.0/(sqrt(2.0*Condense_PI) * sigma) *
exp(-0.5 * (val*val / (sigma*sigma)));
}
/* The process model for a first-order auto-regressive process is:
x_{t+1} - mean = (x_t - mean)*scaling + sigma*w_t
where w_t is unit iid Gaussian noise. gaussian_random can be found
in utility.c */
QPointF iterate_first_order_arp(QPointF previous, ProcessModel process)
{
double val_x = process.sigma * gaussian_random();
double val_y = process.sigma * gaussian_random();
return QPointF(process.mean, process.mean)
+ (previous - QPointF(process.mean, process.mean)) * process.scaling
+ QPointF(val_x, val_y);
}
/* All of the global information is packaged into the following two
structures. `global' contains information which is constant over a
run of the algorithm and `data' contains all of the current state
at a given iteration. */
GlobalData global;
IterationData data;
Tracker::Tracker(QObject *parent) :
QObject(parent)
{
m_initialized = false;
m_frameWidth = 0;
m_frameHeight = 0;
m_initX = 0.0f; // start x position
m_initY = 0.0f; // start y position
m_initWidth = 0;
m_initHeight = 0;
m_isLost = false;
m_sectionClusteringResult.clear();
m_clusteringAlgorithm = Tracker::SpectralClustering;
m_estimatedTargetAmount = 0;
}
void Tracker::setFrameSize(int width, int height)
{
m_frameWidth = width;
m_frameHeight = height;
if (!m_initialized)
initialise();
}
void Tracker::setInitialState(double x, double y, int width, int height)
{
m_initX = x;
m_initY = y;
m_initWidth = width;
m_initHeight = height;
}
void Tracker::propagate(ViolaJonesClassifier::VJDetection obs)
{
if (!m_initialized)
initialise();
m_spatioTemporalDetections.append(obs);
int totalFrames = m_spatioTemporalDetections.length();
int sectionSize = 15;
int overlapingSize = 5;
int sectionCount = (totalFrames - overlapingSize) / (sectionSize - overlapingSize);
sectionCount = std::max(0, sectionCount);
for (int i = 0; i < sectionCount; i++)
{
if (i < m_sectionClusteringResult.length())
continue;
int startFrame = (sectionSize - overlapingSize) * i;
int endFrame = startFrame + sectionSize - 1;
runClusteringModelSelection(startFrame, endFrame);
int estimatedCount = getEstimatedTargetAmount(); // TODO: remove
m_sectionClusteringResult.append(estimatedCount); // TODO: remove
}
// runClusteringModelSelection(0, m_spatioTemporalDetections.length() - 1);
// runTrajectoryCounting();
condensation_obtain_observations(obs); /* Go make necessary measurements */
condensation_predict_new_bases(); /* Push previous state through process model */
condensation_calculate_base_weights(); /* Apply Bayesian measurement weighting */
condensation_update_after_iterating(); /* Tidy up, display output, etc. */
}
QList<Tracker::Particle> Tracker::getParticles()
{
QList<Particle> particles;
for (int i = 0; i < global.nsamples; i++)
{
Particle p;
p.pos = data.old_positions[i];
p.weight = data.sample_weights[i];
particles.append(p);
}
return particles;
}
QList<Tracker::Particle> Tracker::getDetections()
{
QList<Particle> particles;
for (int i = 0; i < data.meas.observed.length(); i++)
{
Particle p;
p.pos = data.meas.observed[i];
p.weight = 1;
particles.append(p);
}
return particles;
}
QList<STCluster> Tracker::getSTClusters()
{
return m_clusters;
}
QList<STLine> Tracker::getAllLineSegments()
{
return m_lineSegments;
}
QList<STPoint> Tracker::getAllSTPoints()
{
QList<STPoint> stPointList;
int startFrame = 0;
int endFrame = m_spatioTemporalDetections.length() - 1;
std::vector<cv::Point3f> points = st_getPoints(startFrame, endFrame);
int pointsCount = (int)points.size();
for (int i = 0; i < pointsCount; i++)
{
cv::Point3f point = points.at(i);
STPoint stPoint;
stPoint.x = point.x;
stPoint.y = point.y;
stPoint.t = point.z;
stPointList.append(stPoint);
}
return stPointList;
}
QList<STPoint> Tracker::getFilteredSTPoints()
{
return m_filteredPoints;
}
QList<STCone> Tracker::getSTCones()
{
return m_cones;
}
QList<STPoint> Tracker::getManualLabelings()
{
return m_manualLabelings;
}
QList< QList<QColor> > Tracker::getColorLabels()
{
return m_colorLabels;
}
QList<Tracker::Trajectory> Tracker::getTrajectories()
{
return m_trajectories;
}
cv::Mat Tracker::getDetectionConfidenceMap()
{
return m_confidenceMap;
}
int Tracker::getEstimatedTargetAmount()
{
return m_estimatedTargetAmount;
}
QList<int> Tracker::getCountingResult()
{
return m_sectionClusteringResult;
}
bool Tracker::isLost()
{
return m_isLost;
}
bool Tracker::isInit()
{
return m_initialized;
}
void Tracker::addManualLabeling(float x, float y, int frameNo)
{
STPoint stPoint;
stPoint.x = x;
stPoint.y = y;
stPoint.t = frameNo;
m_manualLabelings.append(stPoint);
}
bool Tracker::initialise()
{
if (!condensation_init())
{
qDebug() << "Failed to init Condensation algorithm";
return false;
}
if (0 == m_frameWidth || 0 == m_frameHeight)
{
qDebug() << "Failed to init Condensation algorithm, the frame size is not initialized";
return false;
}
m_spatioTemporalDetections.clear();
m_initialized = true;
return true;
}
QPointF Tracker::generateRandomPosition()
{
// 2D uniform distribution
double val_x = rand() % m_frameWidth;
double val_y = rand() % m_frameHeight;
return QPointF(val_x, val_y);
}
bool Tracker::insideFrame(QPointF sample)
{
if (sample.x() >= 0 && sample.x() <= m_frameWidth && sample.y() >=0 && sample.y() <= m_frameHeight)
return true;
else
return false;
}
void Tracker::runClusteringModelSelection(int startFrame, int endFrame)
{
std::vector<cv::Point3f> points = st_getPoints(startFrame, endFrame);
int pointsCount = (int)points.size();
cv::Mat labels;
// TODO: Space time cone filtering
qDebug() << "Points before filtering:" << pointsCount;
QList<STPoint> filteredPoints = runSpaceTimeConeFiltering(startFrame, endFrame);
m_filteredPoints.append(filteredPoints);
points = Utility::QListSTPointToStdVectorCvPoint3f(filteredPoints);
pointsCount = (int)points.size();
qDebug() << "Points after filtering:" << pointsCount;
if (0 == pointsCount)
return;
#ifdef PERFORMANCE_TUNING
QElapsedTimer elapsedTimer;
elapsedTimer.start();
#endif
int maxCluster = 0;
// int linesCount = clusterDetections_HoughTransform(startFrame, endFrame);
// if (linesCount < 1)
// maxCluster = pointsCount;
// else
// maxCluster = 2 * linesCount < pointsCount ? 2 * linesCount : pointsCount;
maxCluster = std::min(pointsCount, 10);
cv::Mat clusteringData;
if (Tracker::SpectralClustering == m_clusteringAlgorithm)
{
/* Create adjacency and degree matrices */
float sigma = 100.0f;
cv::Mat adjacency = Utility::gaussianDistance(points, sigma);
cv::Mat degree = degreeMatrix(adjacency);
/* Create laplacian matrix */
cv::Mat L = cv::Mat::diag(degree) - adjacency;
cv::Mat degree_05;
pow(degree, -0.5, degree_05);
degree_05 = cv::Mat::diag(degree_05);
L = (degree_05 * L) * degree_05;
/* Perform eigen decompositions */
cv::Mat eigenvalues, eigenvectors;
cv::eigen(L, eigenvalues, eigenvectors);
clusteringData = eigenvectors;
} else if (Tracker::KMeansClustering == m_clusteringAlgorithm) {
clusteringData = cv::Mat(points);
} else if (Tracker::ARALClustering == m_clusteringAlgorithm) {
// do nothing, we will use points
}
class ARALClustering aralClustering;
std::vector<int> rhos = aralClustering.calculateLocalDensity(points);
// std::cout << "rhos:" << std::endl;
int avgRho = 0;
for (size_t n = 0; n < rhos.size(); n++)
{
avgRho += rhos.at(n);
// std::cout << rhos.at(n) << std::endl;
}
if (0 != rhos.size())
{
avgRho /= rhos.size();
// std::cout << "Avg. rho:" << avgRho << std::endl;
}
// std::cout << "\n" << std::endl;
std::vector<double> deltas = aralClustering.calculateDistanceToHigherDensity(points, rhos);
// std::cout << "deltas:" << std::endl;
double avgDelta = 0.0;
for (size_t m = 0; m < deltas.size(); m++)
{
avgDelta += deltas.at(m);
// std::cout << deltas.at(m) << std::endl;
}
if (0 != deltas.size())
{
avgDelta /= deltas.size();
// std::cout << "Avg. delta:" << avgDelta << std::endl;
}
if (rhos.size() == deltas.size())
{
int rhoThreshold = avgRho/2;
double maxDelta = aralClustering.getMaxDelta(deltas);
double deltaThreshold = maxDelta - (maxDelta - avgDelta)/2;
for (int ii = 0; ii < (int)rhos.size(); ii++)
{
int rho = rhos.at(ii);
double delta = deltas.at(ii);
if (rho < rhoThreshold && delta > deltaThreshold)
{
cv::Point3f p = points.at(ii);
STPoint stP;
stP.x = p.x;
stP.y = p.y;
stP.t = p.z;
// std::cout << "Outlier candidate:" << "(" << p.x << "," << p.y << "," << p.z << ")" << std::endl;
}
}
}
double minMDL = 100000;
int clusterCount = 1;
cv::Mat candidateLabels;
for (int k = 1; k <= maxCluster; k++)
{
cv::Mat dataPoints;
if (Tracker::SpectralClustering == m_clusteringAlgorithm)
{
/* Since it's automatically sorted in descending order, take the last two entries of eigenvectors */
dataPoints = clusteringData.rowRange(clusteringData.rows - k, clusteringData.rows).t();
} else if (Tracker::KMeansClustering == m_clusteringAlgorithm) {
dataPoints = clusteringData;
} else if (Tracker::ARALClustering == m_clusteringAlgorithm) {
class ARALClustering aralClustering;
std::vector<int> rhos = aralClustering.calculateLocalDensity(points);
std::cout << "rhos:" << std::endl;
for (size_t n = 0; n < rhos.size(); n++)
{
std::cout << rhos.at(n) << std::endl;
}
std::cout << "\n" << std::endl;
std::vector<double> deltas = aralClustering.calculateDistanceToHigherDensity(points, rhos);
std::cout << "deltas:" << std::endl;
for (size_t m = 0; m < deltas.size(); m++)
{
std::cout << deltas.at(m) << std::endl;
}
}
cv::kmeans(dataPoints,
k,
candidateLabels,
cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 10, 1.0),
3,
cv::KMEANS_PP_CENTERS);
double mdl = calculateMDL(k, cv::Mat(points), candidateLabels);
if (mdl < minMDL)
{
minMDL = mdl;
clusterCount = k;
labels = candidateLabels.clone();
}
}
m_estimatedTargetAmount = clusterCount;
#ifdef PERFORMANCE_TUNING
qDebug() << "Tracker::runClusteringModelSelection MDL elapsed time: " << elapsedTimer.elapsed();
#endif
// Prepare cluster informations
m_clusters.clear();
double interval = 1.0 / double(clusterCount+1);
for (int label = 0; label < clusterCount; label++)
{
double val = double(label+1) * interval;
QColor color = Utility::getJetColor(val, 0.0, 1.0);
STCluster cluster;
cluster.label = label;
cluster.color = color;
m_clusters.append(cluster);
}
for (int i = 0; i < pointsCount; i++)
{
int label = labels.at<int>(i);
cv::Point3f point = points.at(i);
STPoint stPoint;
stPoint.x = point.x;
stPoint.y = point.y;
stPoint.t = point.z;
STCluster cluster = m_clusters.at(label);
cluster.points.append(stPoint);
m_clusters.replace(label, cluster);
}
// Cluster outlier removal
// runClusterOutlierRemoval();
// Calculate eigen vector(line) for each cluster
runClusterEigenLineCalculation();
// Update trajectories and detection colors(for each cluster) for each frame
// m_trajectories.clear();
// for (int cluster = 0; cluster < clusterCount; cluster++)
// {
// Trajectory track;
// track.label = cluster;
// m_trajectories.append(track);
// }
// m_colorLabels.clear();
// int offset = 0;
// for (int t = startFrame; t <= endFrame; t++)
// {
// QList<QColor> colors;
// ViolaJonesClassifier::VJDetection obs = m_spatioTemporalDetections.at(t);
// int num = obs.polygons.length();
// for (int i = 0; i < num; i++)
// {
// int label = labels.at<int>(offset + i);
// double val = double(label+1)*interval;
// QColor color = Utility::getJetColor(val, 0.0, 1.0);
// colors << color;
// Trajectory track;
// track.label = label;
// track.color = color;
// track.points = m_trajectories.at(label).points;
// QPointF center = obs.polygons.at(i).boundingRect().center();
// track.points.append(center);
// m_trajectories.replace(label, track);
// }
// m_colorLabels.append(colors);
// offset += num;
// }
}
QList<STPoint> Tracker::runSpaceTimeConeFiltering(int startFrame, int endFrame)
{
#ifdef PERFORMANCE_TUNING
QElapsedTimer elapsedTimer;
elapsedTimer.start();
#endif
QList<STPoint> filteredSTPoints;
int maxVelocity = 20;
int deltaTime = 1;
QList<STCone> cones;
// For each time/frame t
for (int t = startFrame; t <= endFrame; t++)
{
ViolaJonesClassifier::VJDetection obs = m_spatioTemporalDetections.at(t);
int num = obs.polygons.length();
for (int i = 0; i < num; i++)
{
QPointF center = obs.polygons.at(i).boundingRect().center();
STPoint point;
point.x = center.x();
point.y = center.y();
point.t = t * 10;
filteredSTPoints.append(point);
// Cone growing for a. static object, or b. holonomically moving object
if (0 == t)
{
STCone cone;
cone.points.append(point);
cones.append(cone);
} else {
bool assignment = false;
for (int j = 0; j < cones.length(); j++)
{
STCone cone = cones.at(j);
QList<STPoint> points = cone.points;
for (int n = points.length() - 1; n >= 0 ; n--)
{
STPoint p = points.at(n);
if (1 * 10 != (point.t - p.t))
break;
double distance = sqrt( pow((point.x - p.x), 2) + pow((point.y - p.y), 2) );
if (distance <= (maxVelocity * deltaTime))
{
cone.points.append(point);
cones.replace(j, cone);
assignment = true;
}
}
}
if (!assignment)
{
STCone cone;
cone.points.append(point);
cones.append(cone);
}
}
}
}
for (int n = 0; n < cones.length(); n++)
{
STCone cone = cones.at(n);
QList<STPoint> stPoints = cone.points;
if (stPoints.length() < 3)
{
foreach (const STPoint &pointToRemove, stPoints)
{
filteredSTPoints.removeOne(pointToRemove);
}
} else {
m_cones.append(cone);
}
}
// for (int n = 0; n < cones.length(); n++)
// {
// qDebug() << "Cone " << n+1;
// STCone cone = cones.at(n);
// QList<STPoint> stPoints = cone.points;
// for (int m = 0; m < stPoints.length(); m++)
// {
// STPoint p = stPoints.at(m);
// qDebug() << QString("(%1,%2,%3)").arg(p.x).arg(p.y).arg(p.t/10);
// }
// }
#ifdef PERFORMANCE_TUNING
qDebug() << "Tracker::runSpaceTimeConeFiltering elapsed time: " << elapsedTimer.elapsed();
#endif
return filteredSTPoints;
}
void Tracker::runClusterOutlierRemoval()
{
#ifdef PERFORMANCE_TUNING
QElapsedTimer elapsedTimer;
elapsedTimer.start();
#endif
int clusterCount = m_estimatedTargetAmount;
for (int label = 0; label < clusterCount; label++)
{
STCluster cluster = m_clusters.at(label);
QList<STPoint> points = cluster.points;
bool removalNeeded;
do {
removalNeeded = false;
int clusterSize = points.length();
if (clusterSize > 1)
{
QList<int> pointTimeDiffList;
QList<float> pointSpaceDiffList;
for (int i = 0; i < clusterSize; i++)
{
if (i > 0)
{
int tDiff = points.at(i).t - points.at(i-1).t;
pointTimeDiffList.append(tDiff);
float xDiff = points.at(i).x - points.at(i-1).x;
float yDiff = points.at(i).y - points.at(i-1).y;
float sDiff = sqrt(pow(xDiff, 2) + pow(yDiff, 2));
pointSpaceDiffList.append(sDiff);
}
}
int maxTimeDiff = 5;
int maxSpaceDiff = 100;
for (int j = 0; j < pointTimeDiffList.length(); j++)
{
int tDiff = pointTimeDiffList.at(j);
if (0 == tDiff)
continue;
float sDiff = pointSpaceDiffList.at(j);
if (tDiff > maxTimeDiff * 10 || sDiff > maxSpaceDiff)
{
points.removeAt(j);
removalNeeded = true;
break;
}
}
}
} while (removalNeeded);
cluster.points = points;
m_clusters.replace(label, cluster);
}
#ifdef PERFORMANCE_TUNING
qDebug() << "Tracker::runClusterOutlierRemoval elapsed time: " << elapsedTimer.elapsed();
#endif
}
void Tracker::runClusterEigenLineCalculation()
{
#ifdef PERFORMANCE_TUNING
QElapsedTimer elapsedTimer;
elapsedTimer.start();
#endif
int clusterCount = m_estimatedTargetAmount;
for (int label = 0; label < clusterCount; label++)
{
STCluster cluster = m_clusters.at(label);
QList<STPoint> stPoints = cluster.points;
std::vector<cv::Point3f> cvPoints;
for (int s = 0; s < stPoints.length(); s++)
{
STPoint stP = stPoints.at(s);
cv::Point3f cvP(stP.x, stP.y, stP.t);
cvPoints.push_back(cvP);
}
if (stPoints.length() > 1)
{
STLine line = Utility::fit3DLineToPoints(cvPoints);
cluster.eigenLine = line;
m_lineSegments.append(line);
}
m_clusters.replace(label, cluster);
}
#ifdef PERFORMANCE_TUNING
qDebug() << "Tracker::runClusterEigenLineCalculation elapsed time: " << elapsedTimer.elapsed();
#endif
}
void Tracker::runTrajectoryCounting()
{
std::vector<cv::Point3f> points = st_getPoints(0, m_spatioTemporalDetections.length() - 1);
cv::Mat clusteringData = cv::Mat(points);
Utility::fastICA(clusteringData);
}
std::vector<cv::Point3f> Tracker::st_getPoints(int startFrame, int endFrame)
{
std::vector<cv::Point3f> points;
// For each time/frame t
for (int t = startFrame; t <= endFrame; t++)
{
ViolaJonesClassifier::VJDetection obs = m_spatioTemporalDetections.at(t);
int num = obs.polygons.length();
for (int i = 0; i < num; i++)
{
QPointF center = obs.polygons.at(i).boundingRect().center();
points.push_back(cv::Point3f(center.x(), center.y(), t*10));
}
}
return points;
}
int Tracker::clusterDetections_HoughTransform(int startFrame, int endFrame)
{
#ifdef PERFORMANCE_TUNING
QElapsedTimer elapsedTimer;
elapsedTimer.start();
#endif
int x_offset = 10 / 2;
int y_offset = 20 / 2;
int frameCount = endFrame - startFrame + 1;
int space_width = 320 + x_offset * (frameCount-1);
int space_height = 150 + y_offset * (frameCount-1);
cv::Mat spaceImage = cv::Mat::zeros(space_height, space_width, CV_8UC3);
for (int t = startFrame; t < endFrame; t++)
{
ViolaJonesClassifier::VJDetection obs = m_spatioTemporalDetections.at(t);
int num = obs.polygons.length();
for (int i = 0; i < num; i++)
{
QPointF center = obs.polygons.at(i).boundingRect().center();
center /= 4;
int x = center.x() + ((frameCount-1) - t) * x_offset;
int y = center.y() + ((frameCount-1) - t) * y_offset;
int thickness = -1;
int lineType = 8;
cv::Point p(x, y);
cv::circle(spaceImage,
p,
1,
cv::Scalar(255, 255, 255),
thickness,
lineType);
}
}
spaceImage.at<float>(75, 160) = 255;
cv::Mat dst, color_dst;
cv::Canny(spaceImage, dst, 50, 200, 3);
cv::cvtColor(dst, color_dst, cv::COLOR_GRAY2BGR);
std::vector<cv::Vec4i> lines;
double rho = 1;
double theta = CV_PI/180;
int threshold = 6;
double minLineLength = 80;
double maxLineGap = 40;
cv::HoughLinesP(dst, lines, rho, theta * 2, threshold, minLineLength, maxLineGap);
for (size_t i = 0; i < lines.size(); i++)
{
cv::line(color_dst, cv::Point(lines[i][0], lines[i][1]),
cv::Point(lines[i][2], lines[i][3]), cv::Scalar(0,255,0), 2, 8);
}
// cv::namedWindow( "Detected Lines", 1 );
// cv::imshow( "Detected Lines", color_dst );
#ifdef PERFORMANCE_TUNING
qDebug() << "Tracker::clusterDetections_HoughTransform elapsed time: " << elapsedTimer.elapsed();
#endif
return (int)lines.size();
}
double Tracker::calculateMDL(int k, cv::Mat points, cv::Mat labels)
{
QHash<int, double> clusterHz;
QHash<int, std::vector<cv::Point3f> > clusterPoints;
for (int i = 0; i < k; i++)
{
clusterHz.insert(i,0);
}
for (int i = 0; i < points.rows; i++)
{
float x = points.at<float>(i, 0);
float y = points.at<float>(i, 1);
float z = points.at<float>(i, 2);
cv::Point3f p(x, y, z);
int label = labels.at<int>(i);
clusterHz[label]++;
clusterPoints[label].push_back(p);
}
double COST = 0.0;
foreach (int key, clusterPoints.keys())
{
std::vector<cv::Point3f> points = clusterPoints.value(key);
double volume = 0.0;
if (points.size() > 1)
volume = Utility::calClusterVolumn(points);
COST += volume;
}
int dimension = 3;
int numOfParameters = dimension * k;
double N = points.rows;
double COMP = 0.5 * numOfParameters * log(N);
COST /= 10;
COMP *= 3;
double mdl = COST + COMP;
// qDebug() << "Cluster K:" << k;
// qDebug() << "Cluster MDL:" << mdl;
// qDebug() << " MDL COST:" << COST;
// qDebug() << " MDL COMP:" << COMP;
// qDebug() << "";
return mdl;
}
int Tracker::getTotalDetectionCount()
{
int count = 0;
for (int n = 0; n < m_spatioTemporalDetections.length(); n++)
{
ViolaJonesClassifier::VJDetection obs = m_spatioTemporalDetections.at(n);
count += obs.polygons.length();
}
return count;
}
/* Create all the arrays, then fill in the prior distribution for the
first iteration. The prior is model-dependent, so
set_up_prior_conditions can be found in model_specific.c */
bool Tracker::condensation_init()
{
condensation_init_defaults();
data.new_positions = (QPointF*)malloc(sizeof(QPointF) * global.nsamples);
data.old_positions = (QPointF*)malloc(sizeof(QPointF) * global.nsamples);
data.sample_weights = (double*)malloc(sizeof(double) * global.nsamples);
data.cumul_prob_array = (double*)malloc(sizeof(double) * global.nsamples);
if (!data.new_positions || !data.old_positions ||
!data.sample_weights || !data.cumul_prob_array)
{
fprintf(stderr, "Failed to allocate memory for sample arrays\n");
qDebug() << "Failed to allocate memory for sample arrays";
return false;
}
condensation_set_up_prior_conditions();
return true;
}
/* This routine fills in the data structures with default constant
values. It could be enhanced by reading informatino from the
command line to allow e.g. N to be altered without recompiling. */
void Tracker::condensation_init_defaults(void)
{
global.nsamples = NSamples;
/* The following routines are model-specific and should be replaced to
implement an arbitrary process and observation model. */
/* Set up the parameters of the prior distribution */
global.prior.mean = PriorMean;
global.prior.sigma = PriorSigma;
/* Set up the parameters of the process model */