bf_match.cu 38.0 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
/*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 bpied warranties, including, but not limited to, the bpied
// 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 "internal_shared.hpp"
#include "opencv2/gpu/device/limits.hpp"
#include "opencv2/gpu/device/vec_distance.hpp"

using namespace cv::gpu;
using namespace cv::gpu::device;

50
namespace cv { namespace gpu { namespace bf_match
51
{
52 53 54 55 56
    ///////////////////////////////////////////////////////////////////////////////
    // Reduction

    template <int BLOCK_SIZE> 
    __device__ void findBestMatch(float& bestDistance, int& bestTrainIdx, float* s_distance, int* s_trainIdx)
57
    {
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
        s_distance += threadIdx.y * BLOCK_SIZE;
        s_trainIdx += threadIdx.y * BLOCK_SIZE;

        s_distance[threadIdx.x] = bestDistance;
        s_trainIdx[threadIdx.x] = bestTrainIdx;

        __syncthreads();

        reducePredVal<BLOCK_SIZE>(s_distance, bestDistance, s_trainIdx, bestTrainIdx, threadIdx.x, less<volatile float>());
    }

    template <int BLOCK_SIZE> 
    __device__ void findBestMatch(float& bestDistance, int& bestTrainIdx, int& bestImgIdx, float* s_distance, int* s_trainIdx, int* s_imgIdx)
    {
        s_distance += threadIdx.y * BLOCK_SIZE;
        s_trainIdx += threadIdx.y * BLOCK_SIZE;
        s_imgIdx   += threadIdx.y * BLOCK_SIZE;

        s_distance[threadIdx.x] = bestDistance;
        s_trainIdx[threadIdx.x] = bestTrainIdx;
        s_imgIdx  [threadIdx.x] = bestImgIdx;

80 81
        __syncthreads();

82
        reducePredVal2<BLOCK_SIZE>(s_distance, bestDistance, s_trainIdx, bestTrainIdx, s_imgIdx, bestImgIdx, threadIdx.x, less<volatile float>());
83 84
    }

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    ///////////////////////////////////////////////////////////////////////////////
    // Match Unrolled Cached

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename T, typename U> 
    __device__ void loadQueryToSmem(int queryIdx, const DevMem2D_<T>& query, U* s_query)
    {
        #pragma unroll
        for (int i = 0; i < MAX_DESC_LEN / BLOCK_SIZE; ++i)
        {
            const int loadX = threadIdx.x + i * BLOCK_SIZE;
            s_query[threadIdx.y * MAX_DESC_LEN + loadX] = loadX < query.cols ? query.ptr(min(queryIdx, query.rows - 1))[loadX] : 0;
        }
    }

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    __device__ void loopUnrolledCached(int queryIdx, const DevMem2D_<T>& query, int imgIdx, const DevMem2D_<T>& train, const Mask& mask, 
                                       typename Dist::value_type* s_query, typename Dist::value_type* s_train, 
                                       float& bestDistance, int& bestTrainIdx, int& bestImgIdx)
103
    {
104
        for (int t = 0, endt = (train.rows + BLOCK_SIZE - 1) / BLOCK_SIZE; t < endt; ++t)
105
        {
106 107 108 109
            Dist dist;

            #pragma unroll
            for (int i = 0; i < MAX_DESC_LEN / BLOCK_SIZE; ++i)
110
            {
111
                const int loadX = threadIdx.x + i * BLOCK_SIZE;
112

113
                s_train[threadIdx.x * BLOCK_SIZE + threadIdx.y] = loadX < train.cols ? train.ptr(min(t * BLOCK_SIZE + threadIdx.y, train.rows - 1))[loadX] : 0;
114

115
                __syncthreads();
116

117 118 119
                #pragma unroll
                for (int j = 0; j < BLOCK_SIZE; ++j)
                    dist.reduceIter(s_query[threadIdx.y * MAX_DESC_LEN + i * BLOCK_SIZE + j], s_train[j * BLOCK_SIZE + threadIdx.x]);
120

121 122 123 124 125 126 127 128 129 130 131 132
                __syncthreads();
            }

            typename Dist::result_type distVal = dist;

            const int trainIdx = t * BLOCK_SIZE + threadIdx.x;

            if (queryIdx < query.rows && trainIdx < train.rows && distVal < bestDistance && mask(queryIdx, trainIdx))
            {
                bestImgIdx = imgIdx;
                bestDistance = distVal;
                bestTrainIdx = trainIdx;
133 134 135 136
            }
        }
    }

137 138
    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    __global__ void matchUnrolledCached(const DevMem2D_<T> query, const DevMem2D_<T> train, const Mask mask, int* bestTrainIdx, float* bestDistance)
139
    {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        extern __shared__ int smem[];

        const int queryIdx = blockIdx.x * BLOCK_SIZE + threadIdx.y;

        typename Dist::value_type* s_query = (typename Dist::value_type*)(smem);
        typename Dist::value_type* s_train = (typename Dist::value_type*)(smem + BLOCK_SIZE * MAX_DESC_LEN);

        loadQueryToSmem<BLOCK_SIZE, MAX_DESC_LEN>(queryIdx, query, s_query);

        float myBestDistance = numeric_limits<float>::max();
        int myBestTrainIdx = -1;

        loopUnrolledCached<BLOCK_SIZE, MAX_DESC_LEN, Dist>(queryIdx, query, 0, train, mask, s_query, s_train, myBestDistance, myBestTrainIdx, myBestTrainIdx);

        __syncthreads();

        float* s_distance = (float*)(smem);
        int* s_trainIdx = (int*)(smem + BLOCK_SIZE * BLOCK_SIZE);

        findBestMatch<BLOCK_SIZE>(myBestDistance, myBestTrainIdx, s_distance, s_trainIdx);
160

161
        if (queryIdx < query.rows && threadIdx.x == 0)
162
        {
163 164
            bestTrainIdx[queryIdx] = myBestTrainIdx;
            bestDistance[queryIdx] = myBestDistance;
165
        }
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    }

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    void matchUnrolledCached(const DevMem2D_<T>& query, const DevMem2D_<T>& train, const Mask& mask, 
                             const DevMem2Di& trainIdx, const DevMem2Df& distance, 
                             cudaStream_t stream)
    {
        const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
        const dim3 grid(divUp(query.rows, BLOCK_SIZE));

        const size_t smemSize = (BLOCK_SIZE * (MAX_DESC_LEN >= BLOCK_SIZE ? MAX_DESC_LEN : BLOCK_SIZE) + BLOCK_SIZE * BLOCK_SIZE) * sizeof(int);

        matchUnrolledCached<BLOCK_SIZE, MAX_DESC_LEN, Dist><<<grid, block, smemSize, stream>>>(query, train, mask, trainIdx.data, distance.data);
        cudaSafeCall( cudaGetLastError() );

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

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    __global__ void matchUnrolledCached(const DevMem2D_<T> query, const DevMem2D_<T>* trains, int n, const Mask mask, 
                                        int* bestTrainIdx, int* bestImgIdx, float* bestDistance)
    {
        extern __shared__ int smem[];

        const int queryIdx = blockIdx.x * BLOCK_SIZE + threadIdx.y;
192

193 194 195 196 197 198 199 200 201 202 203 204
        typename Dist::value_type* s_query = (typename Dist::value_type*)(smem);
        typename Dist::value_type* s_train = (typename Dist::value_type*)(smem + BLOCK_SIZE * MAX_DESC_LEN);

        loadQueryToSmem<BLOCK_SIZE, MAX_DESC_LEN>(queryIdx, query, s_query);

        float myBestDistance = numeric_limits<float>::max();
        int myBestTrainIdx = -1;
        int myBestImgIdx = -1;

        Mask m = mask;

        for (int imgIdx = 0; imgIdx < n; ++imgIdx)
205
        {
206 207 208
            const DevMem2D_<T> train = trains[imgIdx];
            m.next();
            loopUnrolledCached<BLOCK_SIZE, MAX_DESC_LEN, Dist>(queryIdx, query, imgIdx, train, m, s_query, s_train, myBestDistance, myBestTrainIdx, myBestImgIdx);
209 210
        }

211 212 213 214 215 216 217 218 219
        __syncthreads();

        float* s_distance = (float*)(smem);
        int* s_trainIdx = (int*)(smem + BLOCK_SIZE * BLOCK_SIZE);
        int* s_imgIdx = (int*)(smem + 2 * BLOCK_SIZE * BLOCK_SIZE);

        findBestMatch<BLOCK_SIZE>(myBestDistance, myBestTrainIdx, myBestImgIdx, s_distance, s_trainIdx, s_imgIdx);

        if (queryIdx < query.rows && threadIdx.x == 0)
220
        {
221 222 223
            bestTrainIdx[queryIdx] = myBestTrainIdx;
            bestImgIdx[queryIdx] = myBestImgIdx;
            bestDistance[queryIdx] = myBestDistance;
224
        }
225 226 227 228 229 230 231 232 233 234 235
    }

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    void matchUnrolledCached(const DevMem2D_<T>& query, const DevMem2D_<T>* trains, int n, const Mask& mask, 
                             const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
                             cudaStream_t stream)
    {
        const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
        const dim3 grid(divUp(query.rows, BLOCK_SIZE));

        const size_t smemSize = (BLOCK_SIZE * (MAX_DESC_LEN >= 2 * BLOCK_SIZE ? MAX_DESC_LEN : 2 * BLOCK_SIZE) + BLOCK_SIZE * BLOCK_SIZE) * sizeof(int);
236

237 238 239 240 241 242 243 244 245
        matchUnrolledCached<BLOCK_SIZE, MAX_DESC_LEN, Dist><<<grid, block, smemSize, stream>>>(query, trains, n, mask, trainIdx.data, imgIdx.data, distance.data);
        cudaSafeCall( cudaGetLastError() );

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

    ///////////////////////////////////////////////////////////////////////////////
    // Match Unrolled
246

247 248 249 250
    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    __device__ void loopUnrolled(int queryIdx, const DevMem2D_<T>& query, int imgIdx, const DevMem2D_<T>& train, const Mask& mask, 
                                 typename Dist::value_type* s_query, typename Dist::value_type* s_train, 
                                 float& bestDistance, int& bestTrainIdx, int& bestImgIdx)
251
    {
252
        for (int t = 0, endt = (train.rows + BLOCK_SIZE - 1) / BLOCK_SIZE; t < endt; ++t)
253
        {
254
            Dist dist;
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
            #pragma unroll
            for (int i = 0; i < MAX_DESC_LEN / BLOCK_SIZE; ++i)
            {
                const int loadX = threadIdx.x + i * BLOCK_SIZE;

                if (loadX < query.cols)
                {
                    s_query[threadIdx.y * BLOCK_SIZE + threadIdx.x] = query.ptr(min(queryIdx, query.rows - 1))[loadX];
                    s_train[threadIdx.x * BLOCK_SIZE + threadIdx.y] = train.ptr(min(t * BLOCK_SIZE + threadIdx.y, train.rows - 1))[loadX];
                }
                else
                {                
                    s_query[threadIdx.y * BLOCK_SIZE + threadIdx.x] = 0;
                    s_train[threadIdx.x * BLOCK_SIZE + threadIdx.y] = 0;
                }

                __syncthreads();

                #pragma unroll
                for (int j = 0; j < BLOCK_SIZE; ++j)
                    dist.reduceIter(s_query[threadIdx.y * BLOCK_SIZE + j], s_train[j * BLOCK_SIZE + threadIdx.x]);

                __syncthreads();
            }

            typename Dist::result_type distVal = dist;

            const int trainIdx = t * BLOCK_SIZE + threadIdx.x;

            if (queryIdx < query.rows && trainIdx < train.rows && distVal < bestDistance && mask(queryIdx, trainIdx))
286
            {
287 288 289
                bestImgIdx = imgIdx;
                bestDistance = distVal;
                bestTrainIdx = trainIdx;
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 324 325 326 327 328 329 330 331
    }

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask>
    __global__ void matchUnrolled(const DevMem2D_<T> query, const DevMem2D_<T> train, const Mask mask, int* bestTrainIdx, float* bestDistance)
    {
        extern __shared__ int smem[];

        const int queryIdx = blockIdx.x * BLOCK_SIZE + threadIdx.y;

        float myBestDistance = numeric_limits<float>::max();
        int myBestTrainIdx = -1;

        typename Dist::value_type* s_query = (typename Dist::value_type*)(smem);
        typename Dist::value_type* s_train = (typename Dist::value_type*)(smem + BLOCK_SIZE * BLOCK_SIZE);
        
        loopUnrolled<BLOCK_SIZE, MAX_DESC_LEN, Dist>(queryIdx, query, 0, train, mask, s_query, s_train, myBestDistance, myBestTrainIdx, myBestTrainIdx);

        __syncthreads();

        float* s_distance = (float*)(smem);
        int* s_trainIdx = (int*)(smem + BLOCK_SIZE * BLOCK_SIZE);

        findBestMatch<BLOCK_SIZE>(myBestDistance, myBestTrainIdx, s_distance, s_trainIdx);

        if (queryIdx < query.rows && threadIdx.x == 0)
        {
            bestTrainIdx[queryIdx] = myBestTrainIdx;
            bestDistance[queryIdx] = myBestDistance;
        }
    }

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    void matchUnrolled(const DevMem2D_<T>& query, const DevMem2D_<T>& train, const Mask& mask, 
                       const DevMem2Di& trainIdx, const DevMem2Df& distance, 
                       cudaStream_t stream)
    {
        const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
        const dim3 grid(divUp(query.rows, BLOCK_SIZE));

        const size_t smemSize = (2 * BLOCK_SIZE * BLOCK_SIZE) * sizeof(int);
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
        matchUnrolled<BLOCK_SIZE, MAX_DESC_LEN, Dist><<<grid, block, smemSize, stream>>>(query, train, mask, trainIdx.data, distance.data);
        cudaSafeCall( cudaGetLastError() );

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

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask>
    __global__ void matchUnrolled(const DevMem2D_<T> query, const DevMem2D_<T>* trains, int n, const Mask mask, 
                                  int* bestTrainIdx, int* bestImgIdx, float* bestDistance)
    {
        extern __shared__ int smem[];

        const int queryIdx = blockIdx.x * BLOCK_SIZE + threadIdx.y;

        float myBestDistance = numeric_limits<float>::max();
        int myBestTrainIdx = -1;
        int myBestImgIdx = -1;

        typename Dist::value_type* s_query = (typename Dist::value_type*)(smem);
        typename Dist::value_type* s_train = (typename Dist::value_type*)(smem + BLOCK_SIZE * BLOCK_SIZE);

        Mask m = mask;
        
        for (int imgIdx = 0; imgIdx < n; ++imgIdx)
358
        {
359 360 361
            const DevMem2D_<T> train = trains[imgIdx];
            m.next();
            loopUnrolled<BLOCK_SIZE, MAX_DESC_LEN, Dist>(queryIdx, query, imgIdx, train, m, s_query, s_train, myBestDistance, myBestTrainIdx, myBestImgIdx);
362 363
        }

364 365 366 367 368 369 370 371 372
        __syncthreads();

        float* s_distance = (float*)(smem);
        int* s_trainIdx = (int*)(smem + BLOCK_SIZE * BLOCK_SIZE);
        int* s_imgIdxIdx = (int*)(smem + 2 * BLOCK_SIZE * BLOCK_SIZE);

        findBestMatch<BLOCK_SIZE>(myBestDistance, myBestTrainIdx, myBestImgIdx, s_distance, s_trainIdx, s_imgIdxIdx);

        if (queryIdx < query.rows && threadIdx.x == 0)
373
        {
374 375 376
            bestTrainIdx[queryIdx] = myBestTrainIdx;
            bestImgIdx[queryIdx] = myBestImgIdx;
            bestDistance[queryIdx] = myBestDistance;
377
        }
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    }

    template <int BLOCK_SIZE, int MAX_DESC_LEN, typename Dist, typename T, typename Mask> 
    void matchUnrolled(const DevMem2D_<T>& query, const DevMem2D_<T>* trains, int n, const Mask& mask, 
                       const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
                       cudaStream_t stream)
    {
        const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
        const dim3 grid(divUp(query.rows, BLOCK_SIZE));

        const size_t smemSize = (3 * BLOCK_SIZE * BLOCK_SIZE) * sizeof(int);

        matchUnrolled<BLOCK_SIZE, MAX_DESC_LEN, Dist><<<grid, block, smemSize, stream>>>(query, trains, n, mask, trainIdx.data, imgIdx.data, distance.data);
        cudaSafeCall( cudaGetLastError() );

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

397 398
    ///////////////////////////////////////////////////////////////////////////////
    // Match
399

400 401 402 403
    template <int BLOCK_SIZE, typename Dist, typename T, typename Mask> 
    __device__ void loop(int queryIdx, const DevMem2D_<T>& query, int imgIdx, const DevMem2D_<T>& train, const Mask& mask, 
                         typename Dist::value_type* s_query, typename Dist::value_type* s_train, 
                         float& bestDistance, int& bestTrainIdx, int& bestImgIdx)
404
    {
405 406 407
        for (int t = 0, endt = (train.rows + BLOCK_SIZE - 1) / BLOCK_SIZE; t < endt; ++t)
        {
            Dist dist;
408

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
            for (int i = 0, endi = (query.cols + BLOCK_SIZE - 1) / BLOCK_SIZE; i < endi; ++i)
            {
                const int loadX = threadIdx.x + i * BLOCK_SIZE;

                if (loadX < query.cols)
                {
                    s_query[threadIdx.y * BLOCK_SIZE + threadIdx.x] = query.ptr(min(queryIdx, query.rows - 1))[loadX];
                    s_train[threadIdx.x * BLOCK_SIZE + threadIdx.y] = train.ptr(min(t * BLOCK_SIZE + threadIdx.y, train.rows - 1))[loadX];
                }
                else
                {                
                    s_query[threadIdx.y * BLOCK_SIZE + threadIdx.x] = 0;
                    s_train[threadIdx.x * BLOCK_SIZE + threadIdx.y] = 0;
                }

                __syncthreads();

                #pragma unroll
                for (int j = 0; j < BLOCK_SIZE; ++j)
                    dist.reduceIter(s_query[threadIdx.y * BLOCK_SIZE + j], s_train[j * BLOCK_SIZE + threadIdx.x]);

                __syncthreads();
            }
432

433
            typename Dist::result_type distVal = dist;
434

435 436 437 438 439 440 441 442 443
            const int trainIdx = t * BLOCK_SIZE + threadIdx.x;

            if (queryIdx < query.rows && trainIdx < train.rows && distVal < bestDistance && mask(queryIdx, trainIdx))
            {
                bestImgIdx = imgIdx;
                bestDistance = distVal;
                bestTrainIdx = trainIdx;
            }
        }
444 445
    }

446 447
    template <int BLOCK_SIZE, typename Dist, typename T, typename Mask>
    __global__ void match(const DevMem2D_<T> query, const DevMem2D_<T> train, const Mask mask, int* bestTrainIdx, float* bestDistance)
448
    {
449 450 451 452 453 454 455 456 457
        extern __shared__ int smem[];

        const int queryIdx = blockIdx.x * BLOCK_SIZE + threadIdx.y;

        float myBestDistance = numeric_limits<float>::max();
        int myBestTrainIdx = -1;

        typename Dist::value_type* s_query = (typename Dist::value_type*)(smem);
        typename Dist::value_type* s_train = (typename Dist::value_type*)(smem + BLOCK_SIZE * BLOCK_SIZE);
458
        
459
        loop<BLOCK_SIZE, Dist>(queryIdx, query, 0, train, mask, s_query, s_train, myBestDistance, myBestTrainIdx, myBestTrainIdx);
460 461 462

        __syncthreads();

463 464
        float* s_distance = (float*)(smem);
        int* s_trainIdx = (int*)(smem + BLOCK_SIZE * BLOCK_SIZE);
465

466
        findBestMatch<BLOCK_SIZE>(myBestDistance, myBestTrainIdx, s_distance, s_trainIdx);
467

468 469 470 471 472
        if (queryIdx < query.rows && threadIdx.x == 0)
        {
            bestTrainIdx[queryIdx] = myBestTrainIdx;
            bestDistance[queryIdx] = myBestDistance;
        }
473 474
    }

475 476 477 478
    template <int BLOCK_SIZE, typename Dist, typename T, typename Mask> 
    void match(const DevMem2D_<T>& query, const DevMem2D_<T>& train, const Mask& mask, 
               const DevMem2Di& trainIdx, const DevMem2Df& distance, 
               cudaStream_t stream)
479
    {
480 481
        const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
        const dim3 grid(divUp(query.rows, BLOCK_SIZE));
482

483
        const size_t smemSize = (2 * BLOCK_SIZE * BLOCK_SIZE) * sizeof(int);
484

485
        match<BLOCK_SIZE, Dist><<<grid, block, smemSize, stream>>>(query, train, mask, trainIdx.data, distance.data);
486 487 488 489 490 491
        cudaSafeCall( cudaGetLastError() );

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

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    template <int BLOCK_SIZE, typename Dist, typename T, typename Mask>
    __global__ void match(const DevMem2D_<T> query, const DevMem2D_<T>* trains, int n, const Mask mask, 
                          int* bestTrainIdx, int* bestImgIdx, float* bestDistance)
    {
        extern __shared__ int smem[];

        const int queryIdx = blockIdx.x * BLOCK_SIZE + threadIdx.y;

        float myBestDistance = numeric_limits<float>::max();
        int myBestTrainIdx = -1;
        int myBestImgIdx = -1;

        typename Dist::value_type* s_query = (typename Dist::value_type*)(smem);
        typename Dist::value_type* s_train = (typename Dist::value_type*)(smem + BLOCK_SIZE * BLOCK_SIZE);

        Mask m = mask;
        for (int imgIdx = 0; imgIdx < n; ++imgIdx)
        {
            const DevMem2D_<T> train = trains[imgIdx];
            m.next();
            loop<BLOCK_SIZE, Dist>(queryIdx, query, imgIdx, train, m, s_query, s_train, myBestDistance, myBestTrainIdx, myBestImgIdx);
        }

        __syncthreads();

        float* s_distance = (float*)(smem);
        int* s_trainIdx = (int*)(smem + BLOCK_SIZE * BLOCK_SIZE);
        int* s_imgIdxIdx = (int*)(smem + 2 * BLOCK_SIZE * BLOCK_SIZE);

        findBestMatch<BLOCK_SIZE>(myBestDistance, myBestTrainIdx, myBestImgIdx, s_distance, s_trainIdx, s_imgIdxIdx);

        if (queryIdx < query.rows && threadIdx.x == 0)
        {
            bestTrainIdx[queryIdx] = myBestTrainIdx;
            bestImgIdx[queryIdx] = myBestImgIdx;
            bestDistance[queryIdx] = myBestDistance;
        }
    }

    template <int BLOCK_SIZE, typename Dist, typename T, typename Mask> 
    void match(const DevMem2D_<T>& query, const DevMem2D_<T>* trains, int n, const Mask& mask, 
               const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
               cudaStream_t stream)
535
    {
536 537
        const dim3 block(BLOCK_SIZE, BLOCK_SIZE);
        const dim3 grid(divUp(query.rows, BLOCK_SIZE));
538

539
        const size_t smemSize = (2 * BLOCK_SIZE * BLOCK_SIZE) * sizeof(int);
540

541
        match<BLOCK_SIZE, Dist><<<grid, block, smemSize, stream>>>(query, trains, n, mask, trainIdx.data, imgIdx.data, distance.data);
542 543 544 545 546
        cudaSafeCall( cudaGetLastError() );

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

548
    ///////////////////////////////////////////////////////////////////////////////
549
    // Match dispatcher
550

551 552 553 554
    template <typename Dist, typename T, typename Mask> 
    void matchDispatcher(const DevMem2D_<T>& query, const DevMem2D_<T>& train, const Mask& mask, 
                         const DevMem2Di& trainIdx, const DevMem2Df& distance, 
                         int cc, cudaStream_t stream)
555
    {
556
        if (query.cols <= 64)
557
        {
558
            matchUnrolledCached<16, 64, Dist>(query, train, mask, trainIdx, distance, stream);
559
        }
560
        else if (query.cols <= 128)
561
        {
562
            matchUnrolledCached<16, 128, Dist>(query, train, mask, trainIdx, distance, stream);
563
        }
564
        else if (query.cols <= 256)
565
        {
566
            matchUnrolled<16, 256, Dist>(query, train, mask, trainIdx, distance, stream);
567
        }
568 569 570 571 572 573 574 575 576
        else if (query.cols <= 512)
        {            
            matchUnrolled<16, 512, Dist>(query, train, mask, trainIdx, distance, stream);
        }
        else if (query.cols <= 1024)
        {            
            matchUnrolled<16, 1024, Dist>(query, train, mask, trainIdx, distance, stream);
        }
        else
577
        {
578
            match<16, Dist>(query, train, mask, trainIdx, distance, stream);
579
        }
580 581 582 583 584 585 586 587
    }

    template <typename Dist, typename T, typename Mask> 
    void matchDispatcher(const DevMem2D_<T>& query, const DevMem2D_<T>* trains, int n, const Mask& mask, 
                         const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
                         int cc, cudaStream_t stream)
    {
        if (query.cols <= 64)
588
        {
589
            matchUnrolledCached<16, 64, Dist>(query, trains, n, mask, trainIdx, imgIdx, distance, stream);
590
        }
591
        else if (query.cols <= 128)
592
        {
593 594 595 596 597 598 599 600 601 602 603 604 605
            matchUnrolledCached<16, 128, Dist>(query, trains, n, mask, trainIdx, imgIdx, distance, stream);
        }
        else if (query.cols <= 256)
        {
            matchUnrolled<16, 256, Dist>(query, trains, n, mask, trainIdx, imgIdx, distance, stream);
        }
        else if (query.cols <= 512)
        {            
            matchUnrolled<16, 512, Dist>(query, trains, n, mask, trainIdx, imgIdx, distance, stream);
        }
        else if (query.cols <= 1024)
        {            
            matchUnrolled<16, 1024, Dist>(query, trains, n, mask, trainIdx, imgIdx, distance, stream);
606 607 608
        }
        else
        {
609
            match<16, Dist>(query, trains, n, mask, trainIdx, imgIdx, distance, stream);
610 611
        }
    }
612

613 614 615
    ///////////////////////////////////////////////////////////////////////////////
    // Match caller

616 617 618
    template <typename T> void matchL1_gpu(const DevMem2D& query, const DevMem2D& train, const DevMem2D& mask, 
                                           const DevMem2Di& trainIdx, const DevMem2Df& distance,
                                           int cc, cudaStream_t stream)
619 620
    {
        if (mask.data)
621 622 623 624 625
        {
            matchDispatcher< L1Dist<T> >(static_cast< DevMem2D_<T> >(query), static_cast< DevMem2D_<T> >(train), SingleMask(mask), 
                trainIdx, distance, 
                cc, stream);
        }
626
        else
627 628 629 630 631
        {
            matchDispatcher< L1Dist<T> >(static_cast< DevMem2D_<T> >(query), static_cast< DevMem2D_<T> >(train), WithOutMask(), 
                trainIdx, distance, 
                cc, stream);
        }
632 633
    }

634 635 636 637 638 639
    template void matchL1_gpu<uchar >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL1_gpu<schar >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<ushort>(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<short >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<int   >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<float >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
640

641 642 643
    template <typename T> void matchL2_gpu(const DevMem2D& query, const DevMem2D& train, const DevMem2D& mask, 
                                           const DevMem2Di& trainIdx, const DevMem2Df& distance, 
                                           int cc, cudaStream_t stream)
644 645
    {
        if (mask.data)
646 647 648 649 650
        {
            matchDispatcher<L2Dist>(static_cast< DevMem2D_<T> >(query), static_cast< DevMem2D_<T> >(train), SingleMask(mask), 
                trainIdx, distance, 
                cc, stream);
        }
651
        else
652 653 654 655 656
        {
            matchDispatcher<L2Dist>(static_cast< DevMem2D_<T> >(query), static_cast< DevMem2D_<T> >(train), WithOutMask(), 
                trainIdx, distance, 
                cc, stream);
        }
657 658
    }

659 660 661 662 663 664
    //template void matchL2_gpu<uchar >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<schar >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<ushort>(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<short >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<int   >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL2_gpu<float >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
665

666 667 668
    template <typename T> void matchHamming_gpu(const DevMem2D& query, const DevMem2D& train, const DevMem2D& mask, 
                                                const DevMem2Di& trainIdx, const DevMem2Df& distance, 
                                                int cc, cudaStream_t stream)
669 670
    {
        if (mask.data)
671 672 673 674 675
        {
            matchDispatcher<HammingDist>(static_cast< DevMem2D_<T> >(query), static_cast< DevMem2D_<T> >(train), SingleMask(mask), 
                trainIdx, distance, 
                cc, stream);
        }
676
        else
677 678 679 680 681
        {
            matchDispatcher<HammingDist>(static_cast< DevMem2D_<T> >(query), static_cast< DevMem2D_<T> >(train), WithOutMask(), 
                trainIdx, distance, 
                cc, stream);
        }
682 683
    }

684 685 686 687 688
    template void matchHamming_gpu<uchar >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchHamming_gpu<schar >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchHamming_gpu<ushort>(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchHamming_gpu<short >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchHamming_gpu<int   >(const DevMem2D& queryDescs, const DevMem2D& trainDescs, const DevMem2D& mask, const DevMem2Di& trainIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
689

690 691 692
    template <typename T> void matchL1_gpu(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, 
                                           const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
                                           int cc, cudaStream_t stream)
693
    {
694 695 696 697 698 699
        if (masks.data)
        {
            matchDispatcher< L1Dist<T> >(static_cast< DevMem2D_<T> >(query), (const DevMem2D_<T>*)trains.ptr(), trains.cols, MaskCollection(masks.data), 
                trainIdx, imgIdx, distance, 
                cc, stream);
        }
700
        else
701 702 703 704 705
        {
            matchDispatcher< L1Dist<T> >(static_cast< DevMem2D_<T> >(query), (const DevMem2D_<T>*)trains.ptr(), trains.cols, WithOutMask(), 
                trainIdx, imgIdx, distance, 
                cc, stream);
        }
706 707
    }

708 709 710 711 712 713
    template void matchL1_gpu<uchar >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL1_gpu<schar >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<ushort>(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<short >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<int   >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL1_gpu<float >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
714

715 716 717
    template <typename T> void matchL2_gpu(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, 
                                           const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
                                           int cc, cudaStream_t stream)
718
    {
719 720 721 722 723 724
        if (masks.data)
        {
            matchDispatcher<L2Dist>(static_cast< DevMem2D_<T> >(query), (const DevMem2D_<T>*)trains.ptr(), trains.cols, MaskCollection(masks.data), 
                trainIdx, imgIdx, distance, 
                cc, stream);
        }
725
        else
726 727 728 729 730
        {
            matchDispatcher<L2Dist>(static_cast< DevMem2D_<T> >(query), (const DevMem2D_<T>*)trains.ptr(), trains.cols, WithOutMask(), 
                trainIdx, imgIdx, distance, 
                cc, stream);
        }
731 732
    }

733 734 735 736 737 738
    //template void matchL2_gpu<uchar >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<schar >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<ushort>(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<short >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchL2_gpu<int   >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchL2_gpu<float >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& maskCollection, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
739

740 741 742
    template <typename T> void matchHamming_gpu(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, 
                                                const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, 
                                                int cc, cudaStream_t stream)
743
    {
744 745 746 747 748 749
        if (masks.data)
        {
            matchDispatcher<HammingDist>(static_cast< DevMem2D_<T> >(query), (const DevMem2D_<T>*)trains.ptr(), trains.cols, MaskCollection(masks.data), 
                trainIdx, imgIdx, distance, 
                cc, stream);
        }
750
        else
751 752 753 754 755
        {
            matchDispatcher<HammingDist>(static_cast< DevMem2D_<T> >(query), (const DevMem2D_<T>*)trains.ptr(), trains.cols, WithOutMask(), 
                trainIdx, imgIdx, distance, 
                cc, stream);
        }
756 757
    }

758 759 760 761 762
    template void matchHamming_gpu<uchar >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchHamming_gpu<schar >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchHamming_gpu<ushort>(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    //template void matchHamming_gpu<short >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
    template void matchHamming_gpu<int   >(const DevMem2D& query, const DevMem2D& trains, const DevMem2D_<PtrStep>& masks, const DevMem2Di& trainIdx, const DevMem2Di& imgIdx, const DevMem2Df& distance, int cc, cudaStream_t stream);
763
}}}