pyrlk.cu 26.9 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 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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
/*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.
//
// Copyright (c) 2010, Paul Furgale, Chi Hay Tong
//
// The original code was written by Paul Furgale and Chi Hay Tong 
// and later optimized and prepared for integration into OpenCV by Itseez.
//
//M*/

#include "opencv2/gpu/device/common.hpp"
#include "opencv2/gpu/device/utility.hpp"
#include "opencv2/gpu/device/functional.hpp"
#include "opencv2/gpu/device/limits.hpp"

namespace cv { namespace gpu { namespace device 
{
    namespace pyrlk 
    {
        __constant__ int c_cn;
        __constant__ float c_minEigThreshold;
        __constant__ int c_winSize_x;
        __constant__ int c_winSize_y;
        __constant__ int c_winSize_x_cn;
        __constant__ int c_halfWin_x;
        __constant__ int c_halfWin_y;
        __constant__ int c_iters;

        void loadConstants(int cn, float minEigThreshold, int2 winSize, int iters)
        {
            int2 halfWin = make_int2((winSize.x - 1) / 2, (winSize.y - 1) / 2);            
            cudaSafeCall( cudaMemcpyToSymbol(c_cn, &cn, sizeof(int)) );
            cudaSafeCall( cudaMemcpyToSymbol(c_minEigThreshold, &minEigThreshold, sizeof(float)) );
            cudaSafeCall( cudaMemcpyToSymbol(c_winSize_x, &winSize.x, sizeof(int)) );
            cudaSafeCall( cudaMemcpyToSymbol(c_winSize_y, &winSize.y, sizeof(int)) );
            winSize.x *= cn;
            cudaSafeCall( cudaMemcpyToSymbol(c_winSize_x_cn, &winSize.x, sizeof(int)) );
            cudaSafeCall( cudaMemcpyToSymbol(c_halfWin_x, &halfWin.x, sizeof(int)) );
            cudaSafeCall( cudaMemcpyToSymbol(c_halfWin_y, &halfWin.y, sizeof(int)) );
            cudaSafeCall( cudaMemcpyToSymbol(c_iters, &iters, sizeof(int)) );
        }

        __global__ void calcSharrDeriv_vertical(const PtrStepb src, PtrStep<short> dx_buf, PtrStep<short> dy_buf, int rows, int colsn)
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

            if (y < rows && x < colsn)
            {
                const uchar src_val0 = src(y > 0 ? y - 1 : 1, x);
                const uchar src_val1 = src(y, x);
                const uchar src_val2 = src(y < rows - 1 ? y + 1 : rows - 2, x);
                
                dx_buf(y, x) = (src_val0 + src_val2) * 3 + src_val1 * 10;
                dy_buf(y, x) = src_val2 - src_val0;
            }
        }

        __global__ void calcSharrDeriv_horizontal(const PtrStep<short> dx_buf, const PtrStep<short> dy_buf, PtrStep<short> dIdx, PtrStep<short> dIdy, int rows, int cols)
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

            const int colsn = cols * c_cn;

            if (y < rows && x < colsn)
            {
                const short* dx_buf_row = dx_buf.ptr(y);
                const short* dy_buf_row = dy_buf.ptr(y);

                const int xr = x + c_cn < colsn ? x + c_cn : (cols - 2) * c_cn + x + c_cn - colsn;
                const int xl = x - c_cn >= 0 ? x - c_cn : c_cn + x;

                dIdx(y, x) = dx_buf_row[xr] - dx_buf_row[xl];
                dIdy(y, x) = (dy_buf_row[xr] + dy_buf_row[xl]) * 3 + dy_buf_row[x] * 10;
            }
        }

        void calcSharrDeriv_gpu(DevMem2Db src, DevMem2D_<short> dx_buf, DevMem2D_<short> dy_buf, DevMem2D_<short> dIdx, DevMem2D_<short> dIdy, int cn, 
            cudaStream_t stream)
        {
            dim3 block(32, 8);
            dim3 grid(divUp(src.cols * cn, block.x), divUp(src.rows, block.y));

            calcSharrDeriv_vertical<<<grid, block, 0, stream>>>(src, dx_buf, dy_buf, src.rows, src.cols * cn);
            cudaSafeCall( cudaGetLastError() );

            calcSharrDeriv_horizontal<<<grid, block, 0, stream>>>(dx_buf, dy_buf, dIdx, dIdy, src.rows, src.cols);
            cudaSafeCall( cudaGetLastError() );

            if (stream == 0)
                cudaSafeCall( cudaDeviceSynchronize() );
        }

        #define W_BITS 14
        #define W_BITS1 14

        #define  CV_DESCALE(x, n)     (((x) + (1 << ((n)-1))) >> (n))

        __device__ int linearFilter(const PtrStepb& src, float2 pt, int x, int y)
        {
            int2 ipt;
            ipt.x = __float2int_rd(pt.x);
            ipt.y = __float2int_rd(pt.y);

            float a = pt.x - ipt.x;
            float b = pt.y - ipt.y;

            int iw00 = __float2int_rn((1.0f - a) * (1.0f - b) * (1 << W_BITS));
            int iw01 = __float2int_rn(a * (1.0f - b) * (1 << W_BITS));
            int iw10 = __float2int_rn((1.0f - a) * b * (1 << W_BITS));
            int iw11 = (1 << W_BITS) - iw00 - iw01 - iw10;

            const uchar* src_row = src.ptr(ipt.y + y) + ipt.x * c_cn;
            const uchar* src_row1 = src.ptr(ipt.y + y + 1) + ipt.x * c_cn;

            return CV_DESCALE(src_row[x] * iw00 + src_row[x + c_cn] * iw01 + src_row1[x] * iw10 + src_row1[x + c_cn] * iw11, W_BITS1 - 5);
        }

        __device__ int linearFilter(const PtrStep<short>& src, float2 pt, int x, int y)
        {
            int2 ipt;
            ipt.x = __float2int_rd(pt.x);
            ipt.y = __float2int_rd(pt.y);

            float a = pt.x - ipt.x;
            float b = pt.y - ipt.y;

            int iw00 = __float2int_rn((1.0f - a) * (1.0f - b) * (1 << W_BITS));
            int iw01 = __float2int_rn(a * (1.0f - b) * (1 << W_BITS));
            int iw10 = __float2int_rn((1.0f - a) * b * (1 << W_BITS));
            int iw11 = (1 << W_BITS) - iw00 - iw01 - iw10;

            const short* src_row = src.ptr(ipt.y + y) + ipt.x * c_cn;
            const short* src_row1 = src.ptr(ipt.y + y + 1) + ipt.x * c_cn;

            return CV_DESCALE(src_row[x] * iw00 + src_row[x + c_cn] * iw01 + src_row1[x] * iw10 + src_row1[x + c_cn] * iw11, W_BITS1);
        }

        __device__ void reduce(float& val1, float& val2, float& val3, float* smem1, float* smem2, float* smem3, int tid)
        {
            smem1[tid] = val1;
            smem2[tid] = val2;
            smem3[tid] = val3;
            __syncthreads();

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
184
#if __CUDA_ARCH__ > 110
185 186 187 188 189 190 191
            if (tid < 128) 
            { 
                smem1[tid] = val1 += smem1[tid + 128]; 
                smem2[tid] = val2 += smem2[tid + 128]; 
                smem3[tid] = val3 += smem3[tid + 128]; 
            } 
            __syncthreads();
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
192
#endif
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239

            if (tid < 64) 
            { 
                smem1[tid] = val1 += smem1[tid + 64]; 
                smem2[tid] = val2 += smem2[tid + 64]; 
                smem3[tid] = val3 += smem3[tid + 64];
            } 
            __syncthreads();

            if (tid < 32)
            {
                volatile float* vmem1 = smem1;
                volatile float* vmem2 = smem2;
                volatile float* vmem3 = smem3;

                vmem1[tid] = val1 += vmem1[tid + 32]; 
                vmem2[tid] = val2 += vmem2[tid + 32]; 
                vmem3[tid] = val3 += vmem3[tid + 32];

                vmem1[tid] = val1 += vmem1[tid + 16]; 
                vmem2[tid] = val2 += vmem2[tid + 16]; 
                vmem3[tid] = val3 += vmem3[tid + 16];

                vmem1[tid] = val1 += vmem1[tid + 8]; 
                vmem2[tid] = val2 += vmem2[tid + 8]; 
                vmem3[tid] = val3 += vmem3[tid + 8];

                vmem1[tid] = val1 += vmem1[tid + 4]; 
                vmem2[tid] = val2 += vmem2[tid + 4]; 
                vmem3[tid] = val3 += vmem3[tid + 4];

                vmem1[tid] = val1 += vmem1[tid + 2]; 
                vmem2[tid] = val2 += vmem2[tid + 2]; 
                vmem3[tid] = val3 += vmem3[tid + 2];

                vmem1[tid] = val1 += vmem1[tid + 1]; 
                vmem2[tid] = val2 += vmem2[tid + 1]; 
                vmem3[tid] = val3 += vmem3[tid + 1];
            }
        }

        __device__ void reduce(float& val1, float& val2, float* smem1, float* smem2, int tid)
        {
            smem1[tid] = val1;
            smem2[tid] = val2;
            __syncthreads();

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
240
#if __CUDA_ARCH__ > 110
241 242 243 244 245 246
            if (tid < 128) 
            { 
                smem1[tid] = val1 += smem1[tid + 128]; 
                smem2[tid] = val2 += smem2[tid + 128];  
            } 
            __syncthreads();
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
247
#endif
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

            if (tid < 64) 
            { 
                smem1[tid] = val1 += smem1[tid + 64]; 
                smem2[tid] = val2 += smem2[tid + 64]; 
            } 
            __syncthreads();

            if (tid < 32)
            {
                volatile float* vmem1 = smem1;
                volatile float* vmem2 = smem2;

                vmem1[tid] = val1 += vmem1[tid + 32]; 
                vmem2[tid] = val2 += vmem2[tid + 32]; 

                vmem1[tid] = val1 += vmem1[tid + 16]; 
                vmem2[tid] = val2 += vmem2[tid + 16]; 

                vmem1[tid] = val1 += vmem1[tid + 8]; 
                vmem2[tid] = val2 += vmem2[tid + 8]; 

                vmem1[tid] = val1 += vmem1[tid + 4]; 
                vmem2[tid] = val2 += vmem2[tid + 4]; 

                vmem1[tid] = val1 += vmem1[tid + 2]; 
                vmem2[tid] = val2 += vmem2[tid + 2]; 

                vmem1[tid] = val1 += vmem1[tid + 1]; 
                vmem2[tid] = val2 += vmem2[tid + 1]; 
            }
        }

281 282 283 284 285
        __device__ void reduce(float& val1, float* smem1, int tid)
        {
            smem1[tid] = val1;
            __syncthreads();

Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
286
#if __CUDA_ARCH__ > 110
287 288 289 290 291
            if (tid < 128) 
            { 
                smem1[tid] = val1 += smem1[tid + 128]; 
            } 
            __syncthreads();
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
292
#endif
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312

            if (tid < 64) 
            { 
                smem1[tid] = val1 += smem1[tid + 64]; 
            } 
            __syncthreads();

            if (tid < 32)
            {
                volatile float* vmem1 = smem1;

                vmem1[tid] = val1 += vmem1[tid + 32]; 
                vmem1[tid] = val1 += vmem1[tid + 16]; 
                vmem1[tid] = val1 += vmem1[tid + 8]; 
                vmem1[tid] = val1 += vmem1[tid + 4];
                vmem1[tid] = val1 += vmem1[tid + 2]; 
                vmem1[tid] = val1 += vmem1[tid + 1]; 
            }
        }

313 314
        #define SCALE (1.0f / (1 << 20))

315
        template <int PATCH_X, int PATCH_Y, bool calcErr, bool GET_MIN_EIGENVALS>
316 317 318
        __global__ void lkSparse(const PtrStepb I, const PtrStepb J, const PtrStep<short> dIdx, const PtrStep<short> dIdy,
            const float2* prevPts, float2* nextPts, uchar* status, float* err, const int level, const int rows, const int cols)
        {
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
319 320 321 322 323
#if __CUDA_ARCH__ <= 110
            __shared__ float smem1[128];
            __shared__ float smem2[128];
            __shared__ float smem3[128];
#else
324 325 326
            __shared__ float smem1[256];
            __shared__ float smem2[256];
            __shared__ float smem3[256];
Vadim Pisarevsky's avatar
Vadim Pisarevsky committed
327
#endif
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 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 392 393

            const int tid = threadIdx.y * blockDim.x + threadIdx.x;

            float2 prevPt = prevPts[blockIdx.x];
            prevPt.x *= (1.0f / (1 << level));
            prevPt.y *= (1.0f / (1 << level));

            prevPt.x -= c_halfWin_x;
            prevPt.y -= c_halfWin_y;

            if (prevPt.x < -c_winSize_x || prevPt.x >= cols || prevPt.y < -c_winSize_y || prevPt.y >= rows)
            {
                if (level == 0 && tid == 0)
                {
                    status[blockIdx.x] = 0;

                    if (calcErr) 
                        err[blockIdx.x] = 0;
                }

                return;
            }

            // extract the patch from the first image, compute covariation matrix of derivatives
            
            float A11 = 0;
            float A12 = 0;
            float A22 = 0;

            int I_patch[PATCH_Y][PATCH_X];
            int dIdx_patch[PATCH_Y][PATCH_X];
            int dIdy_patch[PATCH_Y][PATCH_X];

            for (int y = threadIdx.y, i = 0; y < c_winSize_y; y += blockDim.y, ++i)
            {                
                for (int x = threadIdx.x, j = 0; x < c_winSize_x_cn; x += blockDim.x, ++j)
                {
                    I_patch[i][j] = linearFilter(I, prevPt, x, y);

                    int ixval = linearFilter(dIdx, prevPt, x, y);
                    int iyval = linearFilter(dIdy, prevPt, x, y);

                    dIdx_patch[i][j] = ixval;
                    dIdy_patch[i][j] = iyval;
                    
                    A11 += ixval * ixval;
                    A12 += ixval * iyval;
                    A22 += iyval * iyval;
                }
            }

            reduce(A11, A12, A22, smem1, smem2, smem3, tid);
            __syncthreads();

            A11 = smem1[0];
            A12 = smem2[0];
            A22 = smem3[0];
            
            A11 *= SCALE;
            A12 *= SCALE;
            A22 *= SCALE;

            {
                float D = A11 * A22 - A12 * A12;
                float minEig = (A22 + A11 - ::sqrtf((A11 - A22) * (A11 - A22) + 4.f * A12 * A12)) / (2 * c_winSize_x * c_winSize_y);
            
394
                if (calcErr && GET_MIN_EIGENVALS && tid == 0) 
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
                    err[blockIdx.x] = minEig;

                if (minEig < c_minEigThreshold || D < numeric_limits<float>::epsilon())
                {
                    if (level == 0 && tid == 0)
                        status[blockIdx.x] = 0;

                    return;
                }

                D = 1.f / D;
            
                A11 *= D;
                A12 *= D;
                A22 *= D;
            }

            float2 nextPt = nextPts[blockIdx.x];
            nextPt.x *= 2.f;
            nextPt.y *= 2.f; 
            
            nextPt.x -= c_halfWin_x;
            nextPt.y -= c_halfWin_y;

            bool status_ = true;

            for (int k = 0; k < c_iters; ++k)
422
            {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
                if (nextPt.x < -c_winSize_x || nextPt.x >= cols || nextPt.y < -c_winSize_y || nextPt.y >= rows)
                {
                    status_ = false;
                    break;
                }

                float b1 = 0;
                float b2 = 0;
                
                for (int y = threadIdx.y, i = 0; y < c_winSize_y; y += blockDim.y, ++i)
                {
                    for (int x = threadIdx.x, j = 0; x < c_winSize_x_cn; x += blockDim.x, ++j)
                    {
                        int diff = linearFilter(J, nextPt, x, y) - I_patch[i][j];

                        b1 += diff * dIdx_patch[i][j];
                        b2 += diff * dIdy_patch[i][j];
                    }
                }
                
                reduce(b1, b2, smem1, smem2, tid);
                __syncthreads();

                b1 = smem1[0];
                b2 = smem2[0];

                b1 *= SCALE;
                b2 *= SCALE;
                    
                float2 delta;
                delta.x = A12 * b2 - A22 * b1;
                delta.y = A12 * b1 - A11 * b2;
                    
                nextPt.x += delta.x;
                nextPt.y += delta.y;

                if (::fabs(delta.x) < 0.01f && ::fabs(delta.y) < 0.01f)
                    break;
            }

463 464 465 466 467
            if (nextPt.x < -c_winSize_x || nextPt.x >= cols || nextPt.y < -c_winSize_y || nextPt.y >= rows)
                status_ = false;

            float errval = 0.f;
            if (calcErr && !GET_MIN_EIGENVALS && status_)
468
            {
469 470 471 472 473 474 475 476
                for (int y = threadIdx.y, i = 0; y < c_winSize_y; y += blockDim.y, ++i)
                {
                    for (int x = threadIdx.x, j = 0; x < c_winSize_x_cn; x += blockDim.x, ++j)
                    {
                        int diff = linearFilter(J, nextPt, x, y) - I_patch[i][j];
                        errval += ::fabsf((float)diff);
                    }
                }
477

478 479 480 481 482 483 484
                reduce(errval, smem1, tid);

                errval /= 32 * c_winSize_x_cn * c_winSize_y;
            }

            if (tid == 0)
            {
485 486 487
                nextPt.x += c_halfWin_x;
                nextPt.y += c_halfWin_y;

488
                status[blockIdx.x] = status_;
489 490 491 492
                nextPts[blockIdx.x] = nextPt;

                if (calcErr && !GET_MIN_EIGENVALS)
                    err[blockIdx.x] = errval;
493 494 495 496 497
            }
        }

        template <int PATCH_X, int PATCH_Y>
        void lkSparse_caller(DevMem2Db I, DevMem2Db J, DevMem2D_<short> dIdx, DevMem2D_<short> dIdy,
498
            const float2* prevPts, float2* nextPts, uchar* status, float* err, bool GET_MIN_EIGENVALS, int ptcount, 
499 500 501 502
            int level, dim3 block, cudaStream_t stream)
        {
            dim3 grid(ptcount);

503
            if (level == 0 && err)
504
            {
505 506 507 508 509 510 511 512 513 514
                if (GET_MIN_EIGENVALS)
                {
                    cudaSafeCall( cudaFuncSetCacheConfig(lkSparse<PATCH_X, PATCH_Y, true, true>, cudaFuncCachePreferL1) );

                    lkSparse<PATCH_X, PATCH_Y, true, true><<<grid, block>>>(I, J, dIdx, dIdy,
                        prevPts, nextPts, status, err, level, I.rows, I.cols);
                }
                else
                {
                    cudaSafeCall( cudaFuncSetCacheConfig(lkSparse<PATCH_X, PATCH_Y, true, false>, cudaFuncCachePreferL1) );
515

516 517 518
                    lkSparse<PATCH_X, PATCH_Y, true, false><<<grid, block>>>(I, J, dIdx, dIdy,
                        prevPts, nextPts, status, err, level, I.rows, I.cols);
                }
519 520 521
            }
            else
            {
522
                cudaSafeCall( cudaFuncSetCacheConfig(lkSparse<PATCH_X, PATCH_Y, false, false>, cudaFuncCachePreferL1) );
523

524
                lkSparse<PATCH_X, PATCH_Y, false, false><<<grid, block>>>(I, J, dIdx, dIdy,
525 526 527 528 529 530 531 532 533 534
                        prevPts, nextPts, status, err, level, I.rows, I.cols);
            }

            cudaSafeCall( cudaGetLastError() );

            if (stream == 0)
                cudaSafeCall( cudaDeviceSynchronize() );
        }

        void lkSparse_gpu(DevMem2Db I, DevMem2Db J, DevMem2D_<short> dIdx, DevMem2D_<short> dIdy,
535
            const float2* prevPts, float2* nextPts, uchar* status, float* err, bool GET_MIN_EIGENVALS, int ptcount, 
536 537 538
            int level, dim3 block, dim3 patch, cudaStream_t stream)
        {
            typedef void (*func_t)(DevMem2Db I, DevMem2Db J, DevMem2D_<short> dIdx, DevMem2D_<short> dIdy,
539
                const float2* prevPts, float2* nextPts, uchar* status, float* err, bool GET_MIN_EIGENVALS, int ptcount, 
540 541 542 543 544 545 546 547 548 549 550 551
                int level, dim3 block, cudaStream_t stream);

            static const func_t funcs[5][5] = 
            {
                {lkSparse_caller<1, 1>, lkSparse_caller<2, 1>, lkSparse_caller<3, 1>, lkSparse_caller<4, 1>, lkSparse_caller<5, 1>},
                {lkSparse_caller<1, 2>, lkSparse_caller<2, 2>, lkSparse_caller<3, 2>, lkSparse_caller<4, 2>, lkSparse_caller<5, 2>},
                {lkSparse_caller<1, 3>, lkSparse_caller<2, 3>, lkSparse_caller<3, 3>, lkSparse_caller<4, 3>, lkSparse_caller<5, 3>},
                {lkSparse_caller<1, 4>, lkSparse_caller<2, 4>, lkSparse_caller<3, 4>, lkSparse_caller<4, 4>, lkSparse_caller<5, 4>},
                {lkSparse_caller<1, 5>, lkSparse_caller<2, 5>, lkSparse_caller<3, 5>, lkSparse_caller<4, 5>, lkSparse_caller<5, 5>}
            };            

            funcs[patch.y - 1][patch.x - 1](I, J, dIdx, dIdy,
552
                prevPts, nextPts, status, err, GET_MIN_EIGENVALS, ptcount, 
553 554 555
                level, block, stream);
        }

556
        template <bool calcErr, bool GET_MIN_EIGENVALS>
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        __global__ void lkDense(const PtrStepb I, const PtrStepb J, const PtrStep<short> dIdx, const PtrStep<short> dIdy,
            PtrStepf u, PtrStepf v, PtrStepf err, const int rows, const int cols)
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

            if (x >= cols || y >= rows)
                return;

            // extract the patch from the first image, compute covariation matrix of derivatives
            
            float A11 = 0;
            float A12 = 0;
            float A22 = 0;

            for (int i = 0; i < c_winSize_y; ++i)
            {                
                for (int j = 0; j < c_winSize_x; ++j)
                {
                    int ixval = dIdx(y - c_halfWin_y + i, x - c_halfWin_x + j);
                    int iyval = dIdy(y - c_halfWin_y + i, x - c_halfWin_x + j);

                    A11 += ixval * ixval;
                    A12 += ixval * iyval;
                    A22 += iyval * iyval;
                }
            }
            
            A11 *= SCALE;
            A12 *= SCALE;
            A22 *= SCALE;

            {
                float D = A11 * A22 - A12 * A12;
                float minEig = (A22 + A11 - ::sqrtf((A11 - A22) * (A11 - A22) + 4.f * A12 * A12)) / (2 * c_winSize_x * c_winSize_y);

593
                if (calcErr && GET_MIN_EIGENVALS)
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
                    err(y, x) = minEig;
            
                if (minEig < c_minEigThreshold || D < numeric_limits<float>::epsilon())
                    return;

                D = 1.f / D;
            
                A11 *= D;
                A12 *= D;
                A22 *= D;
            }

            float2 nextPt;
            nextPt.x = x - c_halfWin_x + u(y, x);
            nextPt.y = y - c_halfWin_y + v(y, x);

            for (int k = 0; k < c_iters; ++k)
            {
                if (nextPt.x < -c_winSize_x || nextPt.x >= cols || nextPt.y < -c_winSize_y || nextPt.y >= rows)
613
                    return;
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632

                float b1 = 0;
                float b2 = 0;
                
                for (int i = 0; i < c_winSize_y; ++i)
                {
                    for (int j = 0; j < c_winSize_x; ++j)
                    {
                        int I_val = I(y - c_halfWin_y + i, x - c_halfWin_x + j);

                        int diff = linearFilter(J, nextPt, j, i) - CV_DESCALE(I_val * (1 << W_BITS), W_BITS1 - 5);
                        
                        b1 += diff * dIdx(y - c_halfWin_y + i, x - c_halfWin_x + j);
                        b2 += diff * dIdy(y - c_halfWin_y + i, x - c_halfWin_x + j);
                    }
                }

                b1 *= SCALE;
                b2 *= SCALE;
633

634 635 636 637 638 639 640 641 642
                float2 delta;
                delta.x = A12 * b2 - A22 * b1;
                delta.y = A12 * b1 - A11 * b2;
                    
                nextPt.x += delta.x;
                nextPt.y += delta.y;

                if (::fabs(delta.x) < 0.01f && ::fabs(delta.y) < 0.01f)
                    break;
643
            }
644

645 646
            u(y, x) = nextPt.x - x + c_halfWin_x;
            v(y, x) = nextPt.y - y + c_halfWin_y;            
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

            if (calcErr && !GET_MIN_EIGENVALS)
            {
                float errval = 0.0f;

                for (int i = 0; i < c_winSize_y; ++i)
                {
                    for (int j = 0; j < c_winSize_x; ++j)
                    {
                        int I_val = I(y - c_halfWin_y + i, x - c_halfWin_x + j);
                        int diff = linearFilter(J, nextPt, j, i) - CV_DESCALE(I_val * (1 << W_BITS), W_BITS1 - 5);
                        errval += ::fabsf((float)diff);
                    }
                }

                errval /= 32 * c_winSize_x_cn * c_winSize_y;

                err(y, x) = errval;
            }
666 667 668
        }

        void lkDense_gpu(DevMem2Db I, DevMem2Db J, DevMem2D_<short> dIdx, DevMem2D_<short> dIdy, 
669
            DevMem2Df u, DevMem2Df v, DevMem2Df* err, bool GET_MIN_EIGENVALS, cudaStream_t stream)
670 671 672 673 674 675
        {
            dim3 block(32, 8);
            dim3 grid(divUp(I.cols, block.x), divUp(I.rows, block.y));

            if (err)
            {
676 677 678
                if (GET_MIN_EIGENVALS)
                {
                    cudaSafeCall( cudaFuncSetCacheConfig(lkDense<true, true>, cudaFuncCachePreferL1) );
679

680 681 682 683 684 685 686 687 688 689
                    lkDense<true, true><<<grid, block, 0, stream>>>(I, J, dIdx, dIdy, u, v, *err, I.rows, I.cols);
                    cudaSafeCall( cudaGetLastError() );
                }
                else
                {
                    cudaSafeCall( cudaFuncSetCacheConfig(lkDense<true, false>, cudaFuncCachePreferL1) );

                    lkDense<true, false><<<grid, block, 0, stream>>>(I, J, dIdx, dIdy, u, v, *err, I.rows, I.cols);
                    cudaSafeCall( cudaGetLastError() );
                }
690 691 692
            }
            else
            {
693
                cudaSafeCall( cudaFuncSetCacheConfig(lkDense<false, false>, cudaFuncCachePreferL1) );
694

695
                lkDense<false, false><<<grid, block, 0, stream>>>(I, J, dIdx, dIdy, u, v, PtrStepf(), I.rows, I.cols);
696 697 698 699 700 701 702 703
                cudaSafeCall( cudaGetLastError() );
            }

            if (stream == 0)
                cudaSafeCall( cudaDeviceSynchronize() );
        }
    }
}}}