global_motion.cpp 23.4 KB
Newer Older
Alexey Spizhevoy's avatar
Alexey Spizhevoy 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-2011, 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*/

43 44
#include "precomp.hpp"
#include "opencv2/videostab/global_motion.hpp"
45
#include "opencv2/videostab/ring_buffer.hpp"
46
#include "opencv2/videostab/outlier_rejection.hpp"
47
#include "opencv2/opencv_modules.hpp"
48
#include "clp.hpp"
49

50 51
#ifdef HAVE_OPENCV_CUDA
#  include "opencv2/cuda.hpp"
52 53
#endif

54 55 56 57 58
namespace cv
{
namespace videostab
{

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
// does isotropic normalization
static Mat normalizePoints(int npoints, Point2f *points)
{
    float cx = 0.f, cy = 0.f;
    for (int i = 0; i < npoints; ++i)
    {
        cx += points[i].x;
        cy += points[i].y;
    }
    cx /= npoints;
    cy /= npoints;

    float d = 0.f;
    for (int i = 0; i < npoints; ++i)
    {
        points[i].x -= cx;
        points[i].y -= cy;
76
        d += std::sqrt(sqr(points[i].x) + sqr(points[i].y));
77 78 79
    }
    d /= npoints;

80
    float s = std::sqrt(2.f) / d;
81 82 83 84 85 86 87 88 89 90 91 92 93 94
    for (int i = 0; i < npoints; ++i)
    {
        points[i].x *= s;
        points[i].y *= s;
    }

    Mat_<float> T = Mat::eye(3, 3, CV_32F);
    T(0,0) = T(1,1) = s;
    T(0,2) = -cx*s;
    T(1,2) = -cy*s;
    return T;
}


95
static Mat estimateGlobMotionLeastSquaresTranslation(
96
        int npoints, Point2f *points0, Point2f *points1, float *rmse)
97 98 99 100 101 102 103 104 105
{
    Mat_<float> M = Mat::eye(3, 3, CV_32F);
    for (int i = 0; i < npoints; ++i)
    {
        M(0,2) += points1[i].x - points0[i].x;
        M(1,2) += points1[i].y - points0[i].y;
    }
    M(0,2) /= npoints;
    M(1,2) /= npoints;
106

107 108 109 110 111 112
    if (rmse)
    {
        *rmse = 0;
        for (int i = 0; i < npoints; ++i)
            *rmse += sqr(points1[i].x - points0[i].x - M(0,2)) +
                     sqr(points1[i].y - points0[i].y - M(1,2));
113
        *rmse = std::sqrt(*rmse / npoints);
114
    }
115

116 117 118 119 120
    return M;
}


static Mat estimateGlobMotionLeastSquaresTranslationAndScale(
121
        int npoints, Point2f *points0, Point2f *points1, float *rmse)
122
{
123 124 125
    Mat_<float> T0 = normalizePoints(npoints, points0);
    Mat_<float> T1 = normalizePoints(npoints, points1);

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    Mat_<float> A(2*npoints, 3), b(2*npoints, 1);
    float *a0, *a1;
    Point2f p0, p1;

    for (int i = 0; i < npoints; ++i)
    {
        a0 = A[2*i];
        a1 = A[2*i+1];
        p0 = points0[i];
        p1 = points1[i];
        a0[0] = p0.x; a0[1] = 1; a0[2] = 0;
        a1[0] = p0.y; a1[1] = 0; a1[2] = 1;
        b(2*i,0) = p1.x;
        b(2*i+1,0) = p1.y;
    }

    Mat_<float> sol;
143
    solve(A, b, sol, DECOMP_NORMAL | DECOMP_LU);
144 145

    if (rmse)
146
        *rmse = static_cast<float>(norm(A*sol, b, NORM_L2) / std::sqrt(static_cast<double>(npoints)));
147 148 149 150 151

    Mat_<float> M = Mat::eye(3, 3, CV_32F);
    M(0,0) = M(1,1) = sol(0,0);
    M(0,2) = sol(1,0);
    M(1,2) = sol(2,0);
152 153

    return T1.inv() * M * T0;
154 155
}

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
static Mat estimateGlobMotionLeastSquaresRotation(
        int npoints, Point2f *points0, Point2f *points1, float *rmse)
{
    Point2f p0, p1;
    float A(0), B(0);
    for(int i=0; i<npoints; ++i)
    {
        p0 = points0[i];
        p1 = points1[i];

        A += p0.x*p1.x + p0.y*p1.y;
        B += p0.x*p1.y - p1.x*p0.y;
    }

    // A*sin(alpha) + B*cos(alpha) = 0
171
    float C = std::sqrt(A*A + B*B);
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    Mat_<float> M = Mat::eye(3, 3, CV_32F);
    if ( C != 0 )
    {
        float sinAlpha = - B / C;
        float cosAlpha = A / C;

        M(0,0) = cosAlpha;
        M(1,1) = M(0,0);
        M(0,1) = sinAlpha;
        M(1,0) = - M(0,1);
    }

    if (rmse)
    {
        *rmse = 0;
        for (int i = 0; i < npoints; ++i)
        {
            p0 = points0[i];
            p1 = points1[i];
            *rmse += sqr(p1.x - M(0,0)*p0.x - M(0,1)*p0.y) +
                     sqr(p1.y - M(1,0)*p0.x - M(1,1)*p0.y);
        }
194
        *rmse = std::sqrt(*rmse / npoints);
195 196 197 198
    }

    return M;
}
199

200
static Mat  estimateGlobMotionLeastSquaresRigid(
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
        int npoints, Point2f *points0, Point2f *points1, float *rmse)
{
    Point2f mean0(0.f, 0.f);
    Point2f mean1(0.f, 0.f);

    for (int i = 0; i < npoints; ++i)
    {
        mean0 += points0[i];
        mean1 += points1[i];
    }

    mean0 *= 1.f / npoints;
    mean1 *= 1.f / npoints;

    Mat_<float> A = Mat::zeros(2, 2, CV_32F);
    Point2f pt0, pt1;

    for (int i = 0; i < npoints; ++i)
    {
        pt0 = points0[i] - mean0;
        pt1 = points1[i] - mean1;
        A(0,0) += pt1.x * pt0.x;
        A(0,1) += pt1.x * pt0.y;
        A(1,0) += pt1.y * pt0.x;
        A(1,1) += pt1.y * pt0.y;
    }

    Mat_<float> M = Mat::eye(3, 3, CV_32F);

    SVD svd(A);
    Mat_<float> R = svd.u * svd.vt;
    Mat tmp(M(Rect(0,0,2,2)));
    R.copyTo(tmp);

    M(0,2) = mean1.x - R(0,0)*mean0.x - R(0,1)*mean0.y;
    M(1,2) = mean1.y - R(1,0)*mean0.x - R(1,1)*mean0.y;

    if (rmse)
    {
        *rmse = 0;
        for (int i = 0; i < npoints; ++i)
        {
            pt0 = points0[i];
            pt1 = points1[i];
            *rmse += sqr(pt1.x - M(0,0)*pt0.x - M(0,1)*pt0.y - M(0,2)) +
                     sqr(pt1.y - M(1,0)*pt0.x - M(1,1)*pt0.y - M(1,2));
        }
248
        *rmse = std::sqrt(*rmse / npoints);
249 250 251 252 253 254
    }

    return M;
}


255
static Mat estimateGlobMotionLeastSquaresSimilarity(
256
        int npoints, Point2f *points0, Point2f *points1, float *rmse)
257
{
258 259 260
    Mat_<float> T0 = normalizePoints(npoints, points0);
    Mat_<float> T1 = normalizePoints(npoints, points1);

261 262 263 264 265 266 267 268 269 270
    Mat_<float> A(2*npoints, 4), b(2*npoints, 1);
    float *a0, *a1;
    Point2f p0, p1;

    for (int i = 0; i < npoints; ++i)
    {
        a0 = A[2*i];
        a1 = A[2*i+1];
        p0 = points0[i];
        p1 = points1[i];
271
        a0[0] = p0.x; a0[1] = p0.y; a0[2] = 1; a0[3] = 0;
272 273 274 275 276 277
        a1[0] = p0.y; a1[1] = -p0.x; a1[2] = 0; a1[3] = 1;
        b(2*i,0) = p1.x;
        b(2*i+1,0) = p1.y;
    }

    Mat_<float> sol;
278
    solve(A, b, sol, DECOMP_NORMAL | DECOMP_LU);
279 280

    if (rmse)
281
        *rmse = static_cast<float>(norm(A*sol, b, NORM_L2) / std::sqrt(static_cast<double>(npoints)));
282 283 284 285 286 287 288

    Mat_<float> M = Mat::eye(3, 3, CV_32F);
    M(0,0) = M(1,1) = sol(0,0);
    M(0,1) = sol(1,0);
    M(1,0) = -sol(1,0);
    M(0,2) = sol(2,0);
    M(1,2) = sol(3,0);
289 290

    return T1.inv() * M * T0;
291 292 293
}


294
static Mat estimateGlobMotionLeastSquaresAffine(
295
        int npoints, Point2f *points0, Point2f *points1, float *rmse)
296
{
297 298 299
    Mat_<float> T0 = normalizePoints(npoints, points0);
    Mat_<float> T1 = normalizePoints(npoints, points1);

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
    Mat_<float> A(2*npoints, 6), b(2*npoints, 1);
    float *a0, *a1;
    Point2f p0, p1;

    for (int i = 0; i < npoints; ++i)
    {
        a0 = A[2*i];
        a1 = A[2*i+1];
        p0 = points0[i];
        p1 = points1[i];
        a0[0] = p0.x; a0[1] = p0.y; a0[2] = 1; a0[3] = a0[4] = a0[5] = 0;
        a1[0] = a1[1] = a1[2] = 0; a1[3] = p0.x; a1[4] = p0.y; a1[5] = 1;
        b(2*i,0) = p1.x;
        b(2*i+1,0) = p1.y;
    }

    Mat_<float> sol;
317
    solve(A, b, sol, DECOMP_NORMAL | DECOMP_LU);
318 319

    if (rmse)
320
        *rmse = static_cast<float>(norm(A*sol, b, NORM_L2) / std::sqrt(static_cast<double>(npoints)));
321 322 323 324 325 326

    Mat_<float> M = Mat::eye(3, 3, CV_32F);
    for (int i = 0, k = 0; i < 2; ++i)
        for (int j = 0; j < 3; ++j, ++k)
            M(i,j) = sol(k,0);

327
    return T1.inv() * M * T0;
328 329 330 331
}


Mat estimateGlobalMotionLeastSquares(
332
        InputOutputArray points0, InputOutputArray points1, int model, float *rmse)
333
{
334
    CV_Assert(model <= MM_AFFINE);
335 336 337
    CV_Assert(points0.type() == points1.type());
    const int npoints = points0.getMat().checkVector(2);
    CV_Assert(points1.getMat().checkVector(2) == npoints);
338

339
    typedef Mat (*Impl)(int, Point2f*, Point2f*, float*);
340 341
    static Impl impls[] = { estimateGlobMotionLeastSquaresTranslation,
                            estimateGlobMotionLeastSquaresTranslationAndScale,
342
                            estimateGlobMotionLeastSquaresRotation,
343
                            estimateGlobMotionLeastSquaresRigid,
344
                            estimateGlobMotionLeastSquaresSimilarity,
345 346
                            estimateGlobMotionLeastSquaresAffine };

347 348 349 350
    Point2f *points0_ = points0.getMat().ptr<Point2f>();
    Point2f *points1_ = points1.getMat().ptr<Point2f>();

    return impls[model](npoints, points0_, points1_, rmse);
351 352 353
}


354
Mat estimateGlobalMotionRansac(
355 356
        InputArray points0, InputArray points1, int model, const RansacParams &params,
        float *rmse, int *ninliers)
357
{
358
    CV_Assert(model <= MM_AFFINE);
359 360 361
    CV_Assert(points0.type() == points1.type());
    const int npoints = points0.getMat().checkVector(2);
    CV_Assert(points1.getMat().checkVector(2) == npoints);
362

363 364 365
    if (npoints < params.size)
        return Mat::eye(3, 3, CV_32F);

366 367
    const Point2f *points0_ = points0.getMat().ptr<Point2f>();
    const Point2f *points1_ = points1.getMat().ptr<Point2f>();
368
    const int niters = params.niters();
369

370
    // current hypothesis
371 372 373
    std::vector<int> indices(params.size);
    std::vector<Point2f> subset0(params.size);
    std::vector<Point2f> subset1(params.size);
374 375

    // best hypothesis
376 377
    std::vector<Point2f> subset0best(params.size);
    std::vector<Point2f> subset1best(params.size);
378 379
    Mat_<float> bestM;
    int ninliersMax = -1;
380 381

    RNG rng(0);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    Point2f p0, p1;
    float x, y;

    for (int iter = 0; iter < niters; ++iter)
    {
        for (int i = 0; i < params.size; ++i)
        {
            bool ok = false;
            while (!ok)
            {
                ok = true;
                indices[i] = static_cast<unsigned>(rng) % npoints;
                for (int j = 0; j < i; ++j)
                    if (indices[i] == indices[j])
                        { ok = false; break; }
            }
        }
        for (int i = 0; i < params.size; ++i)
        {
401 402
            subset0[i] = points0_[indices[i]];
            subset1[i] = points1_[indices[i]];
403 404
        }

405
        Mat_<float> M = estimateGlobalMotionLeastSquares(subset0, subset1, model, 0);
406

Andrey Kamaev's avatar
Andrey Kamaev committed
407
        int numinliers = 0;
408 409
        for (int i = 0; i < npoints; ++i)
        {
410 411
            p0 = points0_[i];
            p1 = points1_[i];
412 413 414
            x = M(0,0)*p0.x + M(0,1)*p0.y + M(0,2);
            y = M(1,0)*p0.x + M(1,1)*p0.y + M(1,2);
            if (sqr(x - p1.x) + sqr(y - p1.y) < params.thresh * params.thresh)
Andrey Kamaev's avatar
Andrey Kamaev committed
415
                numinliers++;
416
        }
Andrey Kamaev's avatar
Andrey Kamaev committed
417
        if (numinliers >= ninliersMax)
418 419
        {
            bestM = M;
Andrey Kamaev's avatar
Andrey Kamaev committed
420
            ninliersMax = numinliers;
421 422 423 424 425 426
            subset0best.swap(subset0);
            subset1best.swap(subset1);
        }
    }

    if (ninliersMax < params.size)
427
        // compute RMSE
428
        bestM = estimateGlobalMotionLeastSquares(subset0best, subset1best, model, rmse);
429 430 431 432
    else
    {
        subset0.resize(ninliersMax);
        subset1.resize(ninliersMax);
Shai's avatar
Shai committed
433
        for (int i = 0, j = 0; i < npoints && j < ninliersMax ; ++i)
434
        {
435 436
            p0 = points0_[i];
            p1 = points1_[i];
437 438 439 440 441 442 443 444 445
            x = bestM(0,0)*p0.x + bestM(0,1)*p0.y + bestM(0,2);
            y = bestM(1,0)*p0.x + bestM(1,1)*p0.y + bestM(1,2);
            if (sqr(x - p1.x) + sqr(y - p1.y) < params.thresh * params.thresh)
            {
                subset0[j] = p0;
                subset1[j] = p1;
                j++;
            }
        }
446
        bestM = estimateGlobalMotionLeastSquares(subset0, subset1, model, rmse);
447 448 449 450 451 452 453 454 455
    }

    if (ninliers)
        *ninliers = ninliersMax;

    return bestM;
}


456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
MotionEstimatorRansacL2::MotionEstimatorRansacL2(MotionModel model)
    : MotionEstimatorBase(model)
{
    setRansacParams(RansacParams::default2dMotion(model));
    setMinInlierRatio(0.1f);
}


Mat MotionEstimatorRansacL2::estimate(InputArray points0, InputArray points1, bool *ok)
{
    CV_Assert(points0.type() == points1.type());
    const int npoints = points0.getMat().checkVector(2);
    CV_Assert(points1.getMat().checkVector(2) == npoints);

    // find motion

    int ninliers = 0;
    Mat_<float> M;

    if (motionModel() != MM_HOMOGRAPHY)
476
        M = estimateGlobalMotionRansac(
477 478 479
                points0, points1, motionModel(), ransacParams_, 0, &ninliers);
    else
    {
480
        std::vector<uchar> mask;
481
        M = findHomography(points0, points1, mask, LMEDS);
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
        for (int i  = 0; i < npoints; ++i)
            if (mask[i]) ninliers++;
    }

    // check if we're confident enough in estimated motion

    if (ok) *ok = true;
    if (static_cast<float>(ninliers) / npoints < minInlierRatio_)
    {
        M = Mat::eye(3, 3, CV_32F);
        if (ok) *ok = false;
    }

    return M;
}


MotionEstimatorL1::MotionEstimatorL1(MotionModel model)
    : MotionEstimatorBase(model)
{
}


// TODO will estimation of all motions as one LP problem be faster?
Mat MotionEstimatorL1::estimate(InputArray points0, InputArray points1, bool *ok)
{
    CV_Assert(points0.type() == points1.type());
    const int npoints = points0.getMat().checkVector(2);
    CV_Assert(points1.getMat().checkVector(2) == npoints);

#ifndef HAVE_CLP

514
    CV_Error(Error::StsError, "The library is built without Clp support");
515 516 517 518 519 520 521 522 523
    if (ok) *ok = false;
    return Mat::eye(3, 3, CV_32F);

#else

    CV_Assert(motionModel() <= MM_AFFINE && motionModel() != MM_RIGID);

    // prepare LP problem

524 525 526
    const Point2f *points0_ = points0.getMat().ptr<Point2f>();
    const Point2f *points1_ = points1.getMat().ptr<Point2f>();

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 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 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    int ncols = 6 + 2*npoints;
    int nrows = 4*npoints;

    if (motionModel() == MM_SIMILARITY)
        nrows += 2;
    else if (motionModel() == MM_TRANSLATION_AND_SCALE)
        nrows += 3;
    else if (motionModel() == MM_TRANSLATION)
        nrows += 4;

    rows_.clear();
    cols_.clear();
    elems_.clear();
    obj_.assign(ncols, 0);
    collb_.assign(ncols, -INF);
    colub_.assign(ncols, INF);

    int c = 6;

    for (int i = 0; i < npoints; ++i, c += 2)
    {
        obj_[c] = 1;
        collb_[c] = 0;

        obj_[c+1] = 1;
        collb_[c+1] = 0;
    }

    elems_.clear();
    rowlb_.assign(nrows, -INF);
    rowub_.assign(nrows, INF);

    int r = 0;
    Point2f p0, p1;

    for (int i = 0; i < npoints; ++i, r += 4)
    {
        p0 = points0_[i];
        p1 = points1_[i];

        set(r, 0, p0.x); set(r, 1, p0.y); set(r, 2, 1); set(r, 6+2*i, -1);
        rowub_[r] = p1.x;

        set(r+1, 3, p0.x); set(r+1, 4, p0.y); set(r+1, 5, 1); set(r+1, 6+2*i+1, -1);
        rowub_[r+1] = p1.y;

        set(r+2, 0, p0.x); set(r+2, 1, p0.y); set(r+2, 2, 1); set(r+2, 6+2*i, 1);
        rowlb_[r+2] = p1.x;

        set(r+3, 3, p0.x); set(r+3, 4, p0.y); set(r+3, 5, 1); set(r+3, 6+2*i+1, 1);
        rowlb_[r+3] = p1.y;
    }

    if (motionModel() == MM_SIMILARITY)
    {
        set(r, 0, 1); set(r, 4, -1); rowlb_[r] = rowub_[r] = 0;
        set(r+1, 1, 1); set(r+1, 3, 1); rowlb_[r+1] = rowub_[r+1] = 0;
    }
    else if (motionModel() == MM_TRANSLATION_AND_SCALE)
    {
        set(r, 0, 1); set(r, 4, -1); rowlb_[r] = rowub_[r] = 0;
        set(r+1, 1, 1); rowlb_[r+1] = rowub_[r+1] = 0;
        set(r+2, 3, 1); rowlb_[r+2] = rowub_[r+2] = 0;
    }
    else if (motionModel() == MM_TRANSLATION)
    {
        set(r, 0, 1); rowlb_[r] = rowub_[r] = 1;
        set(r+1, 1, 1); rowlb_[r+1] = rowub_[r+1] = 0;
        set(r+2, 3, 1); rowlb_[r+2] = rowub_[r+2] = 0;
        set(r+3, 4, 1); rowlb_[r+3] = rowub_[r+3] = 1;
    }

    // solve

    CoinPackedMatrix A(true, &rows_[0], &cols_[0], &elems_[0], elems_.size());
    A.setDimensions(nrows, ncols);

    ClpSimplex model(false);
    model.loadProblem(A, &collb_[0], &colub_[0], &obj_[0], &rowlb_[0], &rowub_[0]);

    ClpDualRowSteepest dualSteep(1);
    model.setDualRowPivotAlgorithm(dualSteep);
    model.scaling(1);

    model.dual();

    // extract motion

    const double *sol = model.getColSolution();

    Mat_<float> M = Mat::eye(3, 3, CV_32F);
    M(0,0) = sol[0];
    M(0,1) = sol[1];
    M(0,2) = sol[2];
    M(1,0) = sol[3];
    M(1,1) = sol[4];
    M(1,2) = sol[5];

    if (ok) *ok = true;
    return M;
#endif
}


631
FromFileMotionReader::FromFileMotionReader(const String &path)
632
    : ImageMotionEstimatorBase(MM_UNKNOWN)
633 634 635 636 637 638
{
    file_.open(path.c_str());
    CV_Assert(file_.is_open());
}


639
Mat FromFileMotionReader::estimate(const Mat &/*frame0*/, const Mat &/*frame1*/, bool *ok)
640 641
{
    Mat_<float> M(3, 3);
642
    bool ok_;
643 644
    file_ >> M(0,0) >> M(0,1) >> M(0,2)
          >> M(1,0) >> M(1,1) >> M(1,2)
645 646
          >> M(2,0) >> M(2,1) >> M(2,2) >> ok_;
    if (ok) *ok = ok_;
647 648 649 650
    return M;
}


651
ToFileMotionWriter::ToFileMotionWriter(const String &path, Ptr<ImageMotionEstimatorBase> estimator)
652
    : ImageMotionEstimatorBase(estimator->motionModel()), motionEstimator_(estimator)
653 654 655 656 657 658
{
    file_.open(path.c_str());
    CV_Assert(file_.is_open());
}


659
Mat ToFileMotionWriter::estimate(const Mat &frame0, const Mat &frame1, bool *ok)
660
{
661
    bool ok_;
662
    Mat_<float> M = motionEstimator_->estimate(frame0, frame1, &ok_);
663 664
    file_ << M(0,0) << " " << M(0,1) << " " << M(0,2) << " "
          << M(1,0) << " " << M(1,1) << " " << M(1,2) << " "
665
          << M(2,0) << " " << M(2,1) << " " << M(2,2) << " " << ok_ << std::endl;
666
    if (ok) *ok = ok_;
667 668 669 670
    return M;
}


671 672
KeypointBasedMotionEstimator::KeypointBasedMotionEstimator(Ptr<MotionEstimatorBase> estimator)
    : ImageMotionEstimatorBase(estimator->motionModel()), motionEstimator_(estimator)
Andrey Kamaev's avatar
Andrey Kamaev committed
673
{
674 675 676
    setDetector(makePtr<GoodFeaturesToTrackDetector>());
    setOpticalFlowEstimator(makePtr<SparsePyrLkOptFlowEstimator>());
    setOutlierRejector(makePtr<NullOutlierRejector>());
677 678 679
}


680
Mat KeypointBasedMotionEstimator::estimate(const Mat &frame0, const Mat &frame1, bool *ok)
681
{
682
    // find keypoints
683
    detector_->detect(frame0, keypointsPrev_);
684 685
    if (keypointsPrev_.empty())
        return Mat::eye(3, 3, CV_32F);
686

687
    // extract points from keypoints
688 689 690 691
    pointsPrev_.resize(keypointsPrev_.size());
    for (size_t i = 0; i < keypointsPrev_.size(); ++i)
        pointsPrev_[i] = keypointsPrev_[i].pt;

692
    // find correspondences
693 694
    optFlowEstimator_->run(frame0, frame1, pointsPrev_, points_, status_, noArray());

695 696 697 698
    // leave good correspondences only

    pointsPrevGood_.clear(); pointsPrevGood_.reserve(points_.size());
    pointsGood_.clear(); pointsGood_.reserve(points_.size());
699

700
    for (size_t i = 0; i < points_.size(); ++i)
701 702 703 704 705 706 707 708
    {
        if (status_[i])
        {
            pointsPrevGood_.push_back(pointsPrev_[i]);
            pointsGood_.push_back(points_[i]);
        }
    }

709
    // perform outlier rejection
710

711
    IOutlierRejector *outlRejector = outlierRejector_.get();
Andrey Kamaev's avatar
Andrey Kamaev committed
712
    if (!dynamic_cast<NullOutlierRejector*>(outlRejector))
713 714 715 716 717 718
    {
        pointsPrev_.swap(pointsPrevGood_);
        points_.swap(pointsGood_);

        outlierRejector_->process(frame0.size(), pointsPrev_, points_, status_);

719 720 721 722 723
        pointsPrevGood_.clear();
        pointsPrevGood_.reserve(points_.size());

        pointsGood_.clear();
        pointsGood_.reserve(points_.size());
724 725 726 727 728 729 730 731 732 733 734

        for (size_t i = 0; i < points_.size(); ++i)
        {
            if (status_[i])
            {
                pointsPrevGood_.push_back(pointsPrev_[i]);
                pointsGood_.push_back(points_[i]);
            }
        }
    }

735 736
    // estimate motion
    return motionEstimator_->estimate(pointsPrevGood_, pointsGood_, ok);
737 738 739
}


740
#if defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDA) && defined(HAVE_OPENCV_CUDAOPTFLOW)
741

742 743
KeypointBasedMotionEstimatorGpu::KeypointBasedMotionEstimatorGpu(Ptr<MotionEstimatorBase> estimator)
    : ImageMotionEstimatorBase(estimator->motionModel()), motionEstimator_(estimator)
744
{
745
    detector_ = cuda::createGoodFeaturesToTrackDetector(CV_8UC1);
746

747
    CV_Assert(cuda::getCudaEnabledDeviceCount() > 0);
748
    setOutlierRejector(makePtr<NullOutlierRejector>());
749 750
}

751

752
Mat KeypointBasedMotionEstimatorGpu::estimate(const Mat &frame0, const Mat &frame1, bool *ok)
753 754 755 756 757 758 759
{
    frame0_.upload(frame0);
    frame1_.upload(frame1);
    return estimate(frame0_, frame1_, ok);
}


760
Mat KeypointBasedMotionEstimatorGpu::estimate(const cuda::GpuMat &frame0, const cuda::GpuMat &frame1, bool *ok)
761 762 763
{
    // convert frame to gray if it's color

764
    cuda::GpuMat grayFrame0;
765 766 767 768
    if (frame0.channels() == 1)
        grayFrame0 = frame0;
    else
    {
769
        cuda::cvtColor(frame0, grayFrame0_, COLOR_BGR2GRAY);
770 771 772 773
        grayFrame0 = grayFrame0_;
    }

    // find keypoints
774
    detector_->detect(grayFrame0, pointsPrev_);
775 776

    // find correspondences
Andrey Kamaev's avatar
Andrey Kamaev committed
777
    optFlowEstimator_.run(frame0, frame1, pointsPrev_, points_, status_);
778 779

    // leave good correspondences only
780
    cuda::compactPoints(pointsPrev_, points_, status_);
781 782 783 784

    pointsPrev_.download(hostPointsPrev_);
    points_.download(hostPoints_);

785
    // perform outlier rejection
786

787
    IOutlierRejector *rejector = outlierRejector_.get();
788
    if (!dynamic_cast<NullOutlierRejector*>(rejector))
789 790 791
    {
        outlierRejector_->process(frame0.size(), hostPointsPrev_, hostPoints_, rejectionStatus_);

792 793 794 795 796
        hostPointsPrevTmp_.clear();
        hostPointsPrevTmp_.reserve(hostPoints_.cols);

        hostPointsTmp_.clear();
        hostPointsTmp_.reserve(hostPoints_.cols);
797 798 799 800 801

        for (int i = 0; i < hostPoints_.cols; ++i)
        {
            if (rejectionStatus_[i])
            {
802 803
                hostPointsPrevTmp_.push_back(hostPointsPrev_.at<Point2f>(0,i));
                hostPointsTmp_.push_back(hostPoints_.at<Point2f>(0,i));
804 805 806
            }
        }

807 808
        hostPointsPrev_ = Mat(1, (int)hostPointsPrevTmp_.size(), CV_32FC2, &hostPointsPrevTmp_[0]);
        hostPoints_ = Mat(1, (int)hostPointsTmp_.size(), CV_32FC2, &hostPointsTmp_[0]);
809 810
    }

811 812
    // estimate motion
    return motionEstimator_->estimate(hostPointsPrev_, hostPoints_, ok);
813
}
814

815
#endif // defined(HAVE_OPENCV_CUDAIMGPROC) && defined(HAVE_OPENCV_CUDA) && defined(HAVE_OPENCV_CUDAOPTFLOW)
816 817


818
Mat getMotion(int from, int to, const std::vector<Mat> &motions)
819 820 821 822 823
{
    Mat M = Mat::eye(3, 3, CV_32F);
    if (to > from)
    {
        for (int i = from; i < to; ++i)
824
            M = at(i, motions) * M;
825 826 827 828
    }
    else if (from > to)
    {
        for (int i = to; i < from; ++i)
829
            M = at(i, motions) * M;
830 831 832 833 834 835 836
        M = M.inv();
    }
    return M;
}

} // namespace videostab
} // namespace cv