lbp.cu 12.1 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
/*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
31
// any express or implied warranties, including, but not limited to, the implied
32 33 34 35 36 37 38 39 40 41 42
// 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*/

43 44
#if !defined CUDA_DISABLER

45 46 47
#include "lbp.hpp"
#include "opencv2/gpu/device/vec_traits.hpp"
#include "opencv2/gpu/device/saturate_cast.hpp"
48 49 50 51 52

namespace cv { namespace gpu { namespace device
{
    namespace lbp
    {
53 54
        struct LBP
        {
55
            __host__ __device__ __forceinline__ LBP() {}
56

Marina Kolpakova's avatar
Marina Kolpakova committed
57
            __device__ __forceinline__ int operator() (const int* integral, int ty, int fh, int fw, int& shift) const
58 59 60
            {
                int anchors[9];

Marina Kolpakova's avatar
Marina Kolpakova committed
61 62
                anchors[0]  = integral[ty];
                anchors[1]  = integral[ty + fw];
63
                anchors[0] -= anchors[1];
Marina Kolpakova's avatar
Marina Kolpakova committed
64
                anchors[2]  = integral[ty + fw * 2];
65
                anchors[1] -= anchors[2];
Marina Kolpakova's avatar
Marina Kolpakova committed
66
                anchors[2] -= integral[ty + fw * 3];
67 68

                ty += fh;
Marina Kolpakova's avatar
Marina Kolpakova committed
69 70
                anchors[3]  = integral[ty];
                anchors[4]  = integral[ty + fw];
71
                anchors[3] -= anchors[4];
Marina Kolpakova's avatar
Marina Kolpakova committed
72
                anchors[5]  = integral[ty + fw * 2];
73
                anchors[4] -= anchors[5];
Marina Kolpakova's avatar
Marina Kolpakova committed
74
                anchors[5] -= integral[ty + fw * 3];
75 76 77 78 79 80 81

                anchors[0] -= anchors[3];
                anchors[1] -= anchors[4];
                anchors[2] -= anchors[5];
                // 0 - 2 contains s0 - s2

                ty += fh;
Marina Kolpakova's avatar
Marina Kolpakova committed
82 83
                anchors[6]  = integral[ty];
                anchors[7]  = integral[ty + fw];
84
                anchors[6] -= anchors[7];
Marina Kolpakova's avatar
Marina Kolpakova committed
85
                anchors[8]  = integral[ty + fw * 2];
86
                anchors[7] -= anchors[8];
Marina Kolpakova's avatar
Marina Kolpakova committed
87
                anchors[8] -= integral[ty + fw * 3];
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

                anchors[3] -= anchors[6];
                anchors[4] -= anchors[7];
                anchors[5] -= anchors[8];
                // 3 - 5 contains s3 - s5

                anchors[0] -= anchors[4];
                anchors[1] -= anchors[4];
                anchors[2] -= anchors[4];
                anchors[3] -= anchors[4];
                anchors[5] -= anchors[4];

                int response = (~(anchors[0] >> 31)) & 4;
                response |= (~(anchors[1] >> 31)) & 2;;
                response |= (~(anchors[2] >> 31)) & 1;

                shift = (~(anchors[5] >> 31)) & 16;
                shift |= (~(anchors[3] >> 31)) & 1;

                ty += fh;
Marina Kolpakova's avatar
Marina Kolpakova committed
108 109
                anchors[0]  = integral[ty];
                anchors[1]  = integral[ty + fw];
110
                anchors[0] -= anchors[1];
Marina Kolpakova's avatar
Marina Kolpakova committed
111
                anchors[2]  = integral[ty + fw * 2];
112
                anchors[1] -= anchors[2];
Marina Kolpakova's avatar
Marina Kolpakova committed
113
                anchors[2] -= integral[ty + fw * 3];
114 115 116 117 118 119 120 121 122 123

                anchors[6] -= anchors[0];
                anchors[7] -= anchors[1];
                anchors[8] -= anchors[2];
                // 0 -2 contains s6 - s8

                anchors[6] -= anchors[4];
                anchors[7] -= anchors[4];
                anchors[8] -= anchors[4];

124 125 126 127 128 129 130
                shift |= (~(anchors[6] >> 31)) & 2;
                shift |= (~(anchors[7] >> 31)) & 4;
                shift |= (~(anchors[8] >> 31)) & 8;
                return response;
            }
        };

131
        template<typename Pr>
132
        __global__ void disjoin(int4* candidates, int4* objects, unsigned int n, int groupThreshold, float grouping_eps, unsigned int* nclasses)
133 134 135 136 137
        {
            unsigned int tid = threadIdx.x;
            extern __shared__ int sbuff[];

            int* labels = sbuff;
Anatoly Baksheev's avatar
Anatoly Baksheev committed
138
            int* rrects = sbuff + n;
139 140 141 142 143 144 145 146 147 148 149

            Pr predicate(grouping_eps);
            partition(candidates, n, labels, predicate);

            rrects[tid * 4 + 0] = 0;
            rrects[tid * 4 + 1] = 0;
            rrects[tid * 4 + 2] = 0;
            rrects[tid * 4 + 3] = 0;
            __syncthreads();

            int cls = labels[tid];
150 151 152 153 154
            Emulation::smem::atomicAdd((rrects + cls * 4 + 0), candidates[tid].x);
            Emulation::smem::atomicAdd((rrects + cls * 4 + 1), candidates[tid].y);
            Emulation::smem::atomicAdd((rrects + cls * 4 + 2), candidates[tid].z);
            Emulation::smem::atomicAdd((rrects + cls * 4 + 3), candidates[tid].w);

155
            __syncthreads();
156
            labels[tid] = 0;
157

158
            __syncthreads();
159 160
            Emulation::smem::atomicInc((unsigned int*)labels + cls, n);

161
            __syncthreads();
162
            *nclasses = 0;
163 164 165 166 167 168 169 170 171 172

            int active = labels[tid];
            if (active)
            {
                int* r1 = rrects + tid * 4;
                float s = 1.f / active;
                r1[0] = saturate_cast<int>(r1[0] * s);
                r1[1] = saturate_cast<int>(r1[1] * s);
                r1[2] = saturate_cast<int>(r1[2] * s);
                r1[3] = saturate_cast<int>(r1[3] * s);
173 174
            }
            __syncthreads();
175

176 177
            if (active && active >= groupThreshold)
            {
178 179
                int* r1 = rrects + tid * 4;
                int4 r_out = make_int4(r1[0], r1[1], r1[2], r1[3]);
Anatoly Baksheev's avatar
Anatoly Baksheev committed
180

181
                int aidx = Emulation::smem::atomicInc(nclasses, n);
182
                objects[aidx] = r_out;
183 184 185
            }
        }

186
        void connectedConmonents(PtrStepSz<int4> candidates, int ncandidates, PtrStepSz<int4> objects, int groupThreshold, float grouping_eps, unsigned int* nclasses)
187
        {
188
            if (!ncandidates) return;
Anatoly Baksheev's avatar
Anatoly Baksheev committed
189 190 191
            int block = ncandidates;
            int smem  = block * ( sizeof(int) + sizeof(int4) );
            disjoin<InSameComponint><<<1, block, smem>>>(candidates, objects, ncandidates, groupThreshold, grouping_eps, nclasses);
192 193 194 195 196 197 198 199 200 201
            cudaSafeCall( cudaGetLastError() );
        }

        struct Cascade
        {
            __host__ __device__ __forceinline__ Cascade(const Stage* _stages, int _nstages, const ClNode* _nodes, const float* _leaves,
                const int* _subsets, const uchar4* _features, int _subsetSize)

            : stages(_stages), nstages(_nstages), nodes(_nodes), leaves(_leaves), subsets(_subsets), features(_features), subsetSize(_subsetSize){}

marina.kolpakova's avatar
marina.kolpakova committed
202
            __device__ __forceinline__ bool operator() (int y, int x, int* integral, const int pitch) const
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            {
                int current_node = 0;
                int current_leave = 0;

                for (int s = 0; s < nstages; ++s)
                {
                    float sum = 0;
                    Stage stage = stages[s];
                    for (int t = 0; t < stage.ntrees; t++)
                    {
                        ClNode node = nodes[current_node];
                        uchar4 feature = features[node.featureIdx];

                        int shift;
                        int c = evaluator(integral, (y + feature.y) * pitch + x + feature.x, feature.w * pitch, feature.z, shift);
                        int idx =  (subsets[ current_node * subsetSize + c] & ( 1 << shift)) ? current_leave : current_leave + 1;
                        sum += leaves[idx];

                        current_node += 1;
                        current_leave += 2;
                    }

                    if (sum < stage.threshold)
                        return false;
                }

                return true;
            }

            const Stage*  stages;
            const int nstages;

            const ClNode* nodes;
            const float* leaves;
            const int* subsets;
            const uchar4* features;

            const int subsetSize;
            const LBP evaluator;
        };

        // stepShift, scale, width_k, sum_prev => y =  sum_prev + tid_k / width_k, x = tid_k - tid_k / width_k
        __global__ void lbp_cascade(const Cascade cascade, int frameW, int frameH, int windowW, int windowH, float scale, const float factor,
246
            const int total, int* integral, const int pitch, PtrStepSz<int4> objects, unsigned int* classified)
247 248
        {
            int ftid = blockIdx.x * blockDim.x + threadIdx.x;
marina.kolpakova's avatar
marina.kolpakova committed
249
            if (ftid >= total) return;
250

marina.kolpakova's avatar
marina.kolpakova committed
251
            int step = (scale <= 2.f);
252

marina.kolpakova's avatar
marina.kolpakova committed
253 254 255
            int windowsForLine = (__float2int_rn( __fdividef(frameW, scale)) - windowW) >> step;
            int stotal = windowsForLine * ( (__float2int_rn( __fdividef(frameH, scale)) - windowH) >> step);
            int wshift = 0;
256

marina.kolpakova's avatar
marina.kolpakova committed
257
            int scaleTid = ftid;
258

marina.kolpakova's avatar
marina.kolpakova committed
259
            while (scaleTid >= stotal)
260
            {
marina.kolpakova's avatar
marina.kolpakova committed
261 262
                scaleTid -= stotal;
                wshift += __float2int_rn(__fdividef(frameW, scale)) + 1;
263
                scale *= factor;
marina.kolpakova's avatar
marina.kolpakova committed
264 265 266
                step = (scale <= 2.f);
                windowsForLine = ( ((__float2int_rn(__fdividef(frameW, scale)) - windowW) >> step));
                stotal = windowsForLine * ( (__float2int_rn(__fdividef(frameH, scale)) - windowH) >> step);
267 268
            }

marina.kolpakova's avatar
marina.kolpakova committed
269 270
            int y = __fdividef(scaleTid, windowsForLine);
            int x = scaleTid - y * windowsForLine;
271

marina.kolpakova's avatar
marina.kolpakova committed
272 273
            x <<= step;
            y <<= step;
274

marina.kolpakova's avatar
marina.kolpakova committed
275
            if (cascade(y, x + wshift, integral, pitch))
276
            {
marina.kolpakova's avatar
marina.kolpakova committed
277
                if(x >= __float2int_rn(__fdividef(frameW, scale)) - windowW) return;
278

marina.kolpakova's avatar
marina.kolpakova committed
279 280 281 282 283
                int4 rect;
                rect.x = __float2int_rn(x * scale);
                rect.y = __float2int_rn(y * scale);
                rect.z = __float2int_rn(windowW * scale);
                rect.w = __float2int_rn(windowH * scale);
284

285
                int res = atomicInc(classified, (unsigned int)objects.cols);
286 287 288 289 290
                objects(0, res) = rect;
            }
        }

        void classifyPyramid(int frameW, int frameH, int windowW, int windowH, float initialScale, float factor, int workAmount,
291 292
            const PtrStepSzb& mstages, const int nstages, const PtrStepSzi& mnodes, const PtrStepSzf& mleaves, const PtrStepSzi& msubsets, const PtrStepSzb& mfeatures,
            const int subsetSize, PtrStepSz<int4> objects, unsigned int* classified, PtrStepSzi integral)
293
        {
marina.kolpakova's avatar
marina.kolpakova committed
294
            const int block = 128;
295
            int grid = divUp(workAmount, block);
296
            cudaFuncSetCacheConfig(lbp_cascade, cudaFuncCachePreferL1);
297
            Cascade cascade((Stage*)mstages.ptr(), nstages, (ClNode*)mnodes.ptr(), mleaves.ptr(), msubsets.ptr(), (uchar4*)mfeatures.ptr(), subsetSize);
298
            lbp_cascade<<<grid, block>>>(cascade, frameW, frameH, windowW, windowH, initialScale, factor, workAmount, integral.ptr(), (int)integral.step / sizeof(int), objects, classified);
299
        }
300
    }
301 302
}}}

303
#endif /* CUDA_DISABLER */