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

#include "precomp.hpp"

V
Vladislav Vinogradov 已提交
45 46
using namespace cv;
using namespace cv::gpu;
47

48
#if !defined(HAVE_CUDA) || defined(CUDA_DISABLER) || !defined(HAVE_OPENCV_IMGPROC) || !defined(HAVE_OPENCV_GPUARITHM) || !defined(HAVE_OPENCV_GPUIMGPROC)
49

V
Vladislav Vinogradov 已提交
50
cv::gpu::FGDParams::FGDParams() { throw_no_cuda(); }
51

V
Vladislav Vinogradov 已提交
52
Ptr<gpu::BackgroundSubtractorFGD> cv::gpu::createBackgroundSubtractorFGD(const FGDParams&) { throw_no_cuda(); return Ptr<gpu::BackgroundSubtractorFGD>(); }
53 54 55

#else

56
#include "cuda/fgd.hpp"
V
Vladislav Vinogradov 已提交
57
#include "opencv2/imgproc/imgproc_c.h"
58

V
Vladislav Vinogradov 已提交
59 60 61
/////////////////////////////////////////////////////////////////////////
// FGDParams

62 63
namespace
{
V
Vladislav Vinogradov 已提交
64 65 66 67
    // Default parameters of foreground detection algorithm:
    const int BGFG_FGD_LC  = 128;
    const int BGFG_FGD_N1C = 15;
    const int BGFG_FGD_N2C = 25;
68

V
Vladislav Vinogradov 已提交
69 70 71
    const int BGFG_FGD_LCC   = 64;
    const int BGFG_FGD_N1CC = 25;
    const int BGFG_FGD_N2CC = 40;
72

V
Vladislav Vinogradov 已提交
73 74
    // Background reference image update parameter:
    const float BGFG_FGD_ALPHA_1 = 0.1f;
75

V
Vladislav Vinogradov 已提交
76 77 78
    // stat model update parameter
    // 0.002f ~ 1K frame(~45sec), 0.005 ~ 18sec (if 25fps and absolutely static BG)
    const float BGFG_FGD_ALPHA_2 = 0.005f;
79

V
Vladislav Vinogradov 已提交
80 81
    // start value for alpha parameter (to fast initiate statistic model)
    const float BGFG_FGD_ALPHA_3 = 0.1f;
82

V
Vladislav Vinogradov 已提交
83
    const float BGFG_FGD_DELTA = 2.0f;
84

V
Vladislav Vinogradov 已提交
85
    const float BGFG_FGD_T = 0.9f;
86

V
Vladislav Vinogradov 已提交
87
    const float BGFG_FGD_MINAREA= 15.0f;
88 89
}

V
Vladislav Vinogradov 已提交
90
cv::gpu::FGDParams::FGDParams()
91
{
V
Vladislav Vinogradov 已提交
92 93 94
    Lc      = BGFG_FGD_LC;
    N1c     = BGFG_FGD_N1C;
    N2c     = BGFG_FGD_N2C;
95

V
Vladislav Vinogradov 已提交
96 97 98
    Lcc     = BGFG_FGD_LCC;
    N1cc    = BGFG_FGD_N1CC;
    N2cc    = BGFG_FGD_N2CC;
99

V
Vladislav Vinogradov 已提交
100
    delta   = BGFG_FGD_DELTA;
101

V
Vladislav Vinogradov 已提交
102 103 104
    alpha1  = BGFG_FGD_ALPHA_1;
    alpha2  = BGFG_FGD_ALPHA_2;
    alpha3  = BGFG_FGD_ALPHA_3;
105

V
Vladislav Vinogradov 已提交
106 107
    T       = BGFG_FGD_T;
    minArea = BGFG_FGD_MINAREA;
108

V
Vladislav Vinogradov 已提交
109 110
    is_obj_without_holes = true;
    perform_morphing     = 1;
111 112
}

V
Vladislav Vinogradov 已提交
113 114
/////////////////////////////////////////////////////////////////////////
// copyChannels
115 116 117

namespace
{
V
Vladislav Vinogradov 已提交
118
    void copyChannels(const GpuMat& src, GpuMat& dst, int dst_cn = -1)
119 120 121 122 123 124
    {
        const int src_cn = src.channels();

        if (dst_cn < 0)
            dst_cn = src_cn;

V
Vladislav Vinogradov 已提交
125
        gpu::ensureSizeIsEnough(src.size(), CV_MAKE_TYPE(src.depth(), dst_cn), dst);
126 127

        if (src_cn == dst_cn)
V
Vladislav Vinogradov 已提交
128
        {
129
            src.copyTo(dst);
V
Vladislav Vinogradov 已提交
130
        }
131 132 133 134
        else
        {
            static const int cvt_codes[4][4] =
            {
V
Vladislav Vinogradov 已提交
135
                {-1, -1, COLOR_GRAY2BGR, COLOR_GRAY2BGRA},
136
                {-1, -1, -1, -1},
V
Vladislav Vinogradov 已提交
137 138
                {COLOR_BGR2GRAY, -1, -1, COLOR_BGR2BGRA},
                {COLOR_BGRA2GRAY, -1, COLOR_BGRA2BGR, -1}
139 140 141 142 143
            };

            const int cvt_code = cvt_codes[src_cn - 1][dst_cn - 1];
            CV_DbgAssert( cvt_code >= 0 );

V
Vladislav Vinogradov 已提交
144
            gpu::cvtColor(src, dst, cvt_code, dst_cn);
145 146 147 148 149 150 151 152 153
        }
    }
}

/////////////////////////////////////////////////////////////////////////
// changeDetection

namespace
{
V
Vladislav Vinogradov 已提交
154
    void calcDiffHistogram(const GpuMat& prevFrame, const GpuMat& curFrame, GpuMat& hist, GpuMat& histBuf)
155
    {
V
Vladislav Vinogradov 已提交
156 157 158 159
        typedef void (*func_t)(PtrStepSzb prevFrame, PtrStepSzb curFrame,
                               unsigned int* hist0, unsigned int* hist1, unsigned int* hist2,
                               unsigned int* partialBuf0, unsigned int* partialBuf1, unsigned int* partialBuf2,
                               bool cc20, cudaStream_t stream);
160 161 162 163
        static const func_t funcs[4][4] =
        {
            {0,0,0,0},
            {0,0,0,0},
V
Vladislav Vinogradov 已提交
164 165
            {0,0,fgd::calcDiffHistogram_gpu<uchar3, uchar3>,fgd::calcDiffHistogram_gpu<uchar3, uchar4>},
            {0,0,fgd::calcDiffHistogram_gpu<uchar4, uchar3>,fgd::calcDiffHistogram_gpu<uchar4, uchar4>}
166 167 168
        };

        hist.create(3, 256, CV_32SC1);
V
Vladislav Vinogradov 已提交
169
        histBuf.create(3, fgd::PARTIAL_HISTOGRAM_COUNT * fgd::HISTOGRAM_BIN_COUNT, CV_32SC1);
170 171 172 173 174

        funcs[prevFrame.channels() - 1][curFrame.channels() - 1](
                    prevFrame, curFrame,
                    hist.ptr<unsigned int>(0), hist.ptr<unsigned int>(1), hist.ptr<unsigned int>(2),
                    histBuf.ptr<unsigned int>(0), histBuf.ptr<unsigned int>(1), histBuf.ptr<unsigned int>(2),
V
Vladislav Vinogradov 已提交
175
                    deviceSupports(FEATURE_SET_COMPUTE_20), 0);
176 177
    }

V
Vladislav Vinogradov 已提交
178
    void calcRelativeVariance(unsigned int hist[3 * 256], double relativeVariance[3][fgd::HISTOGRAM_BIN_COUNT])
179
    {
V
Vladislav Vinogradov 已提交
180
        std::memset(relativeVariance, 0, 3 * fgd::HISTOGRAM_BIN_COUNT * sizeof(double));
181

V
Vladislav Vinogradov 已提交
182
        for (int thres = fgd::HISTOGRAM_BIN_COUNT - 2; thres >= 0; --thres)
183
        {
V
Vladislav Vinogradov 已提交
184 185 186
            Vec3d sum(0.0, 0.0, 0.0);
            Vec3d sqsum(0.0, 0.0, 0.0);
            Vec3i count(0, 0, 0);
187

V
Vladislav Vinogradov 已提交
188
            for (int j = thres; j < fgd::HISTOGRAM_BIN_COUNT; ++j)
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            {
                sum[0]   += static_cast<double>(j) * hist[j];
                sqsum[0] += static_cast<double>(j * j) * hist[j];
                count[0] += hist[j];

                sum[1]   += static_cast<double>(j) * hist[j + 256];
                sqsum[1] += static_cast<double>(j * j) * hist[j + 256];
                count[1] += hist[j + 256];

                sum[2]   += static_cast<double>(j) * hist[j + 512];
                sqsum[2] += static_cast<double>(j * j) * hist[j + 512];
                count[2] += hist[j + 512];
            }

            count[0] = std::max(count[0], 1);
            count[1] = std::max(count[1], 1);
            count[2] = std::max(count[2], 1);

V
Vladislav Vinogradov 已提交
207
            Vec3d my(
208 209 210 211 212 213 214 215 216 217 218
                sum[0] / count[0],
                sum[1] / count[1],
                sum[2] / count[2]
            );

            relativeVariance[0][thres] = std::sqrt(sqsum[0] / count[0] - my[0] * my[0]);
            relativeVariance[1][thres] = std::sqrt(sqsum[1] / count[1] - my[1] * my[1]);
            relativeVariance[2][thres] = std::sqrt(sqsum[2] / count[2] - my[2] * my[2]);
        }
    }

V
Vladislav Vinogradov 已提交
219
    void calcDiffThreshMask(const GpuMat& prevFrame, const GpuMat& curFrame, Vec3d bestThres, GpuMat& changeMask)
220
    {
V
Vladislav Vinogradov 已提交
221
        typedef void (*func_t)(PtrStepSzb prevFrame, PtrStepSzb curFrame, uchar3 bestThres, PtrStepSzb changeMask, cudaStream_t stream);
222 223 224 225
        static const func_t funcs[4][4] =
        {
            {0,0,0,0},
            {0,0,0,0},
V
Vladislav Vinogradov 已提交
226 227
            {0,0,fgd::calcDiffThreshMask_gpu<uchar3, uchar3>,fgd::calcDiffThreshMask_gpu<uchar3, uchar4>},
            {0,0,fgd::calcDiffThreshMask_gpu<uchar4, uchar3>,fgd::calcDiffThreshMask_gpu<uchar4, uchar4>}
228 229
        };

V
Vladislav Vinogradov 已提交
230
        changeMask.setTo(Scalar::all(0));
231

V
Vladislav Vinogradov 已提交
232 233 234
        funcs[prevFrame.channels() - 1][curFrame.channels() - 1](prevFrame, curFrame,
                                                                 make_uchar3((uchar)bestThres[0], (uchar)bestThres[1], (uchar)bestThres[2]),
                                                                 changeMask, 0);
235 236 237
    }

    // performs change detection for Foreground detection algorithm
V
Vladislav Vinogradov 已提交
238
    void changeDetection(const GpuMat& prevFrame, const GpuMat& curFrame, GpuMat& changeMask, GpuMat& hist, GpuMat& histBuf)
239 240 241 242
    {
        calcDiffHistogram(prevFrame, curFrame, hist, histBuf);

        unsigned int histData[3 * 256];
V
Vladislav Vinogradov 已提交
243
        Mat h_hist(3, 256, CV_32SC1, histData);
244 245
        hist.download(h_hist);

V
Vladislav Vinogradov 已提交
246
        double relativeVariance[3][fgd::HISTOGRAM_BIN_COUNT];
247 248 249
        calcRelativeVariance(histData, relativeVariance);

        // Find maximum:
V
Vladislav Vinogradov 已提交
250 251
        Vec3d bestThres(10.0, 10.0, 10.0);
        for (int i = 0; i < fgd::HISTOGRAM_BIN_COUNT; ++i)
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
        {
            bestThres[0] = std::max(bestThres[0], relativeVariance[0][i]);
            bestThres[1] = std::max(bestThres[1], relativeVariance[1][i]);
            bestThres[2] = std::max(bestThres[2], relativeVariance[2][i]);
        }

        calcDiffThreshMask(prevFrame, curFrame, bestThres, changeMask);
    }
}

/////////////////////////////////////////////////////////////////////////
// bgfgClassification

namespace
{
V
Vladislav Vinogradov 已提交
267 268 269 270
    int bgfgClassification(const GpuMat& prevFrame, const GpuMat& curFrame,
                           const GpuMat& Ftd, const GpuMat& Fbd,
                           GpuMat& foreground, GpuMat& countBuf,
                           const FGDParams& params, int out_cn)
271
    {
V
Vladislav Vinogradov 已提交
272
        typedef void (*func_t)(PtrStepSzb prevFrame, PtrStepSzb curFrame, PtrStepSzb Ftd, PtrStepSzb Fbd, PtrStepSzb foreground,
273 274 275 276 277 278 279 280 281 282 283
                               int deltaC, int deltaCC, float alpha2, int N1c, int N1cc, cudaStream_t stream);
        static const func_t funcs[4][4][4] =
        {
            {
                {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}
            },
            {
                {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}
            },
            {
                {0,0,0,0}, {0,0,0,0},
V
Vladislav Vinogradov 已提交
284 285
                {0,0,fgd::bgfgClassification_gpu<uchar3, uchar3, uchar3>,fgd::bgfgClassification_gpu<uchar3, uchar3, uchar4>},
                {0,0,fgd::bgfgClassification_gpu<uchar3, uchar4, uchar3>,fgd::bgfgClassification_gpu<uchar3, uchar4, uchar4>}
286 287 288
            },
            {
                {0,0,0,0}, {0,0,0,0},
V
Vladislav Vinogradov 已提交
289 290
                {0,0,fgd::bgfgClassification_gpu<uchar4, uchar3, uchar3>,fgd::bgfgClassification_gpu<uchar4, uchar3, uchar4>},
                {0,0,fgd::bgfgClassification_gpu<uchar4, uchar4, uchar3>,fgd::bgfgClassification_gpu<uchar4, uchar4, uchar4>}
291 292 293 294 295 296
            }
        };

        const int deltaC  = cvRound(params.delta * 256 / params.Lc);
        const int deltaCC = cvRound(params.delta * 256 / params.Lcc);

V
Vladislav Vinogradov 已提交
297 298 299
        funcs[prevFrame.channels() - 1][curFrame.channels() - 1][out_cn - 1](prevFrame, curFrame, Ftd, Fbd, foreground,
                                                                             deltaC, deltaCC, params.alpha2,
                                                                             params.N1c, params.N1cc, 0);
300

V
Vladislav Vinogradov 已提交
301
        int count = gpu::countNonZero(foreground, countBuf);
302

V
Vladislav Vinogradov 已提交
303
        gpu::multiply(foreground, Scalar::all(255), foreground);
304 305 306 307 308 309 310 311

        return count;
    }
}

/////////////////////////////////////////////////////////////////////////
// smoothForeground

312 313
#ifdef HAVE_OPENCV_GPUFILTERS

314 315
namespace
{
V
Vladislav Vinogradov 已提交
316
    void morphology(const GpuMat& src, GpuMat& dst, GpuMat& filterBrd, int brd, Ptr<gpu::Filter>& filter, Scalar brdVal)
317
    {
V
Vladislav Vinogradov 已提交
318 319
        gpu::copyMakeBorder(src, filterBrd, brd, brd, brd, brd, BORDER_CONSTANT, brdVal);
        filter->apply(filterBrd(Rect(brd, brd, src.cols, src.rows)), dst);
320 321
    }

V
Vladislav Vinogradov 已提交
322 323 324
    void smoothForeground(GpuMat& foreground, GpuMat& filterBrd, GpuMat& buf,
                          Ptr<gpu::Filter>& erodeFilter, Ptr<gpu::Filter>& dilateFilter,
                          const FGDParams& params)
325 326 327
    {
        const int brd = params.perform_morphing;

V
Vladislav Vinogradov 已提交
328 329
        const Scalar erodeBrdVal = Scalar::all(UCHAR_MAX);
        const Scalar dilateBrdVal = Scalar::all(0);
330 331 332 333 334 335 336 337 338 339 340

        // MORPH_OPEN
        morphology(foreground, buf, filterBrd, brd, erodeFilter, erodeBrdVal);
        morphology(buf, foreground, filterBrd, brd, dilateFilter, dilateBrdVal);

        // MORPH_CLOSE
        morphology(foreground, buf, filterBrd, brd, dilateFilter, dilateBrdVal);
        morphology(buf, foreground, filterBrd, brd, erodeFilter, erodeBrdVal);
    }
}

341 342
#endif

343 344 345 346 347
/////////////////////////////////////////////////////////////////////////
// findForegroundRegions

namespace
{
V
Vladislav Vinogradov 已提交
348
    void seqToContours(CvSeq* _ccontours, CvMemStorage* storage, OutputArrayOfArrays _contours)
349
    {
V
Vladislav Vinogradov 已提交
350
        Seq<CvSeq*> all_contours(cvTreeToNodeSeq(_ccontours, sizeof(CvSeq), storage));
351 352 353

        size_t total = all_contours.size();

354
        _contours.create((int) total, 1, 0, -1, true);
355

V
Vladislav Vinogradov 已提交
356
        SeqIterator<CvSeq*> it = all_contours.begin();
357 358 359 360
        for (size_t i = 0; i < total; ++i, ++it)
        {
            CvSeq* c = *it;
            ((CvContour*)c)->color = (int)i;
361
            _contours.create((int)c->total, 1, CV_32SC2, (int)i, true);
V
Vladislav Vinogradov 已提交
362
            Mat ci = _contours.getMat((int)i);
363 364 365 366 367
            CV_Assert( ci.isContinuous() );
            cvCvtSeqToArray(c, ci.data);
        }
    }

V
Vladislav Vinogradov 已提交
368 369
    int findForegroundRegions(GpuMat& d_foreground, Mat& h_foreground, std::vector< std::vector<Point> >& foreground_regions,
                              CvMemStorage* storage, const FGDParams& params)
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
    {
        int region_count = 0;

        // Discard under-size foreground regions:

        d_foreground.download(h_foreground);
        IplImage ipl_foreground = h_foreground;
        CvSeq* first_seq = 0;

        cvFindContours(&ipl_foreground, storage, &first_seq, sizeof(CvContour), CV_RETR_LIST);

        for (CvSeq* seq = first_seq; seq; seq = seq->h_next)
        {
            CvContour* cnt = reinterpret_cast<CvContour*>(seq);

            if (cnt->rect.width * cnt->rect.height < params.minArea || (params.is_obj_without_holes && CV_IS_SEQ_HOLE(seq)))
            {
                // Delete under-size contour:
                CvSeq* prev_seq = seq->h_prev;
                if (prev_seq)
                {
                    prev_seq->h_next = seq->h_next;

                    if (seq->h_next)
                        seq->h_next->h_prev = prev_seq;
                }
                else
                {
                    first_seq = seq->h_next;

                    if (seq->h_next)
                        seq->h_next->h_prev = NULL;
                }
            }
            else
            {
                region_count++;
            }
        }

        seqToContours(first_seq, storage, foreground_regions);
        h_foreground.setTo(0);

V
Vladislav Vinogradov 已提交
413
        drawContours(h_foreground, foreground_regions, -1, Scalar::all(255), -1);
414 415 416 417 418 419 420 421 422 423 424 425

        d_foreground.upload(h_foreground);

        return region_count;
    }
}

/////////////////////////////////////////////////////////////////////////
// updateBackgroundModel

namespace
{
V
Vladislav Vinogradov 已提交
426 427 428
    void updateBackgroundModel(const GpuMat& prevFrame, const GpuMat& curFrame, const GpuMat& Ftd, const GpuMat& Fbd,
                               const GpuMat& foreground, GpuMat& background,
                               const FGDParams& params)
429
    {
V
Vladislav Vinogradov 已提交
430 431
        typedef void (*func_t)(PtrStepSzb prevFrame, PtrStepSzb curFrame, PtrStepSzb Ftd, PtrStepSzb Fbd,
                               PtrStepSzb foreground, PtrStepSzb background,
432 433 434 435 436 437 438 439 440 441 442
                               int deltaC, int deltaCC, float alpha1, float alpha2, float alpha3, int N1c, int N1cc, int N2c, int N2cc, float T, cudaStream_t stream);
        static const func_t funcs[4][4][4] =
        {
            {
                {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}
            },
            {
                {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}
            },
            {
                {0,0,0,0}, {0,0,0,0},
V
Vladislav Vinogradov 已提交
443 444
                {0,0,fgd::updateBackgroundModel_gpu<uchar3, uchar3, uchar3>,fgd::updateBackgroundModel_gpu<uchar3, uchar3, uchar4>},
                {0,0,fgd::updateBackgroundModel_gpu<uchar3, uchar4, uchar3>,fgd::updateBackgroundModel_gpu<uchar3, uchar4, uchar4>}
445 446 447
            },
            {
                {0,0,0,0}, {0,0,0,0},
V
Vladislav Vinogradov 已提交
448 449
                {0,0,fgd::updateBackgroundModel_gpu<uchar4, uchar3, uchar3>,fgd::updateBackgroundModel_gpu<uchar4, uchar3, uchar4>},
                {0,0,fgd::updateBackgroundModel_gpu<uchar4, uchar4, uchar3>,fgd::updateBackgroundModel_gpu<uchar4, uchar4, uchar4>}
450 451 452 453 454 455 456 457
            }
        };

        const int deltaC  = cvRound(params.delta * 256 / params.Lc);
        const int deltaCC = cvRound(params.delta * 256 / params.Lcc);

        funcs[prevFrame.channels() - 1][curFrame.channels() - 1][background.channels() - 1](
                    prevFrame, curFrame, Ftd, Fbd, foreground, background,
V
Vladislav Vinogradov 已提交
458 459
                    deltaC, deltaCC, params.alpha1, params.alpha2, params.alpha3,
                    params.N1c, params.N1cc, params.N2c, params.N2cc, params.T,
460 461 462 463 464
                    0);
    }
}


V
Vladislav Vinogradov 已提交
465
namespace
466
{
V
Vladislav Vinogradov 已提交
467 468 469 470 471 472 473 474
    class BGPixelStat
    {
    public:
        void create(Size size, const FGDParams& params);

        void setTrained();

        operator fgd::BGPixelStat();
475

V
Vladislav Vinogradov 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    private:
        GpuMat Pbc_;
        GpuMat Pbcc_;
        GpuMat is_trained_st_model_;
        GpuMat is_trained_dyn_model_;

        GpuMat ctable_Pv_;
        GpuMat ctable_Pvb_;
        GpuMat ctable_v_;

        GpuMat cctable_Pv_;
        GpuMat cctable_Pvb_;
        GpuMat cctable_v1_;
        GpuMat cctable_v2_;
    };
491

V
Vladislav Vinogradov 已提交
492 493 494 495
    void BGPixelStat::create(Size size, const FGDParams& params)
    {
        gpu::ensureSizeIsEnough(size, CV_32FC1, Pbc_);
        Pbc_.setTo(Scalar::all(0));
496

V
Vladislav Vinogradov 已提交
497 498
        gpu::ensureSizeIsEnough(size, CV_32FC1, Pbcc_);
        Pbcc_.setTo(Scalar::all(0));
499

V
Vladislav Vinogradov 已提交
500 501
        gpu::ensureSizeIsEnough(size, CV_8UC1, is_trained_st_model_);
        is_trained_st_model_.setTo(Scalar::all(0));
502

V
Vladislav Vinogradov 已提交
503 504
        gpu::ensureSizeIsEnough(size, CV_8UC1, is_trained_dyn_model_);
        is_trained_dyn_model_.setTo(Scalar::all(0));
505

V
Vladislav Vinogradov 已提交
506 507
        gpu::ensureSizeIsEnough(params.N2c * size.height, size.width, CV_32FC1, ctable_Pv_);
        ctable_Pv_.setTo(Scalar::all(0));
508

V
Vladislav Vinogradov 已提交
509 510
        gpu::ensureSizeIsEnough(params.N2c * size.height, size.width, CV_32FC1, ctable_Pvb_);
        ctable_Pvb_.setTo(Scalar::all(0));
511

V
Vladislav Vinogradov 已提交
512 513
        gpu::ensureSizeIsEnough(params.N2c * size.height, size.width, CV_8UC4, ctable_v_);
        ctable_v_.setTo(Scalar::all(0));
514

V
Vladislav Vinogradov 已提交
515 516
        gpu::ensureSizeIsEnough(params.N2cc * size.height, size.width, CV_32FC1, cctable_Pv_);
        cctable_Pv_.setTo(Scalar::all(0));
517

V
Vladislav Vinogradov 已提交
518 519
        gpu::ensureSizeIsEnough(params.N2cc * size.height, size.width, CV_32FC1, cctable_Pvb_);
        cctable_Pvb_.setTo(Scalar::all(0));
520

V
Vladislav Vinogradov 已提交
521 522
        gpu::ensureSizeIsEnough(params.N2cc * size.height, size.width, CV_8UC4, cctable_v1_);
        cctable_v1_.setTo(Scalar::all(0));
523

V
Vladislav Vinogradov 已提交
524 525 526
        gpu::ensureSizeIsEnough(params.N2cc * size.height, size.width, CV_8UC4, cctable_v2_);
        cctable_v2_.setTo(Scalar::all(0));
    }
527

V
Vladislav Vinogradov 已提交
528 529 530 531 532
    void BGPixelStat::setTrained()
    {
        is_trained_st_model_.setTo(Scalar::all(1));
        is_trained_dyn_model_.setTo(Scalar::all(1));
    }
533

V
Vladislav Vinogradov 已提交
534 535 536
    BGPixelStat::operator fgd::BGPixelStat()
    {
        fgd::BGPixelStat stat;
537

V
Vladislav Vinogradov 已提交
538
        stat.rows_ = Pbc_.rows;
539

V
Vladislav Vinogradov 已提交
540 541
        stat.Pbc_data_ = Pbc_.data;
        stat.Pbc_step_ = Pbc_.step;
542

V
Vladislav Vinogradov 已提交
543 544
        stat.Pbcc_data_ = Pbcc_.data;
        stat.Pbcc_step_ = Pbcc_.step;
545

V
Vladislav Vinogradov 已提交
546 547
        stat.is_trained_st_model_data_ = is_trained_st_model_.data;
        stat.is_trained_st_model_step_ = is_trained_st_model_.step;
548

V
Vladislav Vinogradov 已提交
549 550
        stat.is_trained_dyn_model_data_ = is_trained_dyn_model_.data;
        stat.is_trained_dyn_model_step_ = is_trained_dyn_model_.step;
551

V
Vladislav Vinogradov 已提交
552 553
        stat.ctable_Pv_data_ = ctable_Pv_.data;
        stat.ctable_Pv_step_ = ctable_Pv_.step;
554

V
Vladislav Vinogradov 已提交
555 556
        stat.ctable_Pvb_data_ = ctable_Pvb_.data;
        stat.ctable_Pvb_step_ = ctable_Pvb_.step;
557

V
Vladislav Vinogradov 已提交
558 559
        stat.ctable_v_data_ = ctable_v_.data;
        stat.ctable_v_step_ = ctable_v_.step;
560

V
Vladislav Vinogradov 已提交
561 562
        stat.cctable_Pv_data_ = cctable_Pv_.data;
        stat.cctable_Pv_step_ = cctable_Pv_.step;
563

V
Vladislav Vinogradov 已提交
564 565
        stat.cctable_Pvb_data_ = cctable_Pvb_.data;
        stat.cctable_Pvb_step_ = cctable_Pvb_.step;
566

V
Vladislav Vinogradov 已提交
567 568
        stat.cctable_v1_data_ = cctable_v1_.data;
        stat.cctable_v1_step_ = cctable_v1_.step;
569

V
Vladislav Vinogradov 已提交
570 571
        stat.cctable_v2_data_ = cctable_v2_.data;
        stat.cctable_v2_step_ = cctable_v2_.step;
572

V
Vladislav Vinogradov 已提交
573 574
        return stat;
    }
575

V
Vladislav Vinogradov 已提交
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
    class FGDImpl : public gpu::BackgroundSubtractorFGD
    {
    public:
        explicit FGDImpl(const FGDParams& params);
        ~FGDImpl();

        void apply(InputArray image, OutputArray fgmask, double learningRate=-1);

        void getBackgroundImage(OutputArray backgroundImage) const;

        void getForegroundRegions(OutputArrayOfArrays foreground_regions);

    private:
        void initialize(const GpuMat& firstFrame);

        FGDParams params_;
        Size frameSize_;

        GpuMat background_;
        GpuMat foreground_;
        std::vector< std::vector<Point> > foreground_regions_;

        Mat h_foreground_;

        GpuMat prevFrame_;
        GpuMat Ftd_;
        GpuMat Fbd_;
        BGPixelStat stat_;

        GpuMat hist_;
        GpuMat histBuf_;

        GpuMat countBuf_;

        GpuMat buf_;
        GpuMat filterBrd_;

613
#ifdef HAVE_OPENCV_GPUFILTERS
V
Vladislav Vinogradov 已提交
614 615
        Ptr<gpu::Filter> dilateFilter_;
        Ptr<gpu::Filter> erodeFilter_;
616
#endif
V
Vladislav Vinogradov 已提交
617 618 619 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

        CvMemStorage* storage_;
    };

    FGDImpl::FGDImpl(const FGDParams& params) : params_(params), frameSize_(0, 0)
    {
        storage_ = cvCreateMemStorage();
        CV_Assert( storage_ != 0 );
    }

    FGDImpl::~FGDImpl()
    {
        cvReleaseMemStorage(&storage_);
    }

    void FGDImpl::apply(InputArray _frame, OutputArray fgmask, double)
    {
        GpuMat curFrame = _frame.getGpuMat();

        if (curFrame.size() != frameSize_)
        {
            initialize(curFrame);
            return;
        }

        CV_Assert( curFrame.type() == CV_8UC3 || curFrame.type() == CV_8UC4 );
        CV_Assert( curFrame.size() == prevFrame_.size() );

        cvClearMemStorage(storage_);
        foreground_regions_.clear();
        foreground_.setTo(Scalar::all(0));

        changeDetection(prevFrame_, curFrame, Ftd_, hist_, histBuf_);
        changeDetection(background_, curFrame, Fbd_, hist_, histBuf_);

        int FG_pixels_count = bgfgClassification(prevFrame_, curFrame, Ftd_, Fbd_, foreground_, countBuf_, params_, 4);

654
#ifdef HAVE_OPENCV_GPUFILTERS
V
Vladislav Vinogradov 已提交
655 656
        if (params_.perform_morphing > 0)
            smoothForeground(foreground_, filterBrd_, buf_, erodeFilter_, dilateFilter_, params_);
657
#endif
V
Vladislav Vinogradov 已提交
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

        if (params_.minArea > 0 || params_.is_obj_without_holes)
            findForegroundRegions(foreground_, h_foreground_, foreground_regions_, storage_, params_);

        // Check ALL BG update condition:
        const double BGFG_FGD_BG_UPDATE_TRESH = 0.5;
        if (static_cast<double>(FG_pixels_count) / Ftd_.size().area() > BGFG_FGD_BG_UPDATE_TRESH)
            stat_.setTrained();

        updateBackgroundModel(prevFrame_, curFrame, Ftd_, Fbd_, foreground_, background_, params_);

        copyChannels(curFrame, prevFrame_, 4);

        foreground_.copyTo(fgmask);
    }

    void FGDImpl::getBackgroundImage(OutputArray backgroundImage) const
    {
        gpu::cvtColor(background_, backgroundImage, COLOR_BGRA2BGR);
    }

    void FGDImpl::getForegroundRegions(OutputArrayOfArrays dst)
    {
        size_t total = foreground_regions_.size();

        dst.create((int) total, 1, 0, -1, true);

        for (size_t i = 0; i < total; ++i)
        {
            std::vector<Point>& c = foreground_regions_[i];

            dst.create((int) c.size(), 1, CV_32SC2, (int) i, true);
            Mat ci = dst.getMat((int) i);

            Mat(ci.size(), ci.type(), &c[0]).copyTo(ci);
        }
    }

    void FGDImpl::initialize(const GpuMat& firstFrame)
    {
        CV_Assert( firstFrame.type() == CV_8UC3 || firstFrame.type() == CV_8UC4 );

        frameSize_ = firstFrame.size();

        gpu::ensureSizeIsEnough(firstFrame.size(), CV_8UC1, foreground_);

        copyChannels(firstFrame, background_, 4);
        copyChannels(firstFrame, prevFrame_, 4);

        gpu::ensureSizeIsEnough(firstFrame.size(), CV_8UC1, Ftd_);
        gpu::ensureSizeIsEnough(firstFrame.size(), CV_8UC1, Fbd_);

        stat_.create(firstFrame.size(), params_);
        fgd::setBGPixelStat(stat_);

713
#ifdef HAVE_OPENCV_GPUFILTERS
V
Vladislav Vinogradov 已提交
714 715 716 717 718 719 720 721
        if (params_.perform_morphing > 0)
        {
            Mat kernel = getStructuringElement(MORPH_RECT, Size(1 + params_.perform_morphing * 2, 1 + params_.perform_morphing * 2));
            Point anchor(params_.perform_morphing, params_.perform_morphing);

            dilateFilter_ = gpu::createMorphologyFilter(MORPH_DILATE, CV_8UC1, kernel, anchor);
            erodeFilter_ = gpu::createMorphologyFilter(MORPH_ERODE, CV_8UC1, kernel, anchor);
        }
722
#endif
V
Vladislav Vinogradov 已提交
723
    }
724 725
}

V
Vladislav Vinogradov 已提交
726
Ptr<gpu::BackgroundSubtractorFGD> cv::gpu::createBackgroundSubtractorFGD(const FGDParams& params)
727
{
V
Vladislav Vinogradov 已提交
728
    return new FGDImpl(params);
729 730 731
}

#endif // HAVE_CUDA