-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathVisualOdoGroundCam.cpp
More file actions
1405 lines (1231 loc) · 39 KB
/
Copy pathVisualOdoGroundCam.cpp
File metadata and controls
1405 lines (1231 loc) · 39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* A demonstration of visual odometry for car-like vehicles using a downward
* looking camera. Please refer to the publicaiton:
* Navid Nourani-Vatani and Paulo VK Borges
* Correlation-based Visual Odometry for Car-like Vehicles
* Journal of Field Robotics, September 2011
* Copyright (C) 2012 Navid Nourani-Vatani
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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/>.
*/
#include "VisualOdoGroundCam.h"
/**
* Set IMU off set values
*/
const double VisualOdo_t::imuOffsetRoll = 0.0;
const double VisualOdo_t::imuOffsetPitch = 0.0;
const double VisualOdo_t::imuOffsetYaw = 0.0;
/**
* \brief Looks in the directory and returns a sorted vector of files matching
* the fileName.
*/
int getDirContent (string dir,
vector<string> &files,
string fileName,
string extension = "") {
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(dir.c_str())) == NULL) {
cout << "\nError(" << errno << ") opening " << dir << endl;
return 0;
}
list<string> fileList;
while ((dirp = readdir(dp)) != NULL) {
string file = string(dirp->d_name);
bool nameOK = false;
bool extOK = false;
// File name matches
if (fileName == "" || fileName == "*" || file.find(fileName)
!= string::npos) {
nameOK = true;
}
// File extension matches
if (extension == "" || extension == "*" || file.find(extension)
!= string::npos) {
extOK = true;
}
if (nameOK && extOK) {
fileList.push_back(file);
}
}
closedir(dp);
// Sort the directory listing and copy to the vector
files.clear();
fileList.sort();
list<string>::iterator it;
for (it = fileList.begin(); it != fileList.end(); it++) {
files.push_back(*it);
}
return files.size();
}
/*
* \brief Calculate the median of the list.
*/
inline double median (std::list<double> l) {
std::list<double>::iterator it;
l.sort();
// Get the index location of the median
int medianIdx = 0;
if (l.size() % 2 == 0) {
medianIdx = l.size() / 2;
}
else {
medianIdx = l.size() / 2 + 1;
}
// Loop to this location
it = l.begin();
for (int i = 0; i < medianIdx; i++) {
it++;
}
return *it;
}
/**
* \brief Limits a value to a min/max
*/
inline double limit (double val, double minVal = 0, double maxVal = 1) {
if (val < minVal) {
val = minVal;
}
else if (val > maxVal) {
val = maxVal;
}
return val;
}
/**
* \brief Makes sure the value is within the image boundary
*/
inline void boundaryCheck (IplImage * frame,
int templateWinLength,
int * xStart,
int * yStart) {
if (*xStart < 0) {
*xStart = 0;
}
else if (*xStart >= frame->width - templateWinLength) {
*xStart = frame->width - templateWinLength - 1;
}
if (*yStart < 0) {
*yStart = 0;
}
else if (*yStart >= frame->height - templateWinLength) {
*yStart = frame->height - templateWinLength - 1;
}
}
/** ***************************************************************************
* \brief Use OpenCV's MatchTemplate to calculate the flow. The result is a min and a max val and their locations in the second frame.
* \param lastFrame - is the first frame
* \param currFrame - is the second frame we are trying to find a match in
* \param win - is the area in the first frame we want to find in the second frame
* \param minVal - The min value in the result frame
* \param maxVal - The max value in the result frame
* \param minLoc - Location of minVal
* \param maxLoc - Location of maxVal
* \param resize - Resize original frame too speed up detection. If result is bad it will try with original frame size.
* \param matchMethod - The matching method used (See OpenCV ref for details)
*/
bool templateMatching (IplImage * lastFrame,
IplImage * currFrame,
CvRect win,
double * minVal,
double * maxVal,
CvPoint * minLoc,
CvPoint * maxLoc,
double resizeFactor,
int matchMethod) {
static IplImage * tmpCurrFrame = NULL;
static IplImage * tmpLastFrame = NULL;
static CvRect tmpWin;
static IplImage * corrResult = NULL;
static CvMat * tmplate = NULL;
if (resizeFactor <= 0) {
resizeFactor = 1;
}
if (!tmpCurrFrame) {
tmpCurrFrame = cvCreateImage(cvSize(currFrame->width / resizeFactor,
currFrame->height / resizeFactor), IPL_DEPTH_8U,
currFrame->nChannels);
}
if (!tmpLastFrame) {
tmpLastFrame = cvCreateImage(cvSize(lastFrame->width / resizeFactor,
lastFrame->height / resizeFactor), IPL_DEPTH_8U,
lastFrame->nChannels);
}
tmpWin = cvRect(win.x / resizeFactor, win.y / resizeFactor, win.width
/ resizeFactor, win.height / resizeFactor);
// Resize everything
if (resizeFactor != 1.0) {
cvResize(currFrame, tmpCurrFrame);
cvResize(lastFrame, tmpLastFrame);
}
else {
cvCopy(currFrame, tmpCurrFrame);
cvCopy(lastFrame, tmpLastFrame);
}
// Create the template and extract it from the source image
if (!tmplate) {
tmplate = cvCreateMat(tmpWin.height, tmpWin.width, CV_8UC1);
}
// Create template Matrix from last frame
cvGetSubRect(tmpLastFrame, tmplate, tmpWin);
// Specify the size needed by the match function
int resultW = tmpCurrFrame->width - tmplate->width + 1;
int resultH = tmpCurrFrame->height - tmplate->height + 1;
// create the result image
cvReleaseImage(&corrResult);
corrResult = cvCreateImage(cvSize(resultW, resultH), IPL_DEPTH_32F, 1);
// See if we can find tmplate in currFrame
cvMatchTemplate(tmpCurrFrame, tmplate, corrResult, matchMethod);
//cvNamedWindow( "corr res", 1 );
//cvShowImage( "corr res", corrResult );
//cvWaitKey( 1 );
// Get min/max values
cvMinMaxLoc(corrResult, minVal, maxVal, minLoc, maxLoc);
if (minLoc) {
minLoc->x = (int) (minLoc->x * resizeFactor);
minLoc->y = (int) (minLoc->y * resizeFactor);
}
if (maxLoc) {
maxLoc->x = (int) (maxLoc->x * resizeFactor);
maxLoc->y = (int) (maxLoc->y * resizeFactor);
}
cvReleaseImage(&tmpCurrFrame);
cvReleaseImage(&tmpLastFrame);
cvReleaseData(tmplate);
return true;
}
#if USE_LIBMUSIC
/**
* Uses Linear Prediction Filter to perform forward prediction
* @param x - History of data points
* @param filtSize - Filter size
* @return prediction
*/
double predict( const double * x, const int filtSize ) {
double ac[filtSize];
double ref[filtSize];
double lpc[filtSize];
double est = 0;
// Auto-corr
autocorrelation(filtSize, x, filtSize, ac);
if( 0 ) {
cout << "ac: ";
for( int i = 0; i < filtSize; i++ ) {
cout << ac[i] << " ";
}
cout << endl;
}
// LPC
levinson_durbin( ac, ref, lpc );
if( 0 ) {
cout << "LPC: ";
for( int i = 0; i < filtSize; i++ ) {
cout << lpc[i] << " ";
}
cout << endl;
}
// Estimate
for( int i = 0; i < filtSize-1; i++ ) {
est += -lpc[i] * x[filtSize-i-2];
//cout << "-lpc[" << i << "]=" << -lpc[i] << ", x[" << filtSize-i-2 << "]=" << x[filtSize-i-2] << ", est=" << est << endl;
}
return est;
}
#endif
/**
* \brief Calculates the "quality" of the template window using different
* measures.
*/
double getTemplateQuality (IplImage * img, /** Template image */
int method /** 0=Auto-correlation, 1=Std Dev, 2=Variance, 3=MAD, 4=Entropy */
) {
double quality = 0;
// Auto-correlation variables
#ifdef USE_CIMG
CImg<float> tmp;
CImg<float> corr;
IplImage * iplImg = NULL;
CvPoint loc;
double firstMax = 0;
double secondMax = 0;
#endif
// MAD & Variance/StdDev variables
CvScalar mean;
CvScalar std_dev;
CvScalar mean_deviation;
double med = 0;
list<double> medianList;
// Entroty variables
int histSizes = 256;
float s_ranges[] = {0, histSizes};
float * ranges[] = {s_ranges};
static CvHistogram * hist = NULL;
if (hist == NULL && method == 4) {
hist = cvCreateHist(1, &histSizes, CV_HIST_ARRAY, ranges, 1);
}
double entropy = 0;
switch (method) {
/* Quality from auto-correlation */
case 0:
#ifdef USE_CLIMG
tmp.assign( img );
tmp = tmp - tmp.mean();
corr = tmp.correlate( tmp, 0, true );
// Get max location
iplImg = corr.get_IPL();
cvMinMaxLoc( iplImg, NULL, &firstMax, NULL, &loc, NULL );
// Set the max to 0.0
cvSetReal2D( iplImg, loc.x, loc.y, 0 );
// Get second max location
cvMinMaxLoc( iplImg, NULL, &secondMax, NULL, &loc, NULL );
if( secondMax != 0.0 ) {
quality = (secondMax/firstMax);
}
#else
cerr
<< "This feature is unavailable since we have not linked against CImg."
<< endl;
#endif
break;
/* Quality from variance */
case 1:
cvAvgSdv(img, &mean, &std_dev);
quality = pow(std_dev.val[0], 2.0) / MAX_THEORETICAL_VARIANCE;
break;
/* Quality from std dev */
case 2:
cvAvgSdv(img, &mean, &std_dev);
quality = std_dev.val[0] / MAX_THEORETICAL_STDEV;
break;
/* Quality from Me(di)an Absolute Deviation */
case 3:
#if 1 /* Median */
// calculate the median
for (register int j = 0; j < img->height; j++) {
for (register int i = 0; i < img->width; i++) {
medianList.push_back(img->imageData[j * img->widthStep + i]);
}
}
med = median(medianList);
// calculate the absolute deviation
medianList.clear();
for (register int j = 0; j < img->height; j++) {
for (register int i = 0; i < img->width; i++) {
medianList.push_back(fabs(img->imageData[j * img->widthStep
+ i] - med));
}
}
quality = median(medianList);
#else // Mean
mean = cvAvg( img, NULL );
cvAbsDiffS( img, img, mean );
mean_deviation = cvSum( img );
quality = mean_deviation.val[0] / MAX_THEORETICAL_MAD;
//printf( "mad: %d, max: %d, qual: %f\n",
// (int)mean_deviation.val[0], MAX_THEORETICAL_MAD, quality );
#endif
break;
/* Quality from Entropy */
case 4:
cvCalcHist(&img, hist);
cvNormalizeHist(hist, 1.0);
entropy = 0;
for (register int i = 0; i < histSizes; i++) {
float histValue = cvQueryHistValue_1D( hist, i );
if (histValue) {
entropy += histValue * log2(histValue);
}
}
quality = -entropy;
break;
default:
cerr << "Unknown method given: " << method << endl;
break;
}
return quality;
}
/**
* \brief Tries a number of different templates and returns the most suitable
* IplImage * testFrame - The image the template is going to be extracted from
* CvRect * rectOrg - The original template location and size
* int tries - How many different regions it should try
* int MAX_SHIFT - The max shift of template location
* int TQM - The template quality measure to use
*/
double getBestTemplate (IplImage * testFrame,
CvRect * rectOrg,
int tries,
int MAX_SHIFT,
int TQM) {
IplImage * tempTestFrame = NULL;
bool skip;
CvPoint maxLoc;
CvPoint minLoc;
double maxVal;
double minVal;
double scale;
double quality[tries];
double bestQuality = -1e6;
CvRect rect[tries];
CvRect bestRect = *rectOrg;
/* LUT for template locations */
int w = rectOrg->width;
int x = rectOrg->x;
int y = rectOrg->y;
int dX[tries];
int dY[tries];
switch (tries) {
case 1:
dX[0] = 0;
dY[0] = 0;
//dX[0] = -MAX_SHIFT/2; dY[0] = -MAX_SHIFT/2;
break;
case 2:
dX[0] = -MAX_SHIFT / 2;
dY[0] = 0;
dX[1] = +MAX_SHIFT / 2;
dY[1] = 0;
//dX[0] = -MAX_SHIFT/2; dY[0] = -MAX_SHIFT/2;
//dX[1] = +MAX_SHIFT/2; dY[1] = -MAX_SHIFT/2;
break;
case 3:
dX[0] = -MAX_SHIFT / 2;
dY[0] = 0;
dX[1] = +MAX_SHIFT / 2;
dY[1] = 0;
dX[2] = 0;
dY[2] = 0;
break;
case 4:
dX[0] = -MAX_SHIFT / 2;
dY[0] = -MAX_SHIFT / 2;
dX[1] = +MAX_SHIFT / 2;
dY[1] = -MAX_SHIFT / 2;
dX[2] = -MAX_SHIFT / 2;
dY[2] = +MAX_SHIFT / 2;
dX[3] = +MAX_SHIFT / 2;
dY[3] = +MAX_SHIFT / 2;
break;
case 5:
dX[0] = -MAX_SHIFT / 2;
dY[0] = -MAX_SHIFT / 2;
dX[1] = +MAX_SHIFT / 2;
dY[1] = -MAX_SHIFT / 2;
dX[2] = -MAX_SHIFT / 2;
dY[2] = +MAX_SHIFT / 2;
dX[3] = +MAX_SHIFT / 2;
dY[3] = +MAX_SHIFT / 2;
dX[4] = 0;
dY[4] = 0;
break;
case 7:
dX[0] = -MAX_SHIFT / 2;
dY[0] = -MAX_SHIFT;
dX[1] = +MAX_SHIFT / 2;
dY[1] = -MAX_SHIFT;
dX[2] = -MAX_SHIFT;
dY[2] = 0;
dX[3] = 0;
dY[3] = 0;
dX[4] = +MAX_SHIFT;
dY[4] = 0;
dX[5] = -MAX_SHIFT / 2;
dY[5] = +MAX_SHIFT;
dX[6] = +MAX_SHIFT / 2;
dY[6] = +MAX_SHIFT;
break;
case 8:
dX[0] = -MAX_SHIFT;
dY[0] = -MAX_SHIFT / 2;
dX[1] = +MAX_SHIFT;
dY[1] = -MAX_SHIFT / 2;
dX[2] = 0;
dY[2] = -MAX_SHIFT / 2;
dX[3] = -MAX_SHIFT / 2;
dY[3] = 0;
dX[4] = +MAX_SHIFT / 2;
dY[4] = 0;
dX[5] = -MAX_SHIFT;
dY[5] = +MAX_SHIFT / 2;
dX[6] = +MAX_SHIFT;
dY[6] = +MAX_SHIFT / 2;
dX[7] = 0;
dY[7] = +MAX_SHIFT / 2;
break;
default:
cerr << "Can't do " << tries << " tests!" << endl;
return -1;
}
/* Now test the quality of several template areas */
for (int i = 0; i < tries; i++) {
skip = false;
/* Location of template is selected from the LUT */
rect[i] = cvRect(x + dX[i], y + dY[i], w, w);
/* Boundary test */
boundaryCheck(testFrame, rect[i].width, &rect[i].x, &rect[i].y);
// if( rect[i].x < 0 ) {
// rect[i].x = 0;
// }
// if( rect[i].x + rect[i].width >= testFrame->width ) {
// rect[i].x = testFrame->width - rect[i].width - 1;
// }
// if( rect[i].y < 0 ) {
// rect[i].y = 0;
// }
// if( rect[i].y + rect[i].height >= testFrame->height ) {
// rect[i].y = testFrame->height - rect[i].height - 1;
// }
/* Extract the template image */
while (true) {
/* Make sure the template is inside the image boundary */
if (rect[i].x < 0 || rect[i].y < 0 || rect[i].x + rect[i].width
> testFrame->width || rect[i].y + rect[i].height
> testFrame->height) {
skip = true;
cout << "WARNING: Skipping template @ " << rect[i].x << ", "
<< rect[i].y << endl;
break;
}
cvSetImageROI(testFrame, rect[i]);
CvRect r = cvGetImageROI(testFrame);
if (r.x == rect[i].x && r.y == rect[i].y && r.width
== rect[i].width && r.height == rect[i].height) {
if (tempTestFrame) {
cvReleaseImage(&tempTestFrame);
}
tempTestFrame = cvCreateImage(cvSize(r.width, r.height),
testFrame->depth, testFrame->nChannels);
cvCopy(testFrame, tempTestFrame);
cvResetImageROI(testFrame);
break;
}
/* template is outside image region. Let's stick to the original
location. NOTE: there can be multiple of these! */
else {
rect[i] = *rectOrg;
cerr << "\nERROR: This should not happen!" << endl;
abort();
}
}
if (skip) {
continue;
quality[i] = 0;
}
/* Get the template quality */
quality[i] = getTemplateQuality(tempTestFrame, TQM);
if (quality[i] > bestQuality) {
bestQuality = quality[i];
bestRect = rect[i];
}
cvReleaseImage(&tempTestFrame);
if( show ) {
char s[32];
cvRectangle(
prevDrawFrame, cvPoint( rect[i].x, rect[i].y ),
cvPoint( rect[i].x + rect[i].width, rect[i].y + rect[i].height ),
CV_RGB(255,255,0), 3 );
sprintf( s, "%.3f", quality[i] );
cvPutText( prevDrawFrame, s, cvPoint( rect[i].x + 5, rect[i].y + 12 ), &font, CV_RGB(64,64,64) );
}
}
/* return the best location back to the caller */
*rectOrg = bestRect;
return bestQuality;
}
/** ***************************************************************************
*
*/
void calcPoseAfterCamShift (VisualOdo_t * vodo,
int deltaX,
int deltaY,
double deltaTime) {
SMALL::Matrix<4, 4, double> H;
SMALL::Matrix<4, 4, double> Hd;
SMALL::Pose3D poseTmp, poseShift, poseHd;
double rollAng = 0;
double pitchAng = 0;
// Add the influence of roll and pitch
#if imuAvailable
if( imu ) {
rollAng = imu->roll - imuOffsetRoll;
pitchAng = imu->pitch - imuOffsetPitch;
}
#endif
// Convert to real world displacement
poseTmp.setPosition(deltaX * vodo->zConst, deltaY * vodo->zConst, 0.0);
// Convert to vehicle front frame
poseShift = vodo->A3D * poseTmp;
// Displacement seen from the vehicle
double x = poseShift.getX() * cos(pitchAng);
double y = 0; // No side-ways displacement
double z = poseShift.getX() * sin(pitchAng);
double th = atan2(poseShift.getY(), vodo->poseCam.getX());
poseHd.setPosition(x, y, z);
poseHd.setAxisAngle(SMALL::makeVector(0, 0, 1), th);
// Increment pose
vodo->pose = vodo->pose * poseHd;
}
/******************************************************************************
*
* Main worker thread
*
*****************************************************************************/
void * worker_thread (void * arg) {
VisualOdo_t * vodo = (VisualOdo_t *) arg;
// Init working frames
IplImage * currFrame = cvCreateImage(cvGetSize(vodo->frame), IPL_DEPTH_8U,
1);
IplImage * prevFrame = cvCreateImage(cvGetSize(vodo->frame), IPL_DEPTH_8U,
1);
IplImage * tmpFrame =
cvCreateImage(cvGetSize(vodo->frame), IPL_DEPTH_8U, 1);
IplImage * tempTemplateImg = cvCreateImage(cvSize(vodo->templateWinLength,
vodo->templateWinLength), IPL_DEPTH_8U, 1);
// Variables for drawing purposes
CvPoint p;
CvPoint q;
if (show) {
prevDrawFrame = cvCreateImage(cvGetSize(vodo->frame), IPL_DEPTH_8U, 3);
currDrawFrame = cvCreateImage(cvGetSize(vodo->frame), IPL_DEPTH_8U, 3);
cvInitFont(&font, CV_FONT_HERSHEY_PLAIN, 1.0, 1.0);
cvNamedWindow("Previous Frame", 0);
cvMoveWindow("Previous Frame", 510, 10);
cvNamedWindow("Current Frame", 0);
cvMoveWindow("Current Frame", vodo->frame->width / 2 + 520, 10);
}
// Template matching stuff
int xStart = vodo->frame->width / 2 - vodo->templateWinLength / 2;
int yStart = vodo->frame->height / 2 - vodo->templateWinLength / 2;
CvRect win = cvRect(xStart, yStart, vodo->templateWinLength,
vodo->templateWinLength);
CvPoint corrPredictLocation;
CvPoint corrMatchLocation;
double corrMatchVal = 0.0;
int deltaX = 0;
int deltaY = 0;
int deltaXPrev = 0;
int deltaYPrev = 0;
CvRect subWin = cvRect(0, 0, vodo->frame->width, vodo->frame->height);
double quality = 0.0;
double MIN_GOOD_CORR_RESULT = 0.7;
int numBadCorrelationsInSeq = 0;
int numBadCorrelations = 0;
int loopCount = 0;
struct timeval tv;
long prevFrameNum = 0;
double prevFrameTimeDouble = 0;
double deltaTimeRough;
double deltaTime;
double loopStartTime = 0;
double loopEndTime = 0;
// Velocity filtering
int velFiltSize = 5;
std::list<double> velVec(velFiltSize, 0);
if (vodo->startFrame) {
cout << "Skipping until frame " << vodo->startFrame << endl;
if( getFrameFromImages ) {
vodo->frameNum = vodo->startFrame;
prevFrameNum = vodo->frameNum;
}
else {
prevFrameNum = vodo->startFrame;
}
}
/*************************************************************************/
while (!done) {
gettimeofday(&tv, NULL);
loopStartTime = tv.tv_sec + tv.tv_usec * 1e-6;
if (verbose)
cout << endl << endl;
/**********************************************************************
*
* Read Frame
*
**********************************************************************/
if (1) {
// Get frame
if (getFrameFromImages) {
if( vodo->frame ) {
cvReleaseImage( &vodo->frame );
}
vodo->frame
= cvLoadImage(
(fileDir + "/" + fileVec[vodo->frameNum]).c_str(),
CV_LOAD_IMAGE_COLOR);
// TODO: parse file name as grab time
vodo->frameGrabTimeDouble = (1.0 / vodo->MAX_FRAME_RATE)
* vodo->frameNum + 1;
}
else {
vodo->frame = cvQueryFrame(vodo->capture);
// Get time
gettimeofday(&tv, NULL);
vodo->frameGrabTimeDouble = tv.tv_sec + tv.tv_usec * 1e-6;
}
// Make sure the grabbed frame has different time stamp than the
// previous frame
if (vodo->frameGrabTimeDouble == prevFrameTimeDouble) {
continue;
}
// Frame counter is internal (Use counter from camera to be more precise and detected missed frames
vodo->frameNum++;
// Skip first frames
if ( vodo->frameNum < vodo->startFrame ) {
// cout << "Skipping until frame " << vodo->startFrame << " ("
// << vodo->frameNum << ")" << endl;
continue;
}
// Missed frame
// To ensure we can run at the max frame rate we need to always capture consecutive frames
if ((vodo->frameNum - prevFrameNum) > 1) {
cout << "Warning: Missed " << vodo->frameNum - prevFrameNum
<< " frames. (" << prevFrameNum << " -> " << vodo->frameNum << ")" << endl;
done = true;
continue;
}
#if imuAvailable
// Read IMU if available
#endif
// Get delta time and filter it as the time can be noisy.
// I am ensuring that the delta time is a product of the max frame rate
deltaTimeRough = vodo->frameGrabTimeDouble - prevFrameTimeDouble;
deltaTime = round(deltaTimeRough * vodo->MAX_FRAME_RATE)
/ vodo->MAX_FRAME_RATE;
// Copy back
cvCopy(currFrame, prevFrame);
prevFrameTimeDouble = vodo->frameGrabTimeDouble;
prevFrameNum = vodo->frameNum;
// Work on gray scale images
if (vodo->frame->nChannels == currFrame->nChannels) {
cvCopy(vodo->frame, currFrame);
}
else if (vodo->frame->nChannels == 3) {
cvCvtColor(vodo->frame, currFrame, CV_RGB2GRAY);
}
// Prepare drawing frames
if (show) {
cvMerge(currFrame, currFrame, currFrame, NULL, currDrawFrame);
cvMerge(prevFrame, prevFrame, prevFrame, NULL, prevDrawFrame);
}
}
/**********************************************************************
*
* Image displacement calculation
*
*********************************************************************/
if (1) {
CvPoint offset = cvPoint(0, 0);
deltaXPrev = deltaX;
deltaYPrev = deltaY;
// Difference between prediction and actual location
int diffPreTrueU = fabs(vodo->predictDeltaU - deltaXPrev);
int diffPreTrueV = fabs(vodo->predictDeltaV - deltaYPrev);
/* ************************************************
*
* Setup correlation mask location based on the
* prediction
*
*/
#if USE_LIBMUSIC
// Using linear forward prediction FIR filter
if( dUHist.size() >= filtSize ) {
dUIter = dUHist.begin();
dVIter = dVHist.begin();
int ii = 0;
for(; dUIter != dUHist.end(); dUIter++, dVIter++, ii++ ) {
xHist[ii] = *dUIter;
yHist[ii] = *dVIter;
}
predictDeltaU = predict( xHist, filtSize ) * 1.12;
predictDeltaV = predict( yHist, filtSize ) * 1.12;
dUHist.pop_front();
dVHist.pop_front();
}
// The previous match was good so we shift
else if( corrMatchVal >= MIN_GOOD_CORR_RESULT ) {
predictDeltaU = deltaXPrev;
predictDeltaV = deltaYPrev;
}
// Pick the location in the center
else {
predictDeltaU = 0;
predictDeltaV = 0;
}
xStart = templateFixCorner.x + predictDeltaU / 2;
yStart = templateFixCorner.y + predictDeltaV / 2;
#else
// Using Kalman filters to predict the location of the template window
cvKalmanPredict(vodo->kalmanU);
cvKalmanPredict(vodo->kalmanV);
vodo->predictDeltaU = vodo->kalmanU->state_pre->data.fl[0]; //yU_k->data.fl[0];
vodo->predictDeltaV = vodo->kalmanV->state_pre->data.fl[0]; //yV_k->data.fl[0];
xStart = vodo->frame->width / 2 - vodo->templateWinLength / 2
+ vodo->predictDeltaU / 2;
yStart = vodo->frame->height / 2 - vodo->templateWinLength / 2
+ vodo->predictDeltaV / 2;
#endif
// Boundary check
boundaryCheck(vodo->frame, vodo->templateWinLength, &xStart,
&yStart);
// Template location
win = cvRect(xStart, yStart, vodo->templateWinLength,
vodo->templateWinLength);
/* ************************************************
*
* Test the quality of the template
*
*/
quality = -1;
if (vodo->numTemplateTests > 1) {
quality = getBestTemplate(prevFrame, &win,
vodo->numTemplateTests, win.width,
vodo->templateQualityMeasure);
}
/* ************************************************
*
* Template location based on the prediction and
* the best fit location
*
*/
corrPredictLocation = cvPoint(win.x - vodo->predictDeltaU, win.y
- vodo->predictDeltaV);
/* ************************************************
*
* Restricted search
* Take out a sub image for the correlation to find a match
*
*/
if ( vodo->restrictSearch && (corrMatchVal >= MIN_GOOD_CORR_RESULT
|| numBadCorrelationsInSeq <= 1)) {
int h, w;
#if 0
// Linear model
h = (1.5 + (deltaTime*MAX_FRAME_RATE/2) + vel/MAX_VEL) * MIN_SIZE + fabs(yU_k->data.fl[0]);
w = (1.5 + (deltaTime*MAX_FRAME_RATE/2) + vel/MAX_VEL) * MIN_SIZE + fabs(yU_k->data.fl[0]);
#elif 0
// Velocity model
double alpha = 1;
double beta = 40;
h = alpha * (frameNum - prevFrameNum) * fabs(deltaYPrev) + beta;
w = alpha * (frameNum - prevFrameNum) * fabs(deltaXPrev) + beta;
#else
// Constant Size Model
h = vodo->restrictedSearchArea;
w = vodo->restrictedSearchArea;
#endif
h = limit(h, vodo->restrictedSearchArea, vodo->frame->height - 1);
w = limit(w, vodo->restrictedSearchArea, vodo->frame->width - 1);
int x = corrPredictLocation.x + win.width / 2 - w / 2;
int y = corrPredictLocation.y + win.height / 2 - h / 2;
// Boundary Check
x = limit( x, 0, currFrame->width - w - 1);
y = limit( y, 0, currFrame->height - h - 1);
offset = cvPoint(x, y);
// Take out sub-image
CvRect tmpRect = cvRect(x, y, w, h);
if (tmpFrame->width != w || tmpFrame->height != h) {
cvReleaseImage(&tmpFrame);
tmpFrame = cvCreateImage(cvSize(w, h), 8, 1);
}
cvSetImageROI(currFrame, tmpRect);
cvCopy(currFrame, tmpFrame);
cvResetImageROI(currFrame);
if (show) {
// draw restriction
cvRectangle(currDrawFrame, cvPoint(x, y), cvPoint(x + w, y
+ h), CV_RGB( 255, 0, 255 ), 3);
}
}
// Pass on the original image
else {
if (tmpFrame->width != currFrame->width || tmpFrame->height
!= currFrame->height) {
cvReleaseImage(&tmpFrame);
tmpFrame = cvCreateImage(cvGetSize(currFrame),
IPL_DEPTH_8U, 1);
}
cvCopy(currFrame, tmpFrame);
}
/* ************************************************
*
* Calculate template match
*
*/
templateMatching(prevFrame, tmpFrame, win, NULL, &corrMatchVal,
NULL, &corrMatchLocation, vodo->resizeFactor,
CV_TM_CCOEFF_NORMED);
/* ************************************************
*
* Displacement in pixels.
*
*/
//compensate for any offset due to sub-framing
corrMatchLocation.x += offset.x;
corrMatchLocation.y += offset.y;