optflowgf.cpp 40.8 KB
Newer Older
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
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
A
Alexander Alekhin 已提交
44
#include "opencl_kernels_video.hpp"
45
#include "opencv2/core/hal/intrin.hpp"
46

47
#if defined __APPLE__ || defined __ANDROID__
48 49 50
#define SMALL_LOCALSIZE
#endif

51 52 53 54 55 56 57 58 59 60
//
// 2D dense optical flow algorithm from the following paper:
// Gunnar Farneback. "Two-Frame Motion Estimation Based on Polynomial Expansion".
// Proceedings of the 13th Scandinavian Conference on Image Analysis, Gothenburg, Sweden
//

namespace cv
{

static void
61 62
FarnebackPrepareGaussian(int n, double sigma, float *g, float *xg, float *xxg,
                         double &ig11, double &ig03, double &ig33, double &ig55)
63 64 65
{
    if( sigma < FLT_EPSILON )
        sigma = n*0.3;
A
Andrey Kamaev 已提交
66

67
    double s = 0.;
68
    for (int x = -n; x <= n; x++)
69 70 71 72
    {
        g[x] = (float)std::exp(-x*x/(2*sigma*sigma));
        s += g[x];
    }
A
Andrey Kamaev 已提交
73

74
    s = 1./s;
75
    for (int x = -n; x <= n; x++)
76 77 78 79 80 81
    {
        g[x] = (float)(g[x]*s);
        xg[x] = (float)(x*g[x]);
        xxg[x] = (float)(x*x*g[x]);
    }

82 83
    Mat_<double> G(6, 6);
    G.setTo(0);
A
Andrey Kamaev 已提交
84

85 86 87
    for (int y = -n; y <= n; y++)
    {
        for (int x = -n; x <= n; x++)
88 89 90 91 92 93
        {
            G(0,0) += g[y]*g[x];
            G(1,1) += g[y]*g[x]*x*x;
            G(3,3) += g[y]*g[x]*x*x*x*x;
            G(5,5) += g[y]*g[x]*x*x*y*y;
        }
94
    }
A
Andrey Kamaev 已提交
95

96 97 98 99 100 101 102 103 104 105 106 107 108
    //G[0][0] = 1.;
    G(2,2) = G(0,3) = G(0,4) = G(3,0) = G(4,0) = G(1,1);
    G(4,4) = G(3,3);
    G(3,4) = G(4,3) = G(5,5);

    // invG:
    // [ x        e  e    ]
    // [    y             ]
    // [       y          ]
    // [ e        z       ]
    // [ e           z    ]
    // [                u ]
    Mat_<double> invG = G.inv(DECOMP_CHOLESKY);
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    ig11 = invG(1,1);
    ig03 = invG(0,3);
    ig33 = invG(3,3);
    ig55 = invG(5,5);
}

static void
FarnebackPolyExp( const Mat& src, Mat& dst, int n, double sigma )
{
    int k, x, y;

    CV_Assert( src.type() == CV_32FC1 );
    int width = src.cols;
    int height = src.rows;
    AutoBuffer<float> kbuf(n*6 + 3), _row((width + n*2)*3);
125
    float* g = kbuf.data() + n;
126 127
    float* xg = g + n*2 + 1;
    float* xxg = xg + n*2 + 1;
128
    float *row = _row.data() + n*3;
129 130 131
    double ig11, ig03, ig33, ig55;

    FarnebackPrepareGaussian(n, sigma, g, xg, xxg, ig11, ig03, ig33, ig55);
132 133

    dst.create( height, width, CV_32FC(5));
A
Andrey Kamaev 已提交
134

135 136 137
    for( y = 0; y < height; y++ )
    {
        float g0 = g[0], g1, g2;
138 139
        const float *srow0 = src.ptr<float>(y), *srow1 = 0;
        float *drow = dst.ptr<float>(y);
A
Andrey Kamaev 已提交
140

141 142 143 144 145 146
        // vertical part of convolution
        for( x = 0; x < width; x++ )
        {
            row[x*3] = srow0[x]*g0;
            row[x*3+1] = row[x*3+2] = 0.f;
        }
A
Andrey Kamaev 已提交
147

148 149 150
        for( k = 1; k <= n; k++ )
        {
            g0 = g[k]; g1 = xg[k]; g2 = xxg[k];
151 152
            srow0 = src.ptr<float>(std::max(y-k,0));
            srow1 = src.ptr<float>(std::min(y+k,height-1));
A
Andrey Kamaev 已提交
153

154 155 156 157 158 159
            for( x = 0; x < width; x++ )
            {
                float p = srow0[x] + srow1[x];
                float t0 = row[x*3] + g0*p;
                float t1 = row[x*3+1] + g1*(srow1[x] - srow0[x]);
                float t2 = row[x*3+2] + g2*p;
A
Andrey Kamaev 已提交
160

161 162 163 164 165
                row[x*3] = t0;
                row[x*3+1] = t1;
                row[x*3+2] = t2;
            }
        }
A
Andrey Kamaev 已提交
166

167 168 169 170 171 172
        // horizontal part of convolution
        for( x = 0; x < n*3; x++ )
        {
            row[-1-x] = row[2-x];
            row[width*3+x] = row[width*3+x-3];
        }
A
Andrey Kamaev 已提交
173

174 175 176 177 178 179
        for( x = 0; x < width; x++ )
        {
            g0 = g[0];
            // r1 ~ 1, r2 ~ x, r3 ~ y, r4 ~ x^2, r5 ~ y^2, r6 ~ xy
            double b1 = row[x*3]*g0, b2 = 0, b3 = row[x*3+1]*g0,
                b4 = 0, b5 = row[x*3+2]*g0, b6 = 0;
A
Andrey Kamaev 已提交
180

181 182 183 184 185 186 187 188 189 190 191
            for( k = 1; k <= n; k++ )
            {
                double tg = row[(x+k)*3] + row[(x-k)*3];
                g0 = g[k];
                b1 += tg*g0;
                b4 += tg*xxg[k];
                b2 += (row[(x+k)*3] - row[(x-k)*3])*xg[k];
                b3 += (row[(x+k)*3+1] + row[(x-k)*3+1])*g0;
                b6 += (row[(x+k)*3+1] - row[(x-k)*3+1])*xg[k];
                b5 += (row[(x+k)*3+2] + row[(x-k)*3+2])*g0;
            }
A
Andrey Kamaev 已提交
192

193 194 195 196 197 198 199 200
            // do not store r1
            drow[x*5+1] = (float)(b2*ig11);
            drow[x*5] = (float)(b3*ig11);
            drow[x*5+3] = (float)(b1*ig03 + b4*ig33);
            drow[x*5+2] = (float)(b1*ig03 + b5*ig33);
            drow[x*5+4] = (float)(b6*ig55);
        }
    }
A
Andrey Kamaev 已提交
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    row -= n*3;
}


/*static void
FarnebackPolyExpPyr( const Mat& src0, Vector<Mat>& pyr, int maxlevel, int n, double sigma )
{
    Vector<Mat> imgpyr;
    buildPyramid( src0, imgpyr, maxlevel );

    for( int i = 0; i <= maxlevel; i++ )
        FarnebackPolyExp( imgpyr[i], pyr[i], n, sigma );
}*/


static void
FarnebackUpdateMatrices( const Mat& _R0, const Mat& _R1, const Mat& _flow, Mat& matM, int _y0, int _y1 )
{
    const int BORDER = 5;
    static const float border[BORDER] = {0.14f, 0.14f, 0.4472f, 0.4472f, 0.4472f};

    int x, y, width = _flow.cols, height = _flow.rows;
224
    const float* R1 = _R1.ptr<float>();
225
    size_t step1 = _R1.step/sizeof(R1[0]);
A
Andrey Kamaev 已提交
226

227 228 229 230
    matM.create(height, width, CV_32FC(5));

    for( y = _y0; y < _y1; y++ )
    {
231 232 233
        const float* flow = _flow.ptr<float>(y);
        const float* R0 = _R0.ptr<float>(y);
        float* M = matM.ptr<float>(y);
A
Andrey Kamaev 已提交
234

235 236 237 238 239 240 241 242 243 244 245
        for( x = 0; x < width; x++ )
        {
            float dx = flow[x*2], dy = flow[x*2+1];
            float fx = x + dx, fy = y + dy;

#if 1
            int x1 = cvFloor(fx), y1 = cvFloor(fy);
            const float* ptr = R1 + y1*step1 + x1*5;
            float r2, r3, r4, r5, r6;

            fx -= x1; fy -= y1;
A
Andrey Kamaev 已提交
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
            if( (unsigned)x1 < (unsigned)(width-1) &&
                (unsigned)y1 < (unsigned)(height-1) )
            {
                float a00 = (1.f-fx)*(1.f-fy), a01 = fx*(1.f-fy),
                      a10 = (1.f-fx)*fy, a11 = fx*fy;

                r2 = a00*ptr[0] + a01*ptr[5] + a10*ptr[step1] + a11*ptr[step1+5];
                r3 = a00*ptr[1] + a01*ptr[6] + a10*ptr[step1+1] + a11*ptr[step1+6];
                r4 = a00*ptr[2] + a01*ptr[7] + a10*ptr[step1+2] + a11*ptr[step1+7];
                r5 = a00*ptr[3] + a01*ptr[8] + a10*ptr[step1+3] + a11*ptr[step1+8];
                r6 = a00*ptr[4] + a01*ptr[9] + a10*ptr[step1+4] + a11*ptr[step1+9];

                r4 = (R0[x*5+2] + r4)*0.5f;
                r5 = (R0[x*5+3] + r5)*0.5f;
                r6 = (R0[x*5+4] + r6)*0.25f;
            }
#else
            int x1 = cvRound(fx), y1 = cvRound(fy);
            const float* ptr = R1 + y1*step1 + x1*5;
            float r2, r3, r4, r5, r6;

            if( (unsigned)x1 < (unsigned)width &&
                (unsigned)y1 < (unsigned)height )
            {
                r2 = ptr[0];
                r3 = ptr[1];
                r4 = (R0[x*5+2] + ptr[2])*0.5f;
                r5 = (R0[x*5+3] + ptr[3])*0.5f;
                r6 = (R0[x*5+4] + ptr[4])*0.25f;
            }
#endif
            else
            {
                r2 = r3 = 0.f;
                r4 = R0[x*5+2];
                r5 = R0[x*5+3];
                r6 = R0[x*5+4]*0.5f;
            }

            r2 = (R0[x*5] - r2)*0.5f;
            r3 = (R0[x*5+1] - r3)*0.5f;

            r2 += r4*dy + r6*dx;
            r3 += r6*dy + r5*dx;

            if( (unsigned)(x - BORDER) >= (unsigned)(width - BORDER*2) ||
                (unsigned)(y - BORDER) >= (unsigned)(height - BORDER*2))
            {
                float scale = (x < BORDER ? border[x] : 1.f)*
                    (x >= width - BORDER ? border[width - x - 1] : 1.f)*
                    (y < BORDER ? border[y] : 1.f)*
                    (y >= height - BORDER ? border[height - y - 1] : 1.f);

                r2 *= scale; r3 *= scale; r4 *= scale;
                r5 *= scale; r6 *= scale;
            }

            M[x*5]   = r4*r4 + r6*r6; // G(1,1)
            M[x*5+1] = (r4 + r5)*r6;  // G(1,2)=G(2,1)
            M[x*5+2] = r5*r5 + r6*r6; // G(2,2)
            M[x*5+3] = r4*r2 + r6*r3; // h(1)
            M[x*5+4] = r6*r2 + r5*r3; // h(2)
        }
    }
}


static void
FarnebackUpdateFlow_Blur( const Mat& _R0, const Mat& _R1,
                          Mat& _flow, Mat& matM, int block_size,
                          bool update_matrices )
{
    int x, y, width = _flow.cols, height = _flow.rows;
    int m = block_size/2;
    int y0 = 0, y1;
    int min_update_stripe = std::max((1 << 10)/width, block_size);
    double scale = 1./(block_size*block_size);
A
Andrey Kamaev 已提交
324

325
    AutoBuffer<double> _vsum((width+m*2+2)*5);
326
    double* vsum = _vsum.data() + (m+1)*5;
327 328

    // init vsum
329
    const float* srow0 = matM.ptr<float>();
330 331 332 333 334
    for( x = 0; x < width*5; x++ )
        vsum[x] = srow0[x]*(m+2);

    for( y = 1; y < m; y++ )
    {
335
        srow0 = matM.ptr<float>(std::min(y,height-1));
336 337 338 339 340 341 342 343
        for( x = 0; x < width*5; x++ )
            vsum[x] += srow0[x];
    }

    // compute blur(G)*flow=blur(h)
    for( y = 0; y < height; y++ )
    {
        double g11, g12, g22, h1, h2;
344
        float* flow = _flow.ptr<float>(y);
345

346 347
        srow0 = matM.ptr<float>(std::max(y-m-1,0));
        const float* srow1 = matM.ptr<float>(std::min(y+m,height-1));
A
Andrey Kamaev 已提交
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
        // vertical blur
        for( x = 0; x < width*5; x++ )
            vsum[x] += srow1[x] - srow0[x];

        // update borders
        for( x = 0; x < (m+1)*5; x++ )
        {
            vsum[-1-x] = vsum[4-x];
            vsum[width*5+x] = vsum[width*5+x-5];
        }

        // init g** and h*
        g11 = vsum[0]*(m+2);
        g12 = vsum[1]*(m+2);
        g22 = vsum[2]*(m+2);
        h1 = vsum[3]*(m+2);
        h2 = vsum[4]*(m+2);

        for( x = 1; x < m; x++ )
        {
            g11 += vsum[x*5];
            g12 += vsum[x*5+1];
            g22 += vsum[x*5+2];
            h1 += vsum[x*5+3];
            h2 += vsum[x*5+4];
        }

        // horizontal blur
        for( x = 0; x < width; x++ )
        {
            g11 += vsum[(x+m)*5] - vsum[(x-m)*5 - 5];
            g12 += vsum[(x+m)*5 + 1] - vsum[(x-m)*5 - 4];
            g22 += vsum[(x+m)*5 + 2] - vsum[(x-m)*5 - 3];
            h1 += vsum[(x+m)*5 + 3] - vsum[(x-m)*5 - 2];
            h2 += vsum[(x+m)*5 + 4] - vsum[(x-m)*5 - 1];

            double g11_ = g11*scale;
            double g12_ = g12*scale;
            double g22_ = g22*scale;
            double h1_ = h1*scale;
            double h2_ = h2*scale;

            double idet = 1./(g11_*g22_ - g12_*g12_+1e-3);
A
Andrey Kamaev 已提交
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
            flow[x*2] = (float)((g11_*h2_-g12_*h1_)*idet);
            flow[x*2+1] = (float)((g22_*h1_-g12_*h2_)*idet);
        }

        y1 = y == height - 1 ? height : y - block_size;
        if( update_matrices && (y1 == height || y1 >= y0 + min_update_stripe) )
        {
            FarnebackUpdateMatrices( _R0, _R1, _flow, matM, y0, y1 );
            y0 = y1;
        }
    }
}


static void
FarnebackUpdateFlow_GaussianBlur( const Mat& _R0, const Mat& _R1,
                                  Mat& _flow, Mat& matM, int block_size,
                                  bool update_matrices )
{
    int x, y, i, width = _flow.cols, height = _flow.rows;
    int m = block_size/2;
    int y0 = 0, y1;
    int min_update_stripe = std::max((1 << 10)/width, block_size);
    double sigma = m*0.3, s = 1;
A
Andrey Kamaev 已提交
417

418
    AutoBuffer<float> _vsum((width+m*2+2)*5 + 16), _hsum(width*5 + 16);
419
    AutoBuffer<float> _kernel((m+1)*5 + 16);
420 421 422 423
    AutoBuffer<const float*> _srow(m*2+1);
    float *vsum = alignPtr(_vsum.data() + (m+1)*5, 16), *hsum = alignPtr(_hsum.data(), 16);
    float* kernel = _kernel.data();
    const float** srow = _srow.data();
424 425 426 427 428 429 430 431 432 433 434 435 436
    kernel[0] = (float)s;

    for( i = 1; i <= m; i++ )
    {
        float t = (float)std::exp(-i*i/(2*sigma*sigma) );
        kernel[i] = t;
        s += t*2;
    }

    s = 1./s;
    for( i = 0; i <= m; i++ )
        kernel[i] = (float)(kernel[i]*s);

437
#if CV_SIMD128
438 439 440
    float* simd_kernel = alignPtr(kernel + m+1, 16);
    {
        for( i = 0; i <= m; i++ )
441
            v_store(simd_kernel + i*4, v_setall_f32(kernel[i]));
442 443 444 445 446 447 448
    }
#endif

    // compute blur(G)*flow=blur(h)
    for( y = 0; y < height; y++ )
    {
        double g11, g12, g22, h1, h2;
449
        float* flow = _flow.ptr<float>(y);
450 451 452 453

        // vertical blur
        for( i = 0; i <= m; i++ )
        {
454 455
            srow[m-i] = matM.ptr<float>(std::max(y-i,0));
            srow[m+i] = matM.ptr<float>(std::min(y+i,height-1));
456 457 458
        }

        x = 0;
459
#if CV_SIMD128
460 461 462 463
        {
            for( ; x <= width*5 - 16; x += 16 )
            {
                const float *sptr0 = srow[m], *sptr1;
464 465 466 467 468 469
                v_float32x4 g4 = v_load(simd_kernel);
                v_float32x4 s0, s1, s2, s3;
                s0 = v_load(sptr0 + x) * g4;
                s1 = v_load(sptr0 + x + 4) * g4;
                s2 = v_load(sptr0 + x + 8) * g4;
                s3 = v_load(sptr0 + x + 12) * g4;
470 471 472

                for( i = 1; i <= m; i++ )
                {
473
                    v_float32x4 x0, x1;
474
                    sptr0 = srow[m+i], sptr1 = srow[m-i];
475 476 477 478 479 480 481 482 483
                    g4 = v_load(simd_kernel + i*4);
                    x0 = v_load(sptr0 + x) + v_load(sptr1 + x);
                    x1 = v_load(sptr0 + x + 4) + v_load(sptr1 + x + 4);
                    s0 = v_muladd(x0, g4, s0);
                    s1 = v_muladd(x1, g4, s1);
                    x0 = v_load(sptr0 + x + 8) + v_load(sptr1 + x + 8);
                    x1 = v_load(sptr0 + x + 12) + v_load(sptr1 + x + 12);
                    s2 = v_muladd(x0, g4, s2);
                    s3 = v_muladd(x1, g4, s3);
484
                }
A
Andrey Kamaev 已提交
485

486 487 488 489
                v_store(vsum + x, s0);
                v_store(vsum + x + 4, s1);
                v_store(vsum + x + 8, s2);
                v_store(vsum + x + 12, s3);
490 491 492 493 494
            }

            for( ; x <= width*5 - 4; x += 4 )
            {
                const float *sptr0 = srow[m], *sptr1;
495 496
                v_float32x4 g4 = v_load(simd_kernel);
                v_float32x4 s0 = v_load(sptr0 + x) * g4;
497 498 499 500

                for( i = 1; i <= m; i++ )
                {
                    sptr0 = srow[m+i], sptr1 = srow[m-i];
501 502 503
                    g4 = v_load(simd_kernel + i*4);
                    v_float32x4 x0 = v_load(sptr0 + x) + v_load(sptr1 + x);
                    s0 = v_muladd(x0, g4, s0);
504
                }
505
                v_store(vsum + x, s0);
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
            }
        }
#endif
        for( ; x < width*5; x++ )
        {
            float s0 = srow[m][x]*kernel[0];
            for( i = 1; i <= m; i++ )
                s0 += (srow[m+i][x] + srow[m-i][x])*kernel[i];
            vsum[x] = s0;
        }

        // update borders
        for( x = 0; x < m*5; x++ )
        {
            vsum[-1-x] = vsum[4-x];
            vsum[width*5+x] = vsum[width*5+x-5];
        }

        // horizontal blur
        x = 0;
526
#if CV_SIMD128
527 528 529
        {
            for( ; x <= width*5 - 8; x += 8 )
            {
530 531 532
                v_float32x4 g4 = v_load(simd_kernel);
                v_float32x4 s0 = v_load(vsum + x) * g4;
                v_float32x4 s1 = v_load(vsum + x + 4) * g4;
533 534 535

                for( i = 1; i <= m; i++ )
                {
536 537 538 539 540
                    g4 = v_load(simd_kernel + i*4);
                    v_float32x4 x0 = v_load(vsum + x - i*5) + v_load(vsum + x+ i*5);
                    v_float32x4 x1 = v_load(vsum + x - i*5 + 4) + v_load(vsum + x+ i*5 + 4);
                    s0 = v_muladd(x0, g4, s0);
                    s1 = v_muladd(x1, g4, s1);
541 542
                }

543 544
                v_store(hsum + x, s0);
                v_store(hsum + x + 4, s1);
545 546 547 548 549
            }
        }
#endif
        for( ; x < width*5; x++ )
        {
A
Andrey Kamaev 已提交
550
            float sum = vsum[x]*kernel[0];
551
            for( i = 1; i <= m; i++ )
A
Andrey Kamaev 已提交
552 553
                sum += kernel[i]*(vsum[x - i*5] + vsum[x + i*5]);
            hsum[x] = sum;
554 555 556 557 558 559 560 561 562 563 564
        }

        for( x = 0; x < width; x++ )
        {
            g11 = hsum[x*5];
            g12 = hsum[x*5+1];
            g22 = hsum[x*5+2];
            h1 = hsum[x*5+3];
            h2 = hsum[x*5+4];

            double idet = 1./(g11*g22 - g12*g12 + 1e-3);
A
Andrey Kamaev 已提交
565

566 567 568 569 570 571 572 573 574 575 576 577 578
            flow[x*2] = (float)((g11*h2-g12*h1)*idet);
            flow[x*2+1] = (float)((g22*h1-g12*h2)*idet);
        }

        y1 = y == height - 1 ? height : y - block_size;
        if( update_matrices && (y1 == height || y1 >= y0 + min_update_stripe) )
        {
            FarnebackUpdateMatrices( _R0, _R1, _flow, matM, y0, y1 );
            y0 = y1;
        }
    }
}

579
}
580

581 582
namespace cv
{
583 584 585
namespace
{
class FarnebackOpticalFlowImpl : public FarnebackOpticalFlow
586 587
{
public:
588 589 590 591
    FarnebackOpticalFlowImpl(int numLevels=5, double pyrScale=0.5, bool fastPyramids=false, int winSize=13,
                             int numIters=10, int polyN=5, double polySigma=1.1, int flags=0) :
        numLevels_(numLevels), pyrScale_(pyrScale), fastPyramids_(fastPyramids), winSize_(winSize),
        numIters_(numIters), polyN_(polyN), polySigma_(polySigma), flags_(flags)
592 593 594
    {
    }

595 596
    virtual int getNumLevels() const CV_OVERRIDE { return numLevels_; }
    virtual void setNumLevels(int numLevels) CV_OVERRIDE { numLevels_ = numLevels; }
597

598 599
    virtual double getPyrScale() const CV_OVERRIDE { return pyrScale_; }
    virtual void setPyrScale(double pyrScale) CV_OVERRIDE { pyrScale_ = pyrScale; }
600

601 602
    virtual bool getFastPyramids() const CV_OVERRIDE { return fastPyramids_; }
    virtual void setFastPyramids(bool fastPyramids) CV_OVERRIDE { fastPyramids_ = fastPyramids; }
603

604 605
    virtual int getWinSize() const CV_OVERRIDE { return winSize_; }
    virtual void setWinSize(int winSize) CV_OVERRIDE { winSize_ = winSize; }
606

607 608
    virtual int getNumIters() const CV_OVERRIDE { return numIters_; }
    virtual void setNumIters(int numIters) CV_OVERRIDE { numIters_ = numIters; }
609

610 611
    virtual int getPolyN() const CV_OVERRIDE { return polyN_; }
    virtual void setPolyN(int polyN) CV_OVERRIDE { polyN_ = polyN; }
612

613 614
    virtual double getPolySigma() const CV_OVERRIDE { return polySigma_; }
    virtual void setPolySigma(double polySigma) CV_OVERRIDE { polySigma_ = polySigma; }
615

616 617
    virtual int getFlags() const CV_OVERRIDE { return flags_; }
    virtual void setFlags(int flags) CV_OVERRIDE { flags_ = flags; }
618

619
    virtual void calc(InputArray I0, InputArray I1, InputOutputArray flow) CV_OVERRIDE;
620

A
amir.tulegenov 已提交
621 622
    virtual String getDefaultName() const CV_OVERRIDE { return "DenseOpticalFlow.FarnebackOpticalFlow"; }

623 624 625 626 627 628 629 630 631
private:
    int numLevels_;
    double pyrScale_;
    bool fastPyramids_;
    int winSize_;
    int numIters_;
    int polyN_;
    double polySigma_;
    int flags_;
632

633
#ifdef HAVE_OPENCL
634
    bool operator ()(const UMat &frame0, const UMat &frame1, UMat &flowx, UMat &flowy)
635 636 637
    {
        CV_Assert(frame0.channels() == 1 && frame1.channels() == 1);
        CV_Assert(frame0.size() == frame1.size());
638 639
        CV_Assert(polyN_ == 5 || polyN_ == 7);
        CV_Assert(!fastPyramids_ || std::abs(pyrScale_ - 0.5) < 1e-6);
640 641 642 643 644 645 646 647 648 649 650 651

        const int min_size = 32;

        Size size = frame0.size();
        UMat prevFlowX, prevFlowY, curFlowX, curFlowY;

        UMat flowx0 = flowx;
        UMat flowy0 = flowy;

        // Crop unnecessary levels
        double scale = 1;
        int numLevelsCropped = 0;
652
        for (; numLevelsCropped < numLevels_; numLevelsCropped++)
653
        {
654
            scale *= pyrScale_;
655 656 657 658 659 660 661
            if (size.width*scale < min_size || size.height*scale < min_size)
                break;
        }

        frame0.convertTo(frames_[0], CV_32F);
        frame1.convertTo(frames_[1], CV_32F);

662
        if (fastPyramids_)
663 664 665 666 667 668 669 670 671 672 673 674 675
        {
            // Build Gaussian pyramids using pyrDown()
            pyramid0_.resize(numLevelsCropped + 1);
            pyramid1_.resize(numLevelsCropped + 1);
            pyramid0_[0] = frames_[0];
            pyramid1_[0] = frames_[1];
            for (int i = 1; i <= numLevelsCropped; ++i)
            {
                pyrDown(pyramid0_[i - 1], pyramid0_[i]);
                pyrDown(pyramid1_[i - 1], pyramid1_[i]);
            }
        }

676
        setPolynomialExpansionConsts(polyN_, polySigma_);
677 678 679 680 681

        for (int k = numLevelsCropped; k >= 0; k--)
        {
            scale = 1;
            for (int i = 0; i < k; i++)
682
                scale *= pyrScale_;
683 684 685 686 687 688 689 690

            double sigma = (1./scale - 1) * 0.5;
            int smoothSize = cvRound(sigma*5) | 1;
            smoothSize = std::max(smoothSize, 3);

            int width = cvRound(size.width*scale);
            int height = cvRound(size.height*scale);

691
            if (fastPyramids_)
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
            {
                width = pyramid0_[k].cols;
                height = pyramid0_[k].rows;
            }

            if (k > 0)
            {
                curFlowX.create(height, width, CV_32F);
                curFlowY.create(height, width, CV_32F);
            }
            else
            {
                curFlowX = flowx0;
                curFlowY = flowy0;
            }

            if (prevFlowX.empty())
            {
710
                if (flags_ & cv::OPTFLOW_USE_INITIAL_FLOW)
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
                {
                    resize(flowx0, curFlowX, Size(width, height), 0, 0, INTER_LINEAR);
                    resize(flowy0, curFlowY, Size(width, height), 0, 0, INTER_LINEAR);
                    multiply(scale, curFlowX, curFlowX);
                    multiply(scale, curFlowY, curFlowY);
                }
                else
                {
                    curFlowX.setTo(0);
                    curFlowY.setTo(0);
                }
            }
            else
            {
                resize(prevFlowX, curFlowX, Size(width, height), 0, 0, INTER_LINEAR);
                resize(prevFlowY, curFlowY, Size(width, height), 0, 0, INTER_LINEAR);
727 728
                multiply(1./pyrScale_, curFlowX, curFlowX);
                multiply(1./pyrScale_, curFlowY, curFlowY);
729 730 731 732 733 734 735 736 737 738
            }

            UMat M = allocMatFromBuf(5*height, width, CV_32F, M_);
            UMat bufM = allocMatFromBuf(5*height, width, CV_32F, bufM_);
            UMat R[2] =
            {
                allocMatFromBuf(5*height, width, CV_32F, R_[0]),
                allocMatFromBuf(5*height, width, CV_32F, R_[1])
            };

739
            if (fastPyramids_)
740
            {
741 742 743 744
                if (!polynomialExpansionOcl(pyramid0_[k], R[0]))
                    return false;
                if (!polynomialExpansionOcl(pyramid1_[k], R[1]))
                    return false;
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
            }
            else
            {
                UMat blurredFrame[2] =
                {
                    allocMatFromBuf(size.height, size.width, CV_32F, blurredFrame_[0]),
                    allocMatFromBuf(size.height, size.width, CV_32F, blurredFrame_[1])
                };
                UMat pyrLevel[2] =
                {
                    allocMatFromBuf(height, width, CV_32F, pyrLevel_[0]),
                    allocMatFromBuf(height, width, CV_32F, pyrLevel_[1])
                };

                setGaussianBlurKernel(smoothSize, sigma);

                for (int i = 0; i < 2; i++)
                {
763 764
                    if (!gaussianBlurOcl(frames_[i], smoothSize/2, blurredFrame[i]))
                        return false;
765
                    resize(blurredFrame[i], pyrLevel[i], Size(width, height), INTER_LINEAR);
766 767
                    if (!polynomialExpansionOcl(pyrLevel[i], R[i]))
                        return false;
768 769 770
                }
            }

771 772
            if (!updateMatricesOcl(curFlowX, curFlowY, R[0], R[1], M))
                return false;
773

774 775 776
            if (flags_ & OPTFLOW_FARNEBACK_GAUSSIAN)
                setGaussianBlurKernel(winSize_, winSize_/2*0.3f);
            for (int i = 0; i < numIters_; i++)
777
            {
778
                if (flags_ & OPTFLOW_FARNEBACK_GAUSSIAN)
779
                {
780
                    if (!updateFlow_gaussianBlur(R[0], R[1], curFlowX, curFlowY, M, bufM, winSize_, i < numIters_-1))
781 782
                        return false;
                }
783
                else
784
                {
785
                    if (!updateFlow_boxFilter(R[0], R[1], curFlowX, curFlowY, M, bufM, winSize_, i < numIters_-1))
786 787
                        return false;
                }
788 789 790 791 792 793 794 795
            }

            prevFlowX = curFlowX;
            prevFlowY = curFlowY;
        }

        flowx = curFlowX;
        flowy = curFlowY;
796
        return true;
797
    }
798
    virtual void collectGarbage() CV_OVERRIDE {
799 800
        releaseMemory();
    }
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
    void releaseMemory()
    {
        frames_[0].release();
        frames_[1].release();
        pyrLevel_[0].release();
        pyrLevel_[1].release();
        M_.release();
        bufM_.release();
        R_[0].release();
        R_[1].release();
        blurredFrame_[0].release();
        blurredFrame_[1].release();
        pyramid0_.clear();
        pyramid1_.clear();
    }
private:
    UMat m_g;
    UMat m_xg;
    UMat m_xxg;

    double m_igd[4];
    float  m_ig[4];
    void setPolynomialExpansionConsts(int n, double sigma)
    {
        std::vector<float> buf(n*6 + 3);
        float* g = &buf[0] + n;
        float* xg = g + n*2 + 1;
        float* xxg = xg + n*2 + 1;

        FarnebackPrepareGaussian(n, sigma, g, xg, xxg, m_igd[0], m_igd[1], m_igd[2], m_igd[3]);

        cv::Mat t_g(1, n + 1, CV_32FC1, g);     t_g.copyTo(m_g);
        cv::Mat t_xg(1, n + 1, CV_32FC1, xg);   t_xg.copyTo(m_xg);
        cv::Mat t_xxg(1, n + 1, CV_32FC1, xxg); t_xxg.copyTo(m_xxg);

        m_ig[0] = static_cast<float>(m_igd[0]);
        m_ig[1] = static_cast<float>(m_igd[1]);
        m_ig[2] = static_cast<float>(m_igd[2]);
        m_ig[3] = static_cast<float>(m_igd[3]);
    }
private:
    UMat m_gKer;
    inline void setGaussianBlurKernel(int smoothSize, double sigma)
    {
        Mat g = getGaussianKernel(smoothSize, sigma, CV_32F);
        Mat gKer(1, smoothSize/2 + 1, CV_32FC1, g.ptr<float>(smoothSize/2));
        gKer.copyTo(m_gKer);
    }
private:
    UMat frames_[2];
    UMat pyrLevel_[2], M_, bufM_, R_[2], blurredFrame_[2];
    std::vector<UMat> pyramid0_, pyramid1_;

    static UMat allocMatFromBuf(int rows, int cols, int type, UMat &mat)
    {
        if (!mat.empty() && mat.type() == type && mat.rows >= rows && mat.cols >= cols)
            return mat(Rect(0, 0, cols, rows));
        return mat = UMat(rows, cols, type);
    }
private:
#define DIVUP(total, grain) (((total) + (grain) - 1) / (grain))

    bool gaussianBlurOcl(const UMat &src, int ksizeHalf, UMat &dst)
    {
865
#ifdef SMALL_LOCALSIZE
866 867 868 869
        size_t localsize[2] = { 128, 1};
#else
        size_t localsize[2] = { 256, 1};
#endif
870
        size_t globalsize[2] = { (size_t)src.cols, (size_t)src.rows};
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
        int smem_size = (int)((localsize[0] + 2*ksizeHalf) * sizeof(float));
        ocl::Kernel kernel;
        if (!kernel.create("gaussianBlur", cv::ocl::video::optical_flow_farneback_oclsrc, ""))
            return false;

        CV_Assert(dst.size() == src.size());
        int idxArg = 0;
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(src));
        idxArg = kernel.set(idxArg, (int)(src.step / src.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
        idxArg = kernel.set(idxArg, (int)(dst.step / dst.elemSize()));
        idxArg = kernel.set(idxArg, dst.rows);
        idxArg = kernel.set(idxArg, dst.cols);
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(m_gKer));
        idxArg = kernel.set(idxArg, (int)ksizeHalf);
I
Ilya Lavrenov 已提交
886
        kernel.set(idxArg, (void *)NULL, smem_size);
887 888 889 890 891
        return kernel.run(2, globalsize, localsize, false);
    }
    bool gaussianBlur5Ocl(const UMat &src, int ksizeHalf, UMat &dst)
    {
        int height = src.rows / 5;
892
#ifdef SMALL_LOCALSIZE
893 894 895 896
        size_t localsize[2] = { 128, 1};
#else
        size_t localsize[2] = { 256, 1};
#endif
897
        size_t globalsize[2] = { (size_t)src.cols, (size_t)height};
898 899 900 901 902 903 904 905 906 907 908 909 910 911
        int smem_size = (int)((localsize[0] + 2*ksizeHalf) * 5 * sizeof(float));
        ocl::Kernel kernel;
        if (!kernel.create("gaussianBlur5", cv::ocl::video::optical_flow_farneback_oclsrc, ""))
            return false;

        int idxArg = 0;
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(src));
        idxArg = kernel.set(idxArg, (int)(src.step / src.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
        idxArg = kernel.set(idxArg, (int)(dst.step / dst.elemSize()));
        idxArg = kernel.set(idxArg, height);
        idxArg = kernel.set(idxArg, src.cols);
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(m_gKer));
        idxArg = kernel.set(idxArg, (int)ksizeHalf);
I
Ilya Lavrenov 已提交
912
        kernel.set(idxArg, (void *)NULL, smem_size);
913 914
        return kernel.run(2, globalsize, localsize, false);
    }
915
    bool polynomialExpansionOcl(const UMat &src, UMat &dst)
916
    {
917
#ifdef SMALL_LOCALSIZE
918 919 920 921
        size_t localsize[2] = { 128, 1};
#else
        size_t localsize[2] = { 256, 1};
#endif
922
        size_t globalsize[2] = { DIVUP((size_t)src.cols, localsize[0] - 2*polyN_) * localsize[0], (size_t)src.rows};
923

V
vbystricky 已提交
924
#if 0
925
        const cv::ocl::Device &device = cv::ocl::Device::getDefault();
926
        bool useDouble = (0 != device.doubleFPConfig());
927

928
        cv::String build_options = cv::format("-D polyN=%d -D USE_DOUBLE=%d", polyN_, useDouble ? 1 : 0);
V
vbystricky 已提交
929
#else
930
        cv::String build_options = cv::format("-D polyN=%d", polyN_);
V
vbystricky 已提交
931
#endif
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
        ocl::Kernel kernel;
        if (!kernel.create("polynomialExpansion", cv::ocl::video::optical_flow_farneback_oclsrc, build_options))
            return false;

        int smem_size = (int)(3 * localsize[0] * sizeof(float));
        int idxArg = 0;
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(src));
        idxArg = kernel.set(idxArg, (int)(src.step / src.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
        idxArg = kernel.set(idxArg, (int)(dst.step / dst.elemSize()));
        idxArg = kernel.set(idxArg, src.rows);
        idxArg = kernel.set(idxArg, src.cols);
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(m_g));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(m_xg));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(m_xxg));
        idxArg = kernel.set(idxArg, (void *)NULL, smem_size);
I
Ilya Lavrenov 已提交
948
        kernel.set(idxArg, (void *)m_ig, 4 * sizeof(float));
949 950 951 952 953
        return kernel.run(2, globalsize, localsize, false);
    }
    bool boxFilter5Ocl(const UMat &src, int ksizeHalf, UMat &dst)
    {
        int height = src.rows / 5;
954
#ifdef SMALL_LOCALSIZE
955 956 957 958
        size_t localsize[2] = { 128, 1};
#else
        size_t localsize[2] = { 256, 1};
#endif
959
        size_t globalsize[2] = { (size_t)src.cols, (size_t)height};
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974

        ocl::Kernel kernel;
        if (!kernel.create("boxFilter5", cv::ocl::video::optical_flow_farneback_oclsrc, ""))
            return false;

        int smem_size = (int)((localsize[0] + 2*ksizeHalf) * 5 * sizeof(float));

        int idxArg = 0;
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(src));
        idxArg = kernel.set(idxArg, (int)(src.step / src.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(dst));
        idxArg = kernel.set(idxArg, (int)(dst.step / dst.elemSize()));
        idxArg = kernel.set(idxArg, height);
        idxArg = kernel.set(idxArg, src.cols);
        idxArg = kernel.set(idxArg, (int)ksizeHalf);
I
Ilya Lavrenov 已提交
975
        kernel.set(idxArg, (void *)NULL, smem_size);
976 977 978 979 980
        return kernel.run(2, globalsize, localsize, false);
    }

    bool updateFlowOcl(const UMat &M, UMat &flowx, UMat &flowy)
    {
981
#ifdef SMALL_LOCALSIZE
982 983 984 985
        size_t localsize[2] = { 32, 4};
#else
        size_t localsize[2] = { 32, 8};
#endif
986
        size_t globalsize[2] = { (size_t)flowx.cols, (size_t)flowx.rows};
987 988 989 990 991 992 993 994 995 996 997 998 999

        ocl::Kernel kernel;
        if (!kernel.create("updateFlow", cv::ocl::video::optical_flow_farneback_oclsrc, ""))
            return false;

        int idxArg = 0;
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(M));
        idxArg = kernel.set(idxArg, (int)(M.step / M.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(flowx));
        idxArg = kernel.set(idxArg, (int)(flowx.step / flowx.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(flowy));
        idxArg = kernel.set(idxArg, (int)(flowy.step / flowy.elemSize()));
        idxArg = kernel.set(idxArg, (int)flowy.rows);
I
Ilya Lavrenov 已提交
1000
        kernel.set(idxArg, (int)flowy.cols);
1001 1002 1003 1004
        return kernel.run(2, globalsize, localsize, false);
    }
    bool updateMatricesOcl(const UMat &flowx, const UMat &flowy, const UMat &R0, const UMat &R1, UMat &M)
    {
1005
#ifdef SMALL_LOCALSIZE
1006 1007 1008 1009
        size_t localsize[2] = { 32, 4};
#else
        size_t localsize[2] = { 32, 8};
#endif
1010
        size_t globalsize[2] = { (size_t)flowx.cols, (size_t)flowx.rows};
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027

        ocl::Kernel kernel;
        if (!kernel.create("updateMatrices", cv::ocl::video::optical_flow_farneback_oclsrc, ""))
            return false;

        int idxArg = 0;
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(flowx));
        idxArg = kernel.set(idxArg, (int)(flowx.step / flowx.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(flowy));
        idxArg = kernel.set(idxArg, (int)(flowy.step / flowy.elemSize()));
        idxArg = kernel.set(idxArg, (int)flowx.rows);
        idxArg = kernel.set(idxArg, (int)flowx.cols);
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(R0));
        idxArg = kernel.set(idxArg, (int)(R0.step / R0.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrReadOnly(R1));
        idxArg = kernel.set(idxArg, (int)(R1.step / R1.elemSize()));
        idxArg = kernel.set(idxArg, ocl::KernelArg::PtrWriteOnly(M));
I
Ilya Lavrenov 已提交
1028
        kernel.set(idxArg, (int)(M.step / M.elemSize()));
1029 1030 1031
        return kernel.run(2, globalsize, localsize, false);
    }

1032
    bool updateFlow_boxFilter(
1033 1034 1035
        const UMat& R0, const UMat& R1, UMat& flowx, UMat &flowy,
        UMat& M, UMat &bufM, int blockSize, bool updateMatrices)
    {
1036 1037
        if (!boxFilter5Ocl(M, blockSize/2, bufM))
            return false;
1038
        swap(M, bufM);
1039 1040
        if (!updateFlowOcl(M, flowx, flowy))
            return false;
1041
        if (updateMatrices)
1042 1043 1044
            if (!updateMatricesOcl(flowx, flowy, R0, R1, M))
                return false;
        return true;
1045
    }
1046
    bool updateFlow_gaussianBlur(
1047 1048 1049
        const UMat& R0, const UMat& R1, UMat& flowx, UMat& flowy,
        UMat& M, UMat &bufM, int blockSize, bool updateMatrices)
    {
1050 1051
        if (!gaussianBlur5Ocl(M, blockSize/2, bufM))
            return false;
1052
        swap(M, bufM);
1053 1054
        if (!updateFlowOcl(M, flowx, flowy))
            return false;
1055
        if (updateMatrices)
1056 1057 1058
            if (!updateMatricesOcl(flowx, flowy, R0, R1, M))
                return false;
        return true;
1059
    }
1060 1061
    bool calc_ocl( InputArray _prev0, InputArray _next0,
                   InputOutputArray _flow0)
1062
    {
1063 1064 1065 1066 1067 1068 1069 1070
        if ((5 != polyN_) && (7 != polyN_))
            return false;
        if (_next0.size() != _prev0.size())
            return false;
        int typePrev = _prev0.type();
        int typeNext = _next0.type();
        if ((1 != CV_MAT_CN(typePrev)) || (1 != CV_MAT_CN(typeNext)))
            return false;
1071

1072
        std::vector<UMat> flowar;
1073 1074 1075 1076 1077 1078 1079

        // If flag is set, check for integrity; if not set, allocate memory space
        if (flags_ & OPTFLOW_USE_INITIAL_FLOW)
        {
            if (_flow0.empty() || _flow0.size() != _prev0.size() || _flow0.channels() != 2 ||
                _flow0.depth() != CV_32F)
                return false;
1080
            split(_flow0, flowar);
1081
        }
1082 1083
        else
        {
1084 1085
            flowar.push_back(UMat(_prev0.size(), CV_32FC1));
            flowar.push_back(UMat(_prev0.size(), CV_32FC1));
1086 1087 1088 1089 1090 1091
        }
        if(!this->operator()(_prev0.getUMat(), _next0.getUMat(), flowar[0], flowar[1])){
            return false;
        }
        merge(flowar, _flow0);
        return true;
1092
    }
1093
#else // HAVE_OPENCL
1094
    virtual void collectGarbage() CV_OVERRIDE {}
1095
#endif
1096
};
1097

1098 1099 1100
void FarnebackOpticalFlowImpl::calc(InputArray _prev0, InputArray _next0,
                                    InputOutputArray _flow0)
{
1101
    CV_INSTRUMENT_REGION();
1102

1103 1104 1105
    CV_OCL_RUN(_flow0.isUMat() &&
               ocl::Image2D::isFormatSupported(CV_32F, 1, false),
               calc_ocl(_prev0,_next0,_flow0))
1106
    Mat prev0 = _prev0.getMat(), next0 = _next0.getMat();
1107 1108 1109 1110 1111
    const int min_size = 32;
    const Mat* img[2] = { &prev0, &next0 };

    int i, k;
    double scale;
1112
    Mat prevFlow, flow, fimg;
1113
    int levels = numLevels_;
1114 1115

    CV_Assert( prev0.size() == next0.size() && prev0.channels() == next0.channels() &&
1116
               prev0.channels() == 1 && pyrScale_ < 1 );
1117 1118 1119 1120 1121 1122 1123 1124

    // If flag is set, check for integrity; if not set, allocate memory space
    if( flags_ & OPTFLOW_USE_INITIAL_FLOW )
        CV_Assert( _flow0.size() == prev0.size() && _flow0.channels() == 2 &&
                   _flow0.depth() == CV_32F );
    else
        _flow0.create( prev0.size(), CV_32FC2 );

1125
    Mat flow0 = _flow0.getMat();
1126 1127 1128

    for( k = 0, scale = 1; k < levels; k++ )
    {
1129
        scale *= pyrScale_;
1130 1131 1132 1133 1134 1135 1136 1137 1138
        if( prev0.cols*scale < min_size || prev0.rows*scale < min_size )
            break;
    }

    levels = k;

    for( k = levels; k >= 0; k-- )
    {
        for( i = 0, scale = 1; i < k; i++ )
1139
            scale *= pyrScale_;
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

        double sigma = (1./scale-1)*0.5;
        int smooth_sz = cvRound(sigma*5)|1;
        smooth_sz = std::max(smooth_sz, 3);

        int width = cvRound(prev0.cols*scale);
        int height = cvRound(prev0.rows*scale);

        if( k > 0 )
            flow.create( height, width, CV_32FC2 );
        else
            flow = flow0;

1153
        if( prevFlow.empty() )
1154
        {
1155
            if( flags_ & OPTFLOW_USE_INITIAL_FLOW )
1156 1157 1158 1159 1160 1161 1162 1163 1164
            {
                resize( flow0, flow, Size(width, height), 0, 0, INTER_AREA );
                flow *= scale;
            }
            else
                flow = Mat::zeros( height, width, CV_32FC2 );
        }
        else
        {
1165
            resize( prevFlow, flow, Size(width, height), 0, 0, INTER_LINEAR );
1166
            flow *= 1./pyrScale_;
1167 1168 1169 1170 1171 1172 1173
        }

        Mat R[2], I, M;
        for( i = 0; i < 2; i++ )
        {
            img[i]->convertTo(fimg, CV_32F);
            GaussianBlur(fimg, fimg, Size(smooth_sz, smooth_sz), sigma, sigma);
1174
            resize( fimg, I, Size(width, height), INTER_LINEAR );
1175
            FarnebackPolyExp( I, R[i], polyN_, polySigma_ );
1176
        }
A
Andrey Kamaev 已提交
1177

1178 1179
        FarnebackUpdateMatrices( R[0], R[1], flow, M, 0, flow.rows );

1180
        for( i = 0; i < numIters_; i++ )
1181
        {
1182 1183
            if( flags_ & OPTFLOW_FARNEBACK_GAUSSIAN )
                FarnebackUpdateFlow_GaussianBlur( R[0], R[1], flow, M, winSize_, i < numIters_ - 1 );
1184
            else
1185
                FarnebackUpdateFlow_Blur( R[0], R[1], flow, M, winSize_, i < numIters_ - 1 );
1186 1187 1188 1189 1190
        }

        prevFlow = flow;
    }
}
1191 1192 1193 1194 1195 1196 1197
} // namespace
} // namespace cv

void cv::calcOpticalFlowFarneback( InputArray _prev0, InputArray _next0,
                               InputOutputArray _flow0, double pyr_scale, int levels, int winsize,
                               int iterations, int poly_n, double poly_sigma, int flags )
{
1198
    CV_INSTRUMENT_REGION();
1199

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
    Ptr<cv::FarnebackOpticalFlow> optflow;
    optflow = makePtr<FarnebackOpticalFlowImpl>(levels,pyr_scale,false,winsize,iterations,poly_n,poly_sigma,flags);
    optflow->calc(_prev0,_next0,_flow0);
}


cv::Ptr<cv::FarnebackOpticalFlow> cv::FarnebackOpticalFlow::create(int numLevels, double pyrScale, bool fastPyramids, int winSize,
                                                               int numIters, int polyN, double polySigma, int flags)
{
    return makePtr<FarnebackOpticalFlowImpl>(numLevels, pyrScale, fastPyramids, winSize,
                                             numIters, polyN, polySigma, flags);
}