1
/*M///////////////////////////////////////////////////////////////////////////////////////
3
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5
// By downloading, copying, installing or using the software you agree to this license.
6
// If you do not agree to this license, do not download, install,
7
// copy or use the software.
11
// For Open Source Computer Vision Library
13
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15
// Third party copyrights are property of their respective owners.
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
20
// * Redistribution's of source code must retain the above copyright notice,
21
// this list of conditions and the following disclaimer.
23
// * Redistribution's in binary form must reproduce the above copyright notice,
24
// this list of conditions and the following disclaimer in the documentation
25
// and/or other materials provided with the distribution.
27
// * The name of the copyright holders may not be used to endorse or promote products
28
// derived from this software without specific prior written permission.
30
// This software is provided by the copyright holders and contributors "as is" and
31
// any express or implied warranties, including, but not limited to, the implied
32
// warranties of merchantability and fitness for a particular purpose are disclaimed.
33
// In no event shall the Intel Corporation or contributors be liable for any direct,
34
// indirect, incidental, special, exemplary, or consequential damages
35
// (including, but not limited to, procurement of substitute goods or services;
36
// loss of use, data, or profits; or business interruption) however caused
37
// and on any theory of liability, whether in contract, strict liability,
38
// or tort (including negligence or otherwise) arising in any way out of
39
// the use of this software, even if advised of the possibility of such damage.
43
#include "precomp.hpp"
46
using namespace cv::cuda;
48
#if !defined HAVE_CUDA || defined(CUDA_DISABLER)
50
Ptr<FarnebackOpticalFlow> cv::cuda::FarnebackOpticalFlow::create(int, double, bool, int, int, int, double, int) { throw_no_cuda(); return Ptr<FarnebackOpticalFlow>(); }
56
// CUDA resize() is fast, but it differs from the CPU analog. Disabling this flag
57
// leads to an inefficient code. It's for debug purposes only.
58
#define ENABLE_CUDA_RESIZE 1
60
namespace cv { namespace cuda { namespace device { namespace optflow_farneback
62
void setPolynomialExpansionConsts(
63
int polyN, const float *g, const float *xg, const float *xxg,
64
float ig11, float ig03, float ig33, float ig55);
66
void polynomialExpansionGpu(const PtrStepSzf &src, int polyN, PtrStepSzf dst, cudaStream_t stream);
68
void setUpdateMatricesConsts();
70
void updateMatricesGpu(
71
const PtrStepSzf flowx, const PtrStepSzf flowy, const PtrStepSzf R0, const PtrStepSzf R1,
72
PtrStepSzf M, cudaStream_t stream);
75
const PtrStepSzf M, PtrStepSzf flowx, PtrStepSzf flowy, cudaStream_t stream);
77
void boxFilter5Gpu(const PtrStepSzf src, int ksizeHalf, PtrStepSzf dst, cudaStream_t stream);
79
void boxFilter5Gpu_CC11(const PtrStepSzf src, int ksizeHalf, PtrStepSzf dst, cudaStream_t stream);
81
void setGaussianBlurKernel(const float *gKer, int ksizeHalf);
84
const PtrStepSzf src, int ksizeHalf, PtrStepSzf dst, int borderType, cudaStream_t stream);
86
void gaussianBlur5Gpu(
87
const PtrStepSzf src, int ksizeHalf, PtrStepSzf dst, int borderType, cudaStream_t stream);
89
void gaussianBlur5Gpu_CC11(
90
const PtrStepSzf src, int ksizeHalf, PtrStepSzf dst, int borderType, cudaStream_t stream);
96
class FarnebackOpticalFlowImpl : public FarnebackOpticalFlow
99
FarnebackOpticalFlowImpl(int numLevels, double pyrScale, bool fastPyramids, int winSize,
100
int numIters, int polyN, double polySigma, int flags) :
101
numLevels_(numLevels), pyrScale_(pyrScale), fastPyramids_(fastPyramids), winSize_(winSize),
102
numIters_(numIters), polyN_(polyN), polySigma_(polySigma), flags_(flags)
106
virtual int getNumLevels() const { return numLevels_; }
107
virtual void setNumLevels(int numLevels) { numLevels_ = numLevels; }
109
virtual double getPyrScale() const { return pyrScale_; }
110
virtual void setPyrScale(double pyrScale) { pyrScale_ = pyrScale; }
112
virtual bool getFastPyramids() const { return fastPyramids_; }
113
virtual void setFastPyramids(bool fastPyramids) { fastPyramids_ = fastPyramids; }
115
virtual int getWinSize() const { return winSize_; }
116
virtual void setWinSize(int winSize) { winSize_ = winSize; }
118
virtual int getNumIters() const { return numIters_; }
119
virtual void setNumIters(int numIters) { numIters_ = numIters; }
121
virtual int getPolyN() const { return polyN_; }
122
virtual void setPolyN(int polyN) { polyN_ = polyN; }
124
virtual double getPolySigma() const { return polySigma_; }
125
virtual void setPolySigma(double polySigma) { polySigma_ = polySigma; }
127
virtual int getFlags() const { return flags_; }
128
virtual void setFlags(int flags) { flags_ = flags; }
130
virtual void calc(InputArray I0, InputArray I1, InputOutputArray flow, Stream& stream);
143
void prepareGaussian(
144
int n, double sigma, float *g, float *xg, float *xxg,
145
double &ig11, double &ig03, double &ig33, double &ig55);
147
void setPolynomialExpansionConsts(int n, double sigma);
149
void updateFlow_boxFilter(
150
const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat &flowy,
151
GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);
153
void updateFlow_gaussianBlur(
154
const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat& flowy,
155
GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[]);
157
void calcImpl(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &stream);
160
GpuMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
161
std::vector<GpuMat> pyramid0_, pyramid1_;
164
void FarnebackOpticalFlowImpl::calc(InputArray _frame0, InputArray _frame1, InputOutputArray _flow, Stream& stream)
166
const GpuMat frame0 = _frame0.getGpuMat();
167
const GpuMat frame1 = _frame1.getGpuMat();
169
BufferPool pool(stream);
170
GpuMat flowx = pool.getBuffer(frame0.size(), CV_32FC1);
171
GpuMat flowy = pool.getBuffer(frame0.size(), CV_32FC1);
173
calcImpl(frame0, frame1, flowx, flowy, stream);
175
GpuMat flows[] = {flowx, flowy};
176
cuda::merge(flows, 2, _flow, stream);
179
GpuMat allocMatFromBuf(int rows, int cols, int type, GpuMat& mat)
181
if (!mat.empty() && mat.type() == type && mat.rows >= rows && mat.cols >= cols)
182
return mat(Rect(0, 0, cols, rows));
184
return mat = GpuMat(rows, cols, type);
187
void FarnebackOpticalFlowImpl::prepareGaussian(
188
int n, double sigma, float *g, float *xg, float *xxg,
189
double &ig11, double &ig03, double &ig33, double &ig55)
192
for (int x = -n; x <= n; x++)
194
g[x] = (float)std::exp(-x*x/(2*sigma*sigma));
199
for (int x = -n; x <= n; x++)
201
g[x] = (float)(g[x]*s);
202
xg[x] = (float)(x*g[x]);
203
xxg[x] = (float)(x*x*g[x]);
206
Mat_<double> G(6, 6);
209
for (int y = -n; y <= n; y++)
211
for (int x = -n; x <= n; x++)
214
G(1,1) += g[y]*g[x]*x*x;
215
G(3,3) += g[y]*g[x]*x*x*x*x;
216
G(5,5) += g[y]*g[x]*x*x*y*y;
221
G(2,2) = G(0,3) = G(0,4) = G(3,0) = G(4,0) = G(1,1);
223
G(3,4) = G(4,3) = G(5,5);
232
Mat_<double> invG = G.inv(DECOMP_CHOLESKY);
240
void FarnebackOpticalFlowImpl::setPolynomialExpansionConsts(int n, double sigma)
242
std::vector<float> buf(n*6 + 3);
243
float* g = &buf[0] + n;
244
float* xg = g + n*2 + 1;
245
float* xxg = xg + n*2 + 1;
247
if (sigma < FLT_EPSILON)
250
double ig11, ig03, ig33, ig55;
251
prepareGaussian(n, sigma, g, xg, xxg, ig11, ig03, ig33, ig55);
253
device::optflow_farneback::setPolynomialExpansionConsts(n, g, xg, xxg, static_cast<float>(ig11), static_cast<float>(ig03), static_cast<float>(ig33), static_cast<float>(ig55));
256
void FarnebackOpticalFlowImpl::updateFlow_boxFilter(
257
const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat &flowy,
258
GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[])
260
if (deviceSupports(FEATURE_SET_COMPUTE_12))
261
device::optflow_farneback::boxFilter5Gpu(M, blockSize/2, bufM, StreamAccessor::getStream(streams[0]));
263
device::optflow_farneback::boxFilter5Gpu_CC11(M, blockSize/2, bufM, StreamAccessor::getStream(streams[0]));
266
for (int i = 1; i < 5; ++i)
267
streams[i].waitForCompletion();
268
device::optflow_farneback::updateFlowGpu(M, flowx, flowy, StreamAccessor::getStream(streams[0]));
271
device::optflow_farneback::updateMatricesGpu(flowx, flowy, R0, R1, M, StreamAccessor::getStream(streams[0]));
274
void FarnebackOpticalFlowImpl::updateFlow_gaussianBlur(
275
const GpuMat& R0, const GpuMat& R1, GpuMat& flowx, GpuMat& flowy,
276
GpuMat& M, GpuMat &bufM, int blockSize, bool updateMatrices, Stream streams[])
278
if (deviceSupports(FEATURE_SET_COMPUTE_12))
279
device::optflow_farneback::gaussianBlur5Gpu(
280
M, blockSize/2, bufM, BORDER_REPLICATE, StreamAccessor::getStream(streams[0]));
282
device::optflow_farneback::gaussianBlur5Gpu_CC11(
283
M, blockSize/2, bufM, BORDER_REPLICATE, StreamAccessor::getStream(streams[0]));
286
device::optflow_farneback::updateFlowGpu(M, flowx, flowy, StreamAccessor::getStream(streams[0]));
289
device::optflow_farneback::updateMatricesGpu(flowx, flowy, R0, R1, M, StreamAccessor::getStream(streams[0]));
292
void FarnebackOpticalFlowImpl::calcImpl(const GpuMat &frame0, const GpuMat &frame1, GpuMat &flowx, GpuMat &flowy, Stream &stream)
294
CV_Assert(frame0.channels() == 1 && frame1.channels() == 1);
295
CV_Assert(frame0.size() == frame1.size());
296
CV_Assert(polyN_ == 5 || polyN_ == 7);
297
CV_Assert(!fastPyramids_ || std::abs(pyrScale_ - 0.5) < 1e-6);
303
Size size = frame0.size();
304
GpuMat prevFlowX, prevFlowY, curFlowX, curFlowY;
306
flowx.create(size, CV_32F);
307
flowy.create(size, CV_32F);
308
GpuMat flowx0 = flowx;
309
GpuMat flowy0 = flowy;
311
// Crop unnecessary levels
313
int numLevelsCropped = 0;
314
for (; numLevelsCropped < numLevels_; numLevelsCropped++)
317
if (size.width*scale < MIN_SIZE || size.height*scale < MIN_SIZE)
321
frame0.convertTo(frames_[0], CV_32F, streams[0]);
322
frame1.convertTo(frames_[1], CV_32F, streams[1]);
326
// Build Gaussian pyramids using pyrDown()
327
pyramid0_.resize(numLevelsCropped + 1);
328
pyramid1_.resize(numLevelsCropped + 1);
329
pyramid0_[0] = frames_[0];
330
pyramid1_[0] = frames_[1];
331
for (int i = 1; i <= numLevelsCropped; ++i)
333
cuda::pyrDown(pyramid0_[i - 1], pyramid0_[i], streams[0]);
334
cuda::pyrDown(pyramid1_[i - 1], pyramid1_[i], streams[1]);
338
setPolynomialExpansionConsts(polyN_, polySigma_);
339
device::optflow_farneback::setUpdateMatricesConsts();
341
for (int k = numLevelsCropped; k >= 0; k--)
343
streams[0].waitForCompletion();
346
for (int i = 0; i < k; i++)
349
double sigma = (1./scale - 1) * 0.5;
350
int smoothSize = cvRound(sigma*5) | 1;
351
smoothSize = std::max(smoothSize, 3);
353
int width = cvRound(size.width*scale);
354
int height = cvRound(size.height*scale);
358
width = pyramid0_[k].cols;
359
height = pyramid0_[k].rows;
364
curFlowX.create(height, width, CV_32F);
365
curFlowY.create(height, width, CV_32F);
375
if (flags_ & OPTFLOW_USE_INITIAL_FLOW)
377
cuda::resize(flowx0, curFlowX, Size(width, height), 0, 0, INTER_LINEAR, streams[0]);
378
cuda::resize(flowy0, curFlowY, Size(width, height), 0, 0, INTER_LINEAR, streams[1]);
379
curFlowX.convertTo(curFlowX, curFlowX.depth(), scale, streams[0]);
380
curFlowY.convertTo(curFlowY, curFlowY.depth(), scale, streams[1]);
384
curFlowX.setTo(0, streams[0]);
385
curFlowY.setTo(0, streams[1]);
390
cuda::resize(prevFlowX, curFlowX, Size(width, height), 0, 0, INTER_LINEAR, streams[0]);
391
cuda::resize(prevFlowY, curFlowY, Size(width, height), 0, 0, INTER_LINEAR, streams[1]);
392
curFlowX.convertTo(curFlowX, curFlowX.depth(), 1./pyrScale_, streams[0]);
393
curFlowY.convertTo(curFlowY, curFlowY.depth(), 1./pyrScale_, streams[1]);
396
GpuMat M = allocMatFromBuf(5*height, width, CV_32F, M_);
397
GpuMat bufM = allocMatFromBuf(5*height, width, CV_32F, bufM_);
400
allocMatFromBuf(5*height, width, CV_32F, R_[0]),
401
allocMatFromBuf(5*height, width, CV_32F, R_[1])
406
device::optflow_farneback::polynomialExpansionGpu(pyramid0_[k], polyN_, R[0], StreamAccessor::getStream(streams[0]));
407
device::optflow_farneback::polynomialExpansionGpu(pyramid1_[k], polyN_, R[1], StreamAccessor::getStream(streams[1]));
411
GpuMat blurredFrame[2] =
413
allocMatFromBuf(size.height, size.width, CV_32F, blurredFrame_[0]),
414
allocMatFromBuf(size.height, size.width, CV_32F, blurredFrame_[1])
418
allocMatFromBuf(height, width, CV_32F, pyrLevel_[0]),
419
allocMatFromBuf(height, width, CV_32F, pyrLevel_[1])
422
Mat g = getGaussianKernel(smoothSize, sigma, CV_32F);
423
device::optflow_farneback::setGaussianBlurKernel(g.ptr<float>(smoothSize/2), smoothSize/2);
425
for (int i = 0; i < 2; i++)
427
device::optflow_farneback::gaussianBlurGpu(
428
frames_[i], smoothSize/2, blurredFrame[i], BORDER_REFLECT101, StreamAccessor::getStream(streams[i]));
429
cuda::resize(blurredFrame[i], pyrLevel[i], Size(width, height), 0.0, 0.0, INTER_LINEAR, streams[i]);
430
device::optflow_farneback::polynomialExpansionGpu(pyrLevel[i], polyN_, R[i], StreamAccessor::getStream(streams[i]));
434
streams[1].waitForCompletion();
435
device::optflow_farneback::updateMatricesGpu(curFlowX, curFlowY, R[0], R[1], M, StreamAccessor::getStream(streams[0]));
437
if (flags_ & OPTFLOW_FARNEBACK_GAUSSIAN)
439
Mat g = getGaussianKernel(winSize_, winSize_/2*0.3f, CV_32F);
440
device::optflow_farneback::setGaussianBlurKernel(g.ptr<float>(winSize_/2), winSize_/2);
442
for (int i = 0; i < numIters_; i++)
444
if (flags_ & OPTFLOW_FARNEBACK_GAUSSIAN)
445
updateFlow_gaussianBlur(R[0], R[1], curFlowX, curFlowY, M, bufM, winSize_, i < numIters_-1, streams);
447
updateFlow_boxFilter(R[0], R[1], curFlowX, curFlowY, M, bufM, winSize_, i < numIters_-1, streams);
450
prevFlowX = curFlowX;
451
prevFlowY = curFlowY;
458
streams[0].waitForCompletion();
462
Ptr<FarnebackOpticalFlow> cv::cuda::FarnebackOpticalFlow::create(int numLevels, double pyrScale, bool fastPyramids, int winSize,
463
int numIters, int polyN, double polySigma, int flags)
465
return makePtr<FarnebackOpticalFlowImpl>(numLevels, pyrScale, fastPyramids, winSize,
466
numIters, polyN, polySigma, flags);