generalized_hough.cu 44.3 KB
Newer Older
wester committed
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
/*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*/

wester committed
43 44 45 46
#if defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ == 47)
#   define CUDA_DISABLER
#endif

wester committed
47 48 49 50 51
#if !defined CUDA_DISABLER

#include <thrust/device_ptr.h>
#include <thrust/transform.h>

wester committed
52 53 54 55
#include "opencv2/gpu/device/common.hpp"
#include "opencv2/gpu/device/emulation.hpp"
#include "opencv2/gpu/device/vec_math.hpp"
#include "opencv2/gpu/device/functional.hpp"
wester committed
56

wester committed
57
namespace cv { namespace gpu { namespace device
wester committed
58
{
wester committed
59
    namespace hough
wester committed
60
    {
wester committed
61
        __device__ static int g_counter;
wester committed
62 63

        template <typename T, int PIXELS_PER_THREAD>
wester committed
64
        __global__ void buildEdgePointList(const PtrStepSzb edges, const PtrStep<T> dx, const PtrStep<T> dy, unsigned int* coordList, float* thetaList)
wester committed
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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        {
            __shared__ unsigned int s_coordLists[4][32 * PIXELS_PER_THREAD];
            __shared__ float s_thetaLists[4][32 * PIXELS_PER_THREAD];
            __shared__ int s_sizes[4];
            __shared__ int s_globStart[4];

            const int x = blockIdx.x * blockDim.x * PIXELS_PER_THREAD + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

            if (threadIdx.x == 0)
                s_sizes[threadIdx.y] = 0;
            __syncthreads();

            if (y < edges.rows)
            {
                // fill the queue
                const uchar* edgesRow = edges.ptr(y);
                const T* dxRow = dx.ptr(y);
                const T* dyRow = dy.ptr(y);

                for (int i = 0, xx = x; i < PIXELS_PER_THREAD && xx < edges.cols; ++i, xx += blockDim.x)
                {
                    const T dxVal = dxRow[xx];
                    const T dyVal = dyRow[xx];

                    if (edgesRow[xx] && (dxVal != 0 || dyVal != 0))
                    {
                        const unsigned int coord = (y << 16) | xx;

                        float theta = ::atan2f(dyVal, dxVal);
                        if (theta < 0)
                            theta += 2.0f * CV_PI_F;

                        const int qidx = Emulation::smem::atomicAdd(&s_sizes[threadIdx.y], 1);

                        s_coordLists[threadIdx.y][qidx] = coord;
                        s_thetaLists[threadIdx.y][qidx] = theta;
                    }
                }
            }

            __syncthreads();

            // let one thread reserve the space required in the global list
            if (threadIdx.x == 0 && threadIdx.y == 0)
            {
                // find how many items are stored in each list
                int totalSize = 0;
                for (int i = 0; i < blockDim.y; ++i)
                {
                    s_globStart[i] = totalSize;
                    totalSize += s_sizes[i];
                }

                // calculate the offset in the global list
                const int globalOffset = atomicAdd(&g_counter, totalSize);
                for (int i = 0; i < blockDim.y; ++i)
                    s_globStart[i] += globalOffset;
            }

            __syncthreads();

            // copy local queues to global queue
            const int qsize = s_sizes[threadIdx.y];
            int gidx = s_globStart[threadIdx.y] + threadIdx.x;
            for(int i = threadIdx.x; i < qsize; i += blockDim.x, gidx += blockDim.x)
            {
                coordList[gidx] = s_coordLists[threadIdx.y][i];
                thetaList[gidx] = s_thetaLists[threadIdx.y][i];
            }
        }

        template <typename T>
        int buildEdgePointList_gpu(PtrStepSzb edges, PtrStepSzb dx, PtrStepSzb dy, unsigned int* coordList, float* thetaList)
        {
            const int PIXELS_PER_THREAD = 8;

            void* counterPtr;
            cudaSafeCall( cudaGetSymbolAddress(&counterPtr, g_counter) );

            cudaSafeCall( cudaMemset(counterPtr, 0, sizeof(int)) );

            const dim3 block(32, 4);
            const dim3 grid(divUp(edges.cols, block.x * PIXELS_PER_THREAD), divUp(edges.rows, block.y));

            cudaSafeCall( cudaFuncSetCacheConfig(buildEdgePointList<T, PIXELS_PER_THREAD>, cudaFuncCachePreferShared) );

            buildEdgePointList<T, PIXELS_PER_THREAD><<<grid, block>>>(edges, (PtrStepSz<T>) dx, (PtrStepSz<T>) dy, coordList, thetaList);
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );

            int totalCount;
            cudaSafeCall( cudaMemcpy(&totalCount, counterPtr, sizeof(int), cudaMemcpyDeviceToHost) );

            return totalCount;
        }

        template int buildEdgePointList_gpu<short>(PtrStepSzb edges, PtrStepSzb dx, PtrStepSzb dy, unsigned int* coordList, float* thetaList);
        template int buildEdgePointList_gpu<int>(PtrStepSzb edges, PtrStepSzb dx, PtrStepSzb dy, unsigned int* coordList, float* thetaList);
        template int buildEdgePointList_gpu<float>(PtrStepSzb edges, PtrStepSzb dx, PtrStepSzb dy, unsigned int* coordList, float* thetaList);

        __global__ void buildRTable(const unsigned int* coordList, const float* thetaList, const int pointsCount,
                                    PtrStep<short2> r_table, int* r_sizes, int maxSize,
                                    const short2 templCenter, const float thetaScale)
        {
            const int tid = blockIdx.x * blockDim.x + threadIdx.x;

            if (tid >= pointsCount)
                return;

            const unsigned int coord = coordList[tid];
            short2 p;
            p.x = (coord & 0xFFFF);
            p.y = (coord >> 16) & 0xFFFF;

            const float theta = thetaList[tid];
            const int n = __float2int_rn(theta * thetaScale);

            const int ind = ::atomicAdd(r_sizes + n, 1);
            if (ind < maxSize)
                r_table(n, ind) = saturate_cast<short2>(p - templCenter);
        }

        void buildRTable_gpu(const unsigned int* coordList, const float* thetaList, int pointsCount,
                             PtrStepSz<short2> r_table, int* r_sizes,
                             short2 templCenter, int levels)
        {
            const dim3 block(256);
            const dim3 grid(divUp(pointsCount, block.x));

            const float thetaScale = levels / (2.0f * CV_PI_F);

            buildRTable<<<grid, block>>>(coordList, thetaList, pointsCount, r_table, r_sizes, r_table.cols, templCenter, thetaScale);
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

        ////////////////////////////////////////////////////////////////////////
wester committed
205
        // GHT_Ballard_Pos
wester committed
206

wester committed
207 208 209 210
        __global__ void GHT_Ballard_Pos_calcHist(const unsigned int* coordList, const float* thetaList, const int pointsCount,
                                                 const PtrStep<short2> r_table, const int* r_sizes,
                                                 PtrStepSzi hist,
                                                 const float idp, const float thetaScale)
wester committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
        {
            const int tid = blockIdx.x * blockDim.x + threadIdx.x;

            if (tid >= pointsCount)
                return;

            const unsigned int coord = coordList[tid];
            short2 p;
            p.x = (coord & 0xFFFF);
            p.y = (coord >> 16) & 0xFFFF;

            const float theta = thetaList[tid];
            const int n = __float2int_rn(theta * thetaScale);

            const short2* r_row = r_table.ptr(n);
            const int r_row_size = r_sizes[n];

            for (int j = 0; j < r_row_size; ++j)
            {
wester committed
230
                int2 c = p - r_row[j];
wester committed
231 232 233 234 235 236 237 238 239

                c.x = __float2int_rn(c.x * idp);
                c.y = __float2int_rn(c.y * idp);

                if (c.x >= 0 && c.x < hist.cols - 2 && c.y >= 0 && c.y < hist.rows - 2)
                    ::atomicAdd(hist.ptr(c.y + 1) + c.x + 1, 1);
            }
        }

wester committed
240 241 242 243
        void GHT_Ballard_Pos_calcHist_gpu(const unsigned int* coordList, const float* thetaList, int pointsCount,
                                          PtrStepSz<short2> r_table, const int* r_sizes,
                                          PtrStepSzi hist,
                                          float dp, int levels)
wester committed
244 245 246 247 248 249 250
        {
            const dim3 block(256);
            const dim3 grid(divUp(pointsCount, block.x));

            const float idp = 1.0f / dp;
            const float thetaScale = levels / (2.0f * CV_PI_F);

wester committed
251
            GHT_Ballard_Pos_calcHist<<<grid, block>>>(coordList, thetaList, pointsCount, r_table, r_sizes, hist, idp, thetaScale);
wester committed
252 253 254 255 256
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

wester committed
257
        __global__ void GHT_Ballard_Pos_findPosInHist(const PtrStepSzi hist, float4* out, int3* votes, const int maxSize, const float dp, const int threshold)
wester committed
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
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

            if (x >= hist.cols - 2 || y >= hist.rows - 2)
                return;

            const int curVotes = hist(y + 1, x + 1);

            if (curVotes > threshold &&
                curVotes >  hist(y + 1, x) &&
                curVotes >= hist(y + 1, x + 2) &&
                curVotes >  hist(y, x + 1) &&
                curVotes >= hist(y + 2, x + 1))
            {
                const int ind = ::atomicAdd(&g_counter, 1);

                if (ind < maxSize)
                {
                    out[ind] = make_float4(x * dp, y * dp, 1.0f, 0.0f);
                    votes[ind] = make_int3(curVotes, 0, 0);
                }
            }
        }

wester committed
283
        int GHT_Ballard_Pos_findPosInHist_gpu(PtrStepSzi hist, float4* out, int3* votes, int maxSize, float dp, int threshold)
wester committed
284 285 286 287 288 289 290 291 292
        {
            void* counterPtr;
            cudaSafeCall( cudaGetSymbolAddress(&counterPtr, g_counter) );

            cudaSafeCall( cudaMemset(counterPtr, 0, sizeof(int)) );

            const dim3 block(32, 8);
            const dim3 grid(divUp(hist.cols - 2, block.x), divUp(hist.rows - 2, block.y));

wester committed
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 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 394 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
            cudaSafeCall( cudaFuncSetCacheConfig(GHT_Ballard_Pos_findPosInHist, cudaFuncCachePreferL1) );

            GHT_Ballard_Pos_findPosInHist<<<grid, block>>>(hist, out, votes, maxSize, dp, threshold);
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );

            int totalCount;
            cudaSafeCall( cudaMemcpy(&totalCount, counterPtr, sizeof(int), cudaMemcpyDeviceToHost) );

            totalCount = ::min(totalCount, maxSize);

            return totalCount;
        }

        ////////////////////////////////////////////////////////////////////////
        // GHT_Ballard_PosScale

        __global__ void GHT_Ballard_PosScale_calcHist(const unsigned int* coordList, const float* thetaList,
                                                      PtrStep<short2> r_table, const int* r_sizes,
                                                      PtrStepi hist, const int rows, const int cols,
                                                      const float minScale, const float scaleStep, const int scaleRange,
                                                      const float idp, const float thetaScale)
        {
            const unsigned int coord = coordList[blockIdx.x];
            float2 p;
            p.x = (coord & 0xFFFF);
            p.y = (coord >> 16) & 0xFFFF;

            const float theta = thetaList[blockIdx.x];
            const int n = __float2int_rn(theta * thetaScale);

            const short2* r_row = r_table.ptr(n);
            const int r_row_size = r_sizes[n];

            for (int j = 0; j < r_row_size; ++j)
            {
                const float2 d = saturate_cast<float2>(r_row[j]);

                for (int s = threadIdx.x; s < scaleRange; s += blockDim.x)
                {
                    const float scale = minScale + s * scaleStep;

                    float2 c = p - scale * d;

                    c.x *= idp;
                    c.y *= idp;

                    if (c.x >= 0 && c.x < cols && c.y >= 0 && c.y < rows)
                        ::atomicAdd(hist.ptr((s + 1) * (rows + 2) + __float2int_rn(c.y + 1)) + __float2int_rn(c.x + 1), 1);
                }
            }
        }

        void GHT_Ballard_PosScale_calcHist_gpu(const unsigned int* coordList, const float* thetaList, int pointsCount,
                                               PtrStepSz<short2> r_table, const int* r_sizes,
                                               PtrStepi hist, int rows, int cols,
                                               float minScale, float scaleStep, int scaleRange,
                                               float dp, int levels)
        {
            const dim3 block(256);
            const dim3 grid(pointsCount);

            const float idp = 1.0f / dp;
            const float thetaScale = levels / (2.0f * CV_PI_F);

            GHT_Ballard_PosScale_calcHist<<<grid, block>>>(coordList, thetaList,
                                                           r_table, r_sizes,
                                                           hist, rows, cols,
                                                           minScale, scaleStep, scaleRange,
                                                           idp, thetaScale);
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

        __global__ void GHT_Ballard_PosScale_findPosInHist(const PtrStepi hist, const int rows, const int cols, const int scaleRange,
                                                           float4* out, int3* votes, const int maxSize,
                                                           const float minScale, const float scaleStep, const float dp, const int threshold)
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

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

            for (int s = 0; s < scaleRange; ++s)
            {
                const float scale = minScale + s * scaleStep;

                const int prevScaleIdx = (s) * (rows + 2);
                const int curScaleIdx = (s + 1) * (rows + 2);
                const int nextScaleIdx = (s + 2) * (rows + 2);

                const int curVotes = hist(curScaleIdx + y + 1, x + 1);

                if (curVotes > threshold &&
                    curVotes >  hist(curScaleIdx + y + 1, x) &&
                    curVotes >= hist(curScaleIdx + y + 1, x + 2) &&
                    curVotes >  hist(curScaleIdx + y, x + 1) &&
                    curVotes >= hist(curScaleIdx + y + 2, x + 1) &&
                    curVotes >  hist(prevScaleIdx + y + 1, x + 1) &&
                    curVotes >= hist(nextScaleIdx + y + 1, x + 1))
                {
                    const int ind = ::atomicAdd(&g_counter, 1);

                    if (ind < maxSize)
                    {
                        out[ind] = make_float4(x * dp, y * dp, scale, 0.0f);
                        votes[ind] = make_int3(curVotes, curVotes, 0);
                    }
                }
            }
        }

        int GHT_Ballard_PosScale_findPosInHist_gpu(PtrStepi hist, int rows, int cols, int scaleRange, float4* out, int3* votes, int maxSize,
                                                   float minScale, float scaleStep, float dp, int threshold)
        {
            void* counterPtr;
            cudaSafeCall( cudaGetSymbolAddress(&counterPtr, g_counter) );

            cudaSafeCall( cudaMemset(counterPtr, 0, sizeof(int)) );

            const dim3 block(32, 8);
            const dim3 grid(divUp(cols, block.x), divUp(rows, block.y));

            cudaSafeCall( cudaFuncSetCacheConfig(GHT_Ballard_PosScale_findPosInHist, cudaFuncCachePreferL1) );
wester committed
420

wester committed
421
            GHT_Ballard_PosScale_findPosInHist<<<grid, block>>>(hist, rows, cols, scaleRange, out, votes, maxSize, minScale, scaleStep, dp, threshold);
wester committed
422 423 424 425 426 427 428 429 430 431 432 433 434
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );

            int totalCount;
            cudaSafeCall( cudaMemcpy(&totalCount, counterPtr, sizeof(int), cudaMemcpyDeviceToHost) );

            totalCount = ::min(totalCount, maxSize);

            return totalCount;
        }

        ////////////////////////////////////////////////////////////////////////
wester committed
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 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        // GHT_Ballard_PosRotation

        __global__ void GHT_Ballard_PosRotation_calcHist(const unsigned int* coordList, const float* thetaList,
                                                         PtrStep<short2> r_table, const int* r_sizes,
                                                         PtrStepi hist, const int rows, const int cols,
                                                         const float minAngle, const float angleStep, const int angleRange,
                                                         const float idp, const float thetaScale)
        {
            const unsigned int coord = coordList[blockIdx.x];
            float2 p;
            p.x = (coord & 0xFFFF);
            p.y = (coord >> 16) & 0xFFFF;

            const float thetaVal = thetaList[blockIdx.x];

            for (int a = threadIdx.x; a < angleRange; a += blockDim.x)
            {
                const float angle = (minAngle + a * angleStep) * (CV_PI_F / 180.0f);
                float sinA, cosA;
                sincosf(angle, &sinA, &cosA);

                float theta = thetaVal - angle;
                if (theta < 0)
                    theta += 2.0f * CV_PI_F;

                const int n = __float2int_rn(theta * thetaScale);

                const short2* r_row = r_table.ptr(n);
                const int r_row_size = r_sizes[n];

                for (int j = 0; j < r_row_size; ++j)
                {
                    const float2 d = saturate_cast<float2>(r_row[j]);

                    const float2 dr = make_float2(d.x * cosA - d.y * sinA, d.x * sinA + d.y * cosA);

                    float2 c = make_float2(p.x - dr.x, p.y - dr.y);
                    c.x *= idp;
                    c.y *= idp;

                    if (c.x >= 0 && c.x < cols && c.y >= 0 && c.y < rows)
                        ::atomicAdd(hist.ptr((a + 1) * (rows + 2) + __float2int_rn(c.y + 1)) + __float2int_rn(c.x + 1), 1);
                }
            }
        }

        void GHT_Ballard_PosRotation_calcHist_gpu(const unsigned int* coordList, const float* thetaList, int pointsCount,
                                                  PtrStepSz<short2> r_table, const int* r_sizes,
                                                  PtrStepi hist, int rows, int cols,
                                                  float minAngle, float angleStep, int angleRange,
                                                  float dp, int levels)
        {
            const dim3 block(256);
            const dim3 grid(pointsCount);

            const float idp = 1.0f / dp;
            const float thetaScale = levels / (2.0f * CV_PI_F);

            GHT_Ballard_PosRotation_calcHist<<<grid, block>>>(coordList, thetaList,
                                                              r_table, r_sizes,
                                                              hist, rows, cols,
                                                              minAngle, angleStep, angleRange,
                                                              idp, thetaScale);
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

        __global__ void GHT_Ballard_PosRotation_findPosInHist(const PtrStepi hist, const int rows, const int cols, const int angleRange,
                                                              float4* out, int3* votes, const int maxSize,
                                                              const float minAngle, const float angleStep, const float dp, const int threshold)
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

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

            for (int a = 0; a < angleRange; ++a)
            {
                const float angle = minAngle + a * angleStep;

                const int prevAngleIdx = (a) * (rows + 2);
                const int curAngleIdx = (a + 1) * (rows + 2);
                const int nextAngleIdx = (a + 2) * (rows + 2);

                const int curVotes = hist(curAngleIdx + y + 1, x + 1);

                if (curVotes > threshold &&
                    curVotes >  hist(curAngleIdx + y + 1, x) &&
                    curVotes >= hist(curAngleIdx + y + 1, x + 2) &&
                    curVotes >  hist(curAngleIdx + y, x + 1) &&
                    curVotes >= hist(curAngleIdx + y + 2, x + 1) &&
                    curVotes >  hist(prevAngleIdx + y + 1, x + 1) &&
                    curVotes >= hist(nextAngleIdx + y + 1, x + 1))
                {
                    const int ind = ::atomicAdd(&g_counter, 1);

                    if (ind < maxSize)
                    {
                        out[ind] = make_float4(x * dp, y * dp, 1.0f, angle);
                        votes[ind] = make_int3(curVotes, 0, curVotes);
                    }
                }
            }
        }

        int GHT_Ballard_PosRotation_findPosInHist_gpu(PtrStepi hist, int rows, int cols, int angleRange, float4* out, int3* votes, int maxSize,
                                                      float minAngle, float angleStep, float dp, int threshold)
        {
            void* counterPtr;
            cudaSafeCall( cudaGetSymbolAddress(&counterPtr, g_counter) );

            cudaSafeCall( cudaMemset(counterPtr, 0, sizeof(int)) );

            const dim3 block(32, 8);
            const dim3 grid(divUp(cols, block.x), divUp(rows, block.y));

            cudaSafeCall( cudaFuncSetCacheConfig(GHT_Ballard_PosRotation_findPosInHist, cudaFuncCachePreferL1) );

            GHT_Ballard_PosRotation_findPosInHist<<<grid, block>>>(hist, rows, cols, angleRange, out, votes, maxSize, minAngle, angleStep, dp, threshold);
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );

            int totalCount;
            cudaSafeCall( cudaMemcpy(&totalCount, counterPtr, sizeof(int), cudaMemcpyDeviceToHost) );

            totalCount = ::min(totalCount, maxSize);

            return totalCount;
        }

        ////////////////////////////////////////////////////////////////////////
        // GHT_Guil_Full
wester committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

        struct FeatureTable
        {
            uchar* p1_pos_data;
            size_t p1_pos_step;

            uchar* p1_theta_data;
            size_t p1_theta_step;

            uchar* p2_pos_data;
            size_t p2_pos_step;

            uchar* d12_data;
            size_t d12_step;

            uchar* r1_data;
            size_t r1_step;

            uchar* r2_data;
            size_t r2_step;
        };

        __constant__ FeatureTable c_templFeatures;
        __constant__ FeatureTable c_imageFeatures;

wester committed
595
        void GHT_Guil_Full_setTemplFeatures(PtrStepb p1_pos, PtrStepb p1_theta, PtrStepb p2_pos, PtrStepb d12, PtrStepb r1, PtrStepb r2)
wester committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
        {
            FeatureTable tbl;

            tbl.p1_pos_data = p1_pos.data;
            tbl.p1_pos_step = p1_pos.step;

            tbl.p1_theta_data = p1_theta.data;
            tbl.p1_theta_step = p1_theta.step;

            tbl.p2_pos_data = p2_pos.data;
            tbl.p2_pos_step = p2_pos.step;

            tbl.d12_data = d12.data;
            tbl.d12_step = d12.step;

            tbl.r1_data = r1.data;
            tbl.r1_step = r1.step;

            tbl.r2_data = r2.data;
            tbl.r2_step = r2.step;

            cudaSafeCall( cudaMemcpyToSymbol(c_templFeatures, &tbl, sizeof(FeatureTable)) );
        }
wester committed
619
        void GHT_Guil_Full_setImageFeatures(PtrStepb p1_pos, PtrStepb p1_theta, PtrStepb p2_pos, PtrStepb d12, PtrStepb r1, PtrStepb r2)
wester committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
        {
            FeatureTable tbl;

            tbl.p1_pos_data = p1_pos.data;
            tbl.p1_pos_step = p1_pos.step;

            tbl.p1_theta_data = p1_theta.data;
            tbl.p1_theta_step = p1_theta.step;

            tbl.p2_pos_data = p2_pos.data;
            tbl.p2_pos_step = p2_pos.step;

            tbl.d12_data = d12.data;
            tbl.d12_step = d12.step;

            tbl.r1_data = r1.data;
            tbl.r1_step = r1.step;

            tbl.r2_data = r2.data;
            tbl.r2_step = r2.step;

            cudaSafeCall( cudaMemcpyToSymbol(c_imageFeatures, &tbl, sizeof(FeatureTable)) );
        }

        struct TemplFeatureTable
        {
            static __device__ float2* p1_pos(int n)
            {
                return (float2*)(c_templFeatures.p1_pos_data + n * c_templFeatures.p1_pos_step);
            }
            static __device__ float* p1_theta(int n)
            {
                return (float*)(c_templFeatures.p1_theta_data + n * c_templFeatures.p1_theta_step);
            }
            static __device__ float2* p2_pos(int n)
            {
                return (float2*)(c_templFeatures.p2_pos_data + n * c_templFeatures.p2_pos_step);
            }

            static __device__ float* d12(int n)
            {
                return (float*)(c_templFeatures.d12_data + n * c_templFeatures.d12_step);
            }

            static __device__ float2* r1(int n)
            {
                return (float2*)(c_templFeatures.r1_data + n * c_templFeatures.r1_step);
            }
            static __device__ float2* r2(int n)
            {
                return (float2*)(c_templFeatures.r2_data + n * c_templFeatures.r2_step);
            }
        };
        struct ImageFeatureTable
        {
            static __device__ float2* p1_pos(int n)
            {
                return (float2*)(c_imageFeatures.p1_pos_data + n * c_imageFeatures.p1_pos_step);
            }
            static __device__ float* p1_theta(int n)
            {
                return (float*)(c_imageFeatures.p1_theta_data + n * c_imageFeatures.p1_theta_step);
            }
            static __device__ float2* p2_pos(int n)
            {
                return (float2*)(c_imageFeatures.p2_pos_data + n * c_imageFeatures.p2_pos_step);
            }

            static __device__ float* d12(int n)
            {
                return (float*)(c_imageFeatures.d12_data + n * c_imageFeatures.d12_step);
            }

            static __device__ float2* r1(int n)
            {
                return (float2*)(c_imageFeatures.r1_data + n * c_imageFeatures.r1_step);
            }
            static __device__ float2* r2(int n)
            {
                return (float2*)(c_imageFeatures.r2_data + n * c_imageFeatures.r2_step);
            }
        };

        __device__ float clampAngle(float a)
        {
            float res = a;

            while (res > 2.0f * CV_PI_F)
                res -= 2.0f * CV_PI_F;
            while (res < 0.0f)
                res += 2.0f * CV_PI_F;

            return res;
        }

        __device__ bool angleEq(float a, float b, float eps)
        {
            return (::fabs(clampAngle(a - b)) <= eps);
        }

        template <class FT, bool isTempl>
wester committed
721 722 723 724
        __global__ void GHT_Guil_Full_buildFeatureList(const unsigned int* coordList, const float* thetaList, const int pointsCount,
                                                       int* sizes, const int maxSize,
                                                       const float xi, const float angleEpsilon, const float alphaScale,
                                                       const float2 center, const float maxDist)
wester committed
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        {
            const float p1_theta = thetaList[blockIdx.x];
            const unsigned int coord1 = coordList[blockIdx.x];
            float2 p1_pos;
            p1_pos.x = (coord1 & 0xFFFF);
            p1_pos.y = (coord1 >> 16) & 0xFFFF;

            for (int i = threadIdx.x; i < pointsCount; i += blockDim.x)
            {
                const float p2_theta = thetaList[i];
                const unsigned int coord2 = coordList[i];
                float2 p2_pos;
                p2_pos.x = (coord2 & 0xFFFF);
                p2_pos.y = (coord2 >> 16) & 0xFFFF;

                if (angleEq(p1_theta - p2_theta, xi, angleEpsilon))
                {
                    const float2 d = p1_pos - p2_pos;

                    float alpha12 = clampAngle(::atan2(d.y, d.x) - p1_theta);
                    float d12 = ::sqrtf(d.x * d.x + d.y * d.y);

                    if (d12 > maxDist)
                        continue;

                    float2 r1 = p1_pos - center;
                    float2 r2 = p2_pos - center;

                    const int n = __float2int_rn(alpha12 * alphaScale);

                    const int ind = ::atomicAdd(sizes + n, 1);

                    if (ind < maxSize)
                    {
                        if (!isTempl)
                        {
                            FT::p1_pos(n)[ind] = p1_pos;
                            FT::p2_pos(n)[ind] = p2_pos;
                        }

                        FT::p1_theta(n)[ind] = p1_theta;

                        FT::d12(n)[ind] = d12;

                        if (isTempl)
                        {
                            FT::r1(n)[ind] = r1;
                            FT::r2(n)[ind] = r2;
                        }
                    }
                }
            }
        }

        template <class FT, bool isTempl>
wester committed
780 781 782 783
        void GHT_Guil_Full_buildFeatureList_caller(const unsigned int* coordList, const float* thetaList, int pointsCount,
                                                   int* sizes, int maxSize,
                                                   float xi, float angleEpsilon, int levels,
                                                   float2 center, float maxDist)
wester committed
784 785 786 787 788 789
        {
            const dim3 block(256);
            const dim3 grid(pointsCount);

            const float alphaScale = levels / (2.0f * CV_PI_F);

wester committed
790 791 792 793
            GHT_Guil_Full_buildFeatureList<FT, isTempl><<<grid, block>>>(coordList, thetaList, pointsCount,
                                                                         sizes, maxSize,
                                                                         xi * (CV_PI_F / 180.0f), angleEpsilon * (CV_PI_F / 180.0f), alphaScale,
                                                                         center, maxDist);
wester committed
794 795 796 797 798 799 800 801
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );

            thrust::device_ptr<int> sizesPtr(sizes);
            thrust::transform(sizesPtr, sizesPtr + levels + 1, sizesPtr, device::bind2nd(device::minimum<int>(), maxSize));
        }

wester committed
802 803 804 805
        void GHT_Guil_Full_buildTemplFeatureList_gpu(const unsigned int* coordList, const float* thetaList, int pointsCount,
                                                     int* sizes, int maxSize,
                                                     float xi, float angleEpsilon, int levels,
                                                     float2 center, float maxDist)
wester committed
806
        {
wester committed
807 808 809 810
            GHT_Guil_Full_buildFeatureList_caller<TemplFeatureTable, true>(coordList, thetaList, pointsCount,
                                                                           sizes, maxSize,
                                                                           xi, angleEpsilon, levels,
                                                                           center, maxDist);
wester committed
811
        }
wester committed
812 813 814 815
        void GHT_Guil_Full_buildImageFeatureList_gpu(const unsigned int* coordList, const float* thetaList, int pointsCount,
                                                     int* sizes, int maxSize,
                                                     float xi, float angleEpsilon, int levels,
                                                     float2 center, float maxDist)
wester committed
816
        {
wester committed
817 818 819 820
            GHT_Guil_Full_buildFeatureList_caller<ImageFeatureTable, false>(coordList, thetaList, pointsCount,
                                                                            sizes, maxSize,
                                                                            xi, angleEpsilon, levels,
                                                                            center, maxDist);
wester committed
821 822
        }

wester committed
823 824
        __global__ void GHT_Guil_Full_calcOHist(const int* templSizes, const int* imageSizes, int* OHist,
                                                const float minAngle, const float maxAngle, const float iAngleStep, const int angleRange)
wester committed
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
        {
            extern __shared__ int s_OHist[];
            for (int i = threadIdx.x; i <= angleRange; i += blockDim.x)
                s_OHist[i] = 0;
            __syncthreads();

            const int tIdx = blockIdx.x;
            const int level = blockIdx.y;

            const int tSize = templSizes[level];

            if (tIdx < tSize)
            {
                const int imSize = imageSizes[level];

                const float t_p1_theta = TemplFeatureTable::p1_theta(level)[tIdx];

                for (int i = threadIdx.x; i < imSize; i += blockDim.x)
                {
                    const float im_p1_theta = ImageFeatureTable::p1_theta(level)[i];

                    const float angle = clampAngle(im_p1_theta - t_p1_theta);

                    if (angle >= minAngle && angle <= maxAngle)
                    {
                        const int n = __float2int_rn((angle - minAngle) * iAngleStep);
                        Emulation::smem::atomicAdd(&s_OHist[n], 1);
                    }
                }
            }
            __syncthreads();

            for (int i = threadIdx.x; i <= angleRange; i += blockDim.x)
                ::atomicAdd(OHist + i, s_OHist[i]);
        }

wester committed
861 862 863
        void GHT_Guil_Full_calcOHist_gpu(const int* templSizes, const int* imageSizes, int* OHist,
                                         float minAngle, float maxAngle, float angleStep, int angleRange,
                                         int levels, int tMaxSize)
wester committed
864 865 866 867 868 869 870 871 872 873
        {
            const dim3 block(256);
            const dim3 grid(tMaxSize, levels + 1);

            minAngle *= (CV_PI_F / 180.0f);
            maxAngle *= (CV_PI_F / 180.0f);
            angleStep *= (CV_PI_F / 180.0f);

            const size_t smemSize = (angleRange + 1) * sizeof(float);

wester committed
874 875
            GHT_Guil_Full_calcOHist<<<grid, block, smemSize>>>(templSizes, imageSizes, OHist,
                                                               minAngle, maxAngle, 1.0f / angleStep, angleRange);
wester committed
876 877 878 879 880
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

wester committed
881 882 883
        __global__ void GHT_Guil_Full_calcSHist(const int* templSizes, const int* imageSizes, int* SHist,
                                                const float angle, const float angleEpsilon,
                                                const float minScale, const float maxScale, const float iScaleStep, const int scaleRange)
wester committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
        {
            extern __shared__ int s_SHist[];
            for (int i = threadIdx.x; i <= scaleRange; i += blockDim.x)
                s_SHist[i] = 0;
            __syncthreads();

            const int tIdx = blockIdx.x;
            const int level = blockIdx.y;

            const int tSize = templSizes[level];

            if (tIdx < tSize)
            {
                const int imSize = imageSizes[level];

                const float t_p1_theta = TemplFeatureTable::p1_theta(level)[tIdx] + angle;
                const float t_d12 = TemplFeatureTable::d12(level)[tIdx] + angle;

                for (int i = threadIdx.x; i < imSize; i += blockDim.x)
                {
                    const float im_p1_theta = ImageFeatureTable::p1_theta(level)[i];
                    const float im_d12 = ImageFeatureTable::d12(level)[i];

                    if (angleEq(im_p1_theta, t_p1_theta, angleEpsilon))
                    {
                        const float scale = im_d12 / t_d12;

                        if (scale >= minScale && scale <= maxScale)
                        {
                            const int s = __float2int_rn((scale - minScale) * iScaleStep);
                            Emulation::smem::atomicAdd(&s_SHist[s], 1);
                        }
                    }
                }
            }
            __syncthreads();

            for (int i = threadIdx.x; i <= scaleRange; i += blockDim.x)
                ::atomicAdd(SHist + i, s_SHist[i]);
        }

wester committed
925 926 927 928
        void GHT_Guil_Full_calcSHist_gpu(const int* templSizes, const int* imageSizes, int* SHist,
                                         float angle, float angleEpsilon,
                                         float minScale, float maxScale, float iScaleStep, int scaleRange,
                                         int levels, int tMaxSize)
wester committed
929 930 931 932 933 934 935 936 937
        {
            const dim3 block(256);
            const dim3 grid(tMaxSize, levels + 1);

            angle *= (CV_PI_F / 180.0f);
            angleEpsilon *= (CV_PI_F / 180.0f);

            const size_t smemSize = (scaleRange + 1) * sizeof(float);

wester committed
938 939 940
            GHT_Guil_Full_calcSHist<<<grid, block, smemSize>>>(templSizes, imageSizes, SHist,
                                                               angle, angleEpsilon,
                                                               minScale, maxScale, iScaleStep, scaleRange);
wester committed
941 942 943 944 945
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

wester committed
946 947 948
        __global__ void GHT_Guil_Full_calcPHist(const int* templSizes, const int* imageSizes, PtrStepSzi PHist,
                                                const float angle, const float sinVal, const float cosVal, const float angleEpsilon, const float scale,
                                                const float idp)
wester committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
        {
            const int tIdx = blockIdx.x;
            const int level = blockIdx.y;

            const int tSize = templSizes[level];

            if (tIdx < tSize)
            {
                const int imSize = imageSizes[level];

                const float t_p1_theta = TemplFeatureTable::p1_theta(level)[tIdx] + angle;

                float2 r1 = TemplFeatureTable::r1(level)[tIdx];
                float2 r2 = TemplFeatureTable::r2(level)[tIdx];

                r1 = r1 * scale;
                r2 = r2 * scale;

                r1 = make_float2(cosVal * r1.x - sinVal * r1.y, sinVal * r1.x + cosVal * r1.y);
                r2 = make_float2(cosVal * r2.x - sinVal * r2.y, sinVal * r2.x + cosVal * r2.y);

                for (int i = threadIdx.x; i < imSize; i += blockDim.x)
                {
                    const float im_p1_theta = ImageFeatureTable::p1_theta(level)[i];

                    const float2 im_p1_pos = ImageFeatureTable::p1_pos(level)[i];
                    const float2 im_p2_pos = ImageFeatureTable::p2_pos(level)[i];

                    if (angleEq(im_p1_theta, t_p1_theta, angleEpsilon))
                    {
                        float2 c1, c2;

                        c1 = im_p1_pos - r1;
                        c1 = c1 * idp;

                        c2 = im_p2_pos - r2;
                        c2 = c2 * idp;

                        if (::fabs(c1.x - c2.x) > 1 || ::fabs(c1.y - c2.y) > 1)
                            continue;

                        if (c1.y >= 0 && c1.y < PHist.rows - 2 && c1.x >= 0 && c1.x < PHist.cols - 2)
                            ::atomicAdd(PHist.ptr(__float2int_rn(c1.y) + 1) + __float2int_rn(c1.x) + 1, 1);
                    }
                }
            }
        }

wester committed
997 998 999 1000
        void GHT_Guil_Full_calcPHist_gpu(const int* templSizes, const int* imageSizes, PtrStepSzi PHist,
                                         float angle, float angleEpsilon, float scale,
                                         float dp,
                                         int levels, int tMaxSize)
wester committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        {
            const dim3 block(256);
            const dim3 grid(tMaxSize, levels + 1);

            angle *= (CV_PI_F / 180.0f);
            angleEpsilon *= (CV_PI_F / 180.0f);

            const float sinVal = ::sinf(angle);
            const float cosVal = ::cosf(angle);

wester committed
1011
            cudaSafeCall( cudaFuncSetCacheConfig(GHT_Guil_Full_calcPHist, cudaFuncCachePreferL1) );
wester committed
1012

wester committed
1013 1014 1015
            GHT_Guil_Full_calcPHist<<<grid, block>>>(templSizes, imageSizes, PHist,
                                                     angle, sinVal, cosVal, angleEpsilon, scale,
                                                     1.0f / dp);
wester committed
1016 1017 1018 1019 1020
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );
        }

wester committed
1021 1022 1023
        __global__ void GHT_Guil_Full_findPosInHist(const PtrStepSzi hist, float4* out, int3* votes, const int maxSize,
                                                    const float angle, const int angleVotes, const float scale, const int scaleVotes,
                                                    const float dp, const int threshold)
wester committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        {
            const int x = blockIdx.x * blockDim.x + threadIdx.x;
            const int y = blockIdx.y * blockDim.y + threadIdx.y;

            if (x >= hist.cols - 2 || y >= hist.rows - 2)
                return;

            const int curVotes = hist(y + 1, x + 1);

            if (curVotes > threshold &&
                curVotes >  hist(y + 1, x) &&
                curVotes >= hist(y + 1, x + 2) &&
                curVotes >  hist(y, x + 1) &&
                curVotes >= hist(y + 2, x + 1))
            {
                const int ind = ::atomicAdd(&g_counter, 1);

                if (ind < maxSize)
                {
                    out[ind] = make_float4(x * dp, y * dp, scale, angle);
                    votes[ind] = make_int3(curVotes, scaleVotes, angleVotes);
                }
            }
        }

wester committed
1049 1050 1051
        int GHT_Guil_Full_findPosInHist_gpu(PtrStepSzi hist, float4* out, int3* votes, int curSize, int maxSize,
                                             float angle, int angleVotes, float scale, int scaleVotes,
                                             float dp, int threshold)
wester committed
1052 1053 1054 1055 1056 1057 1058 1059 1060
        {
            void* counterPtr;
            cudaSafeCall( cudaGetSymbolAddress(&counterPtr, g_counter) );

            cudaSafeCall( cudaMemcpy(counterPtr, &curSize, sizeof(int), cudaMemcpyHostToDevice) );

            const dim3 block(32, 8);
            const dim3 grid(divUp(hist.cols - 2, block.x), divUp(hist.rows - 2, block.y));

wester committed
1061
            cudaSafeCall( cudaFuncSetCacheConfig(GHT_Guil_Full_findPosInHist, cudaFuncCachePreferL1) );
wester committed
1062

wester committed
1063 1064 1065
            GHT_Guil_Full_findPosInHist<<<grid, block>>>(hist, out, votes, maxSize,
                                                         angle, angleVotes, scale, scaleVotes,
                                                         dp, threshold);
wester committed
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
            cudaSafeCall( cudaGetLastError() );

            cudaSafeCall( cudaDeviceSynchronize() );

            int totalCount;
            cudaSafeCall( cudaMemcpy(&totalCount, counterPtr, sizeof(int), cudaMemcpyDeviceToHost) );

            totalCount = ::min(totalCount, maxSize);

            return totalCount;
        }
    }
}}}

#endif /* CUDA_DISABLER */