Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/samples/gpu/pyrlk_optical_flow.cpp
16337 views
1
#include <iostream>
2
#include <vector>
3
4
#include <opencv2/core.hpp>
5
#include <opencv2/core/utility.hpp>
6
#include <opencv2/imgproc.hpp>
7
#include <opencv2/highgui.hpp>
8
#include <opencv2/video.hpp>
9
#include <opencv2/cudaoptflow.hpp>
10
#include <opencv2/cudaimgproc.hpp>
11
#include <opencv2/cudaarithm.hpp>
12
13
using namespace std;
14
using namespace cv;
15
using namespace cv::cuda;
16
17
static void download(const GpuMat& d_mat, vector<Point2f>& vec)
18
{
19
vec.resize(d_mat.cols);
20
Mat mat(1, d_mat.cols, CV_32FC2, (void*)&vec[0]);
21
d_mat.download(mat);
22
}
23
24
static void download(const GpuMat& d_mat, vector<uchar>& vec)
25
{
26
vec.resize(d_mat.cols);
27
Mat mat(1, d_mat.cols, CV_8UC1, (void*)&vec[0]);
28
d_mat.download(mat);
29
}
30
31
static void drawArrows(Mat& frame, const vector<Point2f>& prevPts, const vector<Point2f>& nextPts, const vector<uchar>& status, Scalar line_color = Scalar(0, 0, 255))
32
{
33
for (size_t i = 0; i < prevPts.size(); ++i)
34
{
35
if (status[i])
36
{
37
int line_thickness = 1;
38
39
Point p = prevPts[i];
40
Point q = nextPts[i];
41
42
double angle = atan2((double) p.y - q.y, (double) p.x - q.x);
43
44
double hypotenuse = sqrt( (double)(p.y - q.y)*(p.y - q.y) + (double)(p.x - q.x)*(p.x - q.x) );
45
46
if (hypotenuse < 1.0)
47
continue;
48
49
// Here we lengthen the arrow by a factor of three.
50
q.x = (int) (p.x - 3 * hypotenuse * cos(angle));
51
q.y = (int) (p.y - 3 * hypotenuse * sin(angle));
52
53
// Now we draw the main line of the arrow.
54
line(frame, p, q, line_color, line_thickness);
55
56
// Now draw the tips of the arrow. I do some scaling so that the
57
// tips look proportional to the main line of the arrow.
58
59
p.x = (int) (q.x + 9 * cos(angle + CV_PI / 4));
60
p.y = (int) (q.y + 9 * sin(angle + CV_PI / 4));
61
line(frame, p, q, line_color, line_thickness);
62
63
p.x = (int) (q.x + 9 * cos(angle - CV_PI / 4));
64
p.y = (int) (q.y + 9 * sin(angle - CV_PI / 4));
65
line(frame, p, q, line_color, line_thickness);
66
}
67
}
68
}
69
70
inline bool isFlowCorrect(Point2f u)
71
{
72
return !cvIsNaN(u.x) && !cvIsNaN(u.y) && fabs(u.x) < 1e9 && fabs(u.y) < 1e9;
73
}
74
75
static Vec3b computeColor(float fx, float fy)
76
{
77
static bool first = true;
78
79
// relative lengths of color transitions:
80
// these are chosen based on perceptual similarity
81
// (e.g. one can distinguish more shades between red and yellow
82
// than between yellow and green)
83
const int RY = 15;
84
const int YG = 6;
85
const int GC = 4;
86
const int CB = 11;
87
const int BM = 13;
88
const int MR = 6;
89
const int NCOLS = RY + YG + GC + CB + BM + MR;
90
static Vec3i colorWheel[NCOLS];
91
92
if (first)
93
{
94
int k = 0;
95
96
for (int i = 0; i < RY; ++i, ++k)
97
colorWheel[k] = Vec3i(255, 255 * i / RY, 0);
98
99
for (int i = 0; i < YG; ++i, ++k)
100
colorWheel[k] = Vec3i(255 - 255 * i / YG, 255, 0);
101
102
for (int i = 0; i < GC; ++i, ++k)
103
colorWheel[k] = Vec3i(0, 255, 255 * i / GC);
104
105
for (int i = 0; i < CB; ++i, ++k)
106
colorWheel[k] = Vec3i(0, 255 - 255 * i / CB, 255);
107
108
for (int i = 0; i < BM; ++i, ++k)
109
colorWheel[k] = Vec3i(255 * i / BM, 0, 255);
110
111
for (int i = 0; i < MR; ++i, ++k)
112
colorWheel[k] = Vec3i(255, 0, 255 - 255 * i / MR);
113
114
first = false;
115
}
116
117
const float rad = sqrt(fx * fx + fy * fy);
118
const float a = atan2(-fy, -fx) / (float)CV_PI;
119
120
const float fk = (a + 1.0f) / 2.0f * (NCOLS - 1);
121
const int k0 = static_cast<int>(fk);
122
const int k1 = (k0 + 1) % NCOLS;
123
const float f = fk - k0;
124
125
Vec3b pix;
126
127
for (int b = 0; b < 3; b++)
128
{
129
const float col0 = colorWheel[k0][b] / 255.0f;
130
const float col1 = colorWheel[k1][b] / 255.0f;
131
132
float col = (1 - f) * col0 + f * col1;
133
134
if (rad <= 1)
135
col = 1 - rad * (1 - col); // increase saturation with radius
136
else
137
col *= .75; // out of range
138
139
pix[2 - b] = static_cast<uchar>(255.0 * col);
140
}
141
142
return pix;
143
}
144
145
static void drawOpticalFlow(const Mat_<float>& flowx, const Mat_<float>& flowy, Mat& dst, float maxmotion = -1)
146
{
147
dst.create(flowx.size(), CV_8UC3);
148
dst.setTo(Scalar::all(0));
149
150
// determine motion range:
151
float maxrad = maxmotion;
152
153
if (maxmotion <= 0)
154
{
155
maxrad = 1;
156
for (int y = 0; y < flowx.rows; ++y)
157
{
158
for (int x = 0; x < flowx.cols; ++x)
159
{
160
Point2f u(flowx(y, x), flowy(y, x));
161
162
if (!isFlowCorrect(u))
163
continue;
164
165
maxrad = max(maxrad, sqrt(u.x * u.x + u.y * u.y));
166
}
167
}
168
}
169
170
for (int y = 0; y < flowx.rows; ++y)
171
{
172
for (int x = 0; x < flowx.cols; ++x)
173
{
174
Point2f u(flowx(y, x), flowy(y, x));
175
176
if (isFlowCorrect(u))
177
dst.at<Vec3b>(y, x) = computeColor(u.x / maxrad, u.y / maxrad);
178
}
179
}
180
}
181
182
static void showFlow(const char* name, const GpuMat& d_flow)
183
{
184
GpuMat planes[2];
185
cuda::split(d_flow, planes);
186
187
Mat flowx(planes[0]);
188
Mat flowy(planes[1]);
189
190
Mat out;
191
drawOpticalFlow(flowx, flowy, out, 10);
192
193
imshow(name, out);
194
}
195
196
template <typename T> inline T clamp (T x, T a, T b)
197
{
198
return ((x) > (a) ? ((x) < (b) ? (x) : (b)) : (a));
199
}
200
201
template <typename T> inline T mapValue(T x, T a, T b, T c, T d)
202
{
203
x = clamp(x, a, b);
204
return c + (d - c) * (x - a) / (b - a);
205
}
206
207
int main(int argc, const char* argv[])
208
{
209
const char* keys =
210
"{ h help | | print help message }"
211
"{ l left | ../data/pic1.png | specify left image }"
212
"{ r right | ../data/pic2.png | specify right image }"
213
"{ flow | sparse | specify flow type [PyrLK] }"
214
"{ gray | | use grayscale sources [PyrLK Sparse] }"
215
"{ win_size | 21 | specify windows size [PyrLK] }"
216
"{ max_level | 3 | specify max level [PyrLK] }"
217
"{ iters | 30 | specify iterations count [PyrLK] }"
218
"{ points | 4000 | specify points count [GoodFeatureToTrack] }"
219
"{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }";
220
221
CommandLineParser cmd(argc, argv, keys);
222
223
if (cmd.has("help") || !cmd.check())
224
{
225
cmd.printMessage();
226
cmd.printErrors();
227
return 0;
228
}
229
230
string fname0 = cmd.get<string>("left");
231
string fname1 = cmd.get<string>("right");
232
233
if (fname0.empty() || fname1.empty())
234
{
235
cerr << "Missing input file names" << endl;
236
return -1;
237
}
238
239
string flow_type = cmd.get<string>("flow");
240
bool is_sparse = true;
241
if (flow_type == "sparse")
242
{
243
is_sparse = true;
244
}
245
else if (flow_type == "dense")
246
{
247
is_sparse = false;
248
}
249
else
250
{
251
cerr << "please specify 'sparse' or 'dense' as flow type" << endl;
252
return -1;
253
}
254
255
bool useGray = cmd.has("gray");
256
int winSize = cmd.get<int>("win_size");
257
int maxLevel = cmd.get<int>("max_level");
258
int iters = cmd.get<int>("iters");
259
int points = cmd.get<int>("points");
260
double minDist = cmd.get<double>("min_dist");
261
262
Mat frame0 = imread(fname0);
263
Mat frame1 = imread(fname1);
264
265
if (frame0.empty() || frame1.empty())
266
{
267
cout << "Can't load input images" << endl;
268
return -1;
269
}
270
271
cout << "Image size : " << frame0.cols << " x " << frame0.rows << endl;
272
cout << "Points count : " << points << endl;
273
274
cout << endl;
275
276
Mat frame0Gray;
277
cv::cvtColor(frame0, frame0Gray, COLOR_BGR2GRAY);
278
Mat frame1Gray;
279
cv::cvtColor(frame1, frame1Gray, COLOR_BGR2GRAY);
280
281
// goodFeaturesToTrack
282
GpuMat d_frame0Gray(frame0Gray);
283
GpuMat d_prevPts;
284
285
Ptr<cuda::CornersDetector> detector = cuda::createGoodFeaturesToTrackDetector(d_frame0Gray.type(), points, 0.01, minDist);
286
detector->detect(d_frame0Gray, d_prevPts);
287
288
GpuMat d_frame0(frame0);
289
GpuMat d_frame1(frame1);
290
GpuMat d_frame1Gray(frame1Gray);
291
GpuMat d_nextPts;
292
GpuMat d_status;
293
GpuMat d_flow(frame0.size(), CV_32FC2);
294
295
if (is_sparse)
296
{
297
// Sparse
298
Ptr<cuda::SparsePyrLKOpticalFlow> d_pyrLK_sparse = cuda::SparsePyrLKOpticalFlow::create(
299
Size(winSize, winSize), maxLevel, iters);
300
d_pyrLK_sparse->calc(useGray ? d_frame0Gray : d_frame0, useGray ? d_frame1Gray : d_frame1, d_prevPts, d_nextPts, d_status);
301
302
// Draw arrows
303
vector<Point2f> prevPts(d_prevPts.cols);
304
download(d_prevPts, prevPts);
305
306
vector<Point2f> nextPts(d_nextPts.cols);
307
download(d_nextPts, nextPts);
308
309
vector<uchar> status(d_status.cols);
310
download(d_status, status);
311
312
namedWindow("PyrLK [Sparse]", WINDOW_NORMAL);
313
drawArrows(frame0, prevPts, nextPts, status, Scalar(255, 0, 0));
314
imshow("PyrLK [Sparse]", frame0);
315
}
316
else
317
{
318
// Dense
319
Ptr<cuda::DensePyrLKOpticalFlow> d_pyrLK_dense = cuda::DensePyrLKOpticalFlow::create(
320
Size(winSize, winSize), maxLevel, iters);
321
d_pyrLK_dense->calc(d_frame0Gray, d_frame1Gray, d_flow);
322
323
// Draw flows
324
namedWindow("PyrLK [Dense] Flow Field", WINDOW_NORMAL);
325
showFlow("PyrLK [Dense] Flow Field", d_flow);
326
}
327
328
waitKey(0);
329
330
return 0;
331
}
332