1 #include "opencv2/video/tracking.hpp"
2 #include "opencv2/imgproc/imgproc.hpp"
3 #include "opencv2/videoio/videoio.hpp"
4 #include "opencv2/highgui/highgui.hpp"
14 // print a welcome message, and the OpenCV version
15 cout << "\nThis is a demo of Lukas-Kanade optical flow lkdemo(),\n"
16 "Using OpenCV version " << CV_VERSION << endl;
17 cout << "\nIt uses camera by default, but you can provide a path to video as an argument.\n";
18 cout << "\nHot keys: \n"
19 "\tESC - quit the program\n"
20 "\tr - auto-initialize tracking\n"
21 "\tc - delete all the points\n"
22 "\tn - switch the \"night\" mode on/off\n"
23 "To add/remove a feature point click it\n" << endl;
27 bool addRemovePt = false;
29 static void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
31 if( event == EVENT_LBUTTONDOWN )
33 point = Point2f((float)x, (float)y);
38 int main( int argc, char** argv )
43 TermCriteria termcrit(TermCriteria::COUNT|TermCriteria::EPS,20,0.03);
44 Size subPixWinSize(10,10), winSize(31,31);
46 const int MAX_COUNT = 500;
47 bool needToInit = false;
48 bool nightMode = false;
50 if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
51 cap.open(argc == 2 ? argv[1][0] - '0' : 0);
57 cout << "Could not initialize capturing...\n";
61 namedWindow( "LK Demo", 1 );
62 setMouseCallback( "LK Demo", onMouse, 0 );
64 Mat gray, prevGray, image;
65 vector<Point2f> points[2];
75 cvtColor(image, gray, COLOR_BGR2GRAY);
78 image = Scalar::all(0);
82 // automatic initialization
83 goodFeaturesToTrack(gray, points[1], MAX_COUNT, 0.01, 10, Mat(), 3, 0, 0.04);
84 cornerSubPix(gray, points[1], subPixWinSize, Size(-1,-1), termcrit);
87 else if( !points[0].empty() )
92 gray.copyTo(prevGray);
93 calcOpticalFlowPyrLK(prevGray, gray, points[0], points[1], status, err, winSize,
94 3, termcrit, 0, 0.001);
96 for( i = k = 0; i < points[1].size(); i++ )
100 if( norm(point - points[1][i]) <= 5 )
110 points[1][k++] = points[1][i];
111 circle( image, points[1][i], 3, Scalar(0,255,0), -1, 8);
116 if( addRemovePt && points[1].size() < (size_t)MAX_COUNT )
119 tmp.push_back(point);
120 cornerSubPix( gray, tmp, winSize, Size(-1,-1), termcrit);
121 points[1].push_back(tmp[0]);
126 imshow("LK Demo", image);
128 char c = (char)waitKey(10);
141 nightMode = !nightMode;
145 std::swap(points[1], points[0]);
146 cv::swap(prevGray, gray);