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
|
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/tracking.hpp"
#include <iostream>
using namespace cv; using namespace std;
bool pointTrackingFlag = false; Point2f currentPoint;
void onMouse(int event, int x, int y, int, void *) { if (event == CV_EVENT_LBUTTONDOWN) { currentPoint = Point2f((float)x, (float)y);
pointTrackingFlag = true; } }
int main(int argc, char *argv[]) { VideoCapture cap(0);
if (!cap.isOpened()) { cerr << "Unable to open the webcam. Exiting!" << endl; return -1; }
TermCriteria terminationCriteria(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 10, 0.02);
Size windowSize(25, 25);
const int maxNumPoints = 200;
string windowName = "Lucas Kanade Tracker"; namedWindow(windowName, 1); setMouseCallback(windowName, onMouse, 0);
Mat prevGrayImage, curGrayImage, image, frame; vector<Point2f> trackingPoints[ 2 ];
float scalingFactor = 0.75;
while (true) { cap >> frame;
if (frame.empty()) break;
resize(frame, frame, Size(), scalingFactor, scalingFactor, INTER_AREA);
frame.copyTo(image);
cvtColor(image, curGrayImage, COLOR_BGR2GRAY);
if (!trackingPoints[ 0 ].empty()) { vector<uchar> statusVector;
vector<float> errorVector;
if (prevGrayImage.empty()) { curGrayImage.copyTo(prevGrayImage); }
calcOpticalFlowPyrLK(prevGrayImage, curGrayImage, trackingPoints[ 0 ], trackingPoints[ 1 ], statusVector, errorVector, windowSize, 3, terminationCriteria, 0, 0.001);
int count = 0;
int minDist = 7;
for (int i = 0; i < trackingPoints[ 1 ].size(); i++) { if (pointTrackingFlag) { if (norm(currentPoint - trackingPoints[ 1 ][ i ]) <= minDist) { pointTrackingFlag = false; continue; } }
if (!statusVector[ i ]) continue;
trackingPoints[ 1 ][ count++ ] = trackingPoints[ 1 ][ i ];
int radius = 8; int thickness = 2; int lineType = 8; circle(image, trackingPoints[ 1 ][ i ], radius, Scalar(0, 255, 0), thickness, lineType); }
trackingPoints[ 1 ].resize(count); }
if (pointTrackingFlag && trackingPoints[ 1 ].size() < maxNumPoints) { vector<Point2f> tempPoints; tempPoints.push_back(currentPoint);
cornerSubPix(curGrayImage, tempPoints, windowSize, cvSize(-1, -1), terminationCriteria);
trackingPoints[ 1 ].push_back(tempPoints[ 0 ]); pointTrackingFlag = false; }
imshow(windowName, image);
char ch = waitKey(10); if (ch == 27) break;
std::swap(trackingPoints[ 1 ], trackingPoints[ 0 ]);
cv::swap(prevGrayImage, curGrayImage); }
return 0; }
|