global_motion.cpp

Andrei Zaharescu, 2013-05-15 05:16 pm

Download (11.1 kB)

 
1
/*M///////////////////////////////////////////////////////////////////////////////////////
2
//
3
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4
//
5
//  By downloading, copying, installing or using the software you agree to this license.
6
//  If you do not agree to this license, do not download, install,
7
//  copy or use the software.
8
//
9
//
10
//                           License Agreement
11
//                For Open Source Computer Vision Library
12
//
13
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14
// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved.
15
// Third party copyrights are property of their respective owners.
16
//
17
// Redistribution and use in source and binary forms, with or without modification,
18
// are permitted provided that the following conditions are met:
19
//
20
//   * Redistribution's of source code must retain the above copyright notice,
21
//     this list of conditions and the following disclaimer.
22
//
23
//   * Redistribution's in binary form must reproduce the above copyright notice,
24
//     this list of conditions and the following disclaimer in the documentation
25
//     and/or other materials provided with the distribution.
26
//
27
//   * The name of the copyright holders may not be used to endorse or promote products
28
//     derived from this software without specific prior written permission.
29
//
30
// 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
// warranties of merchantability and fitness for a particular purpose are disclaimed.
33
// In no event shall the Intel Corporation or contributors be liable for any direct,
34
// indirect, incidental, special, exemplary, or consequential damages
35
// (including, but not limited to, procurement of substitute goods or services;
36
// loss of use, data, or profits; or business interruption) however caused
37
// and on any theory of liability, whether in contract, strict liability,
38
// or tort (including negligence or otherwise) arising in any way out of
39
// the use of this software, even if advised of the possibility of such damage.
40
//
41
//M*/
42
43
#include "precomp.hpp"
44
#include "opencv2/highgui/highgui.hpp"
45
#include "opencv2/videostab/global_motion.hpp"
46
47
using namespace std;
48
49
namespace cv
50
{
51
namespace videostab
52
{
53
54
static Mat estimateGlobMotionLeastSquaresTranslation(
55
        int npoints, const Point2f *points0, const Point2f *points1, float *rmse)
56
{
57
    Mat_<float> M = Mat::eye(3, 3, CV_32F);
58
    for (int i = 0; i < npoints; ++i)
59
    {
60
        M(0,2) += points1[i].x - points0[i].x;
61
        M(1,2) += points1[i].y - points0[i].y;
62
    }
63
    M(0,2) /= npoints;
64
    M(1,2) /= npoints;
65
    if (rmse)
66
    {
67
        *rmse = 0;
68
        for (int i = 0; i < npoints; ++i)
69
            *rmse += sqr(points1[i].x - points0[i].x - M(0,2)) +
70
                     sqr(points1[i].y - points0[i].y - M(1,2));
71
        *rmse = sqrt(*rmse / npoints);
72
    }
73
    return M;
74
}
75
76
77
static Mat estimateGlobMotionLeastSquaresTranslationAndScale(
78
        int npoints, const Point2f *points0, const Point2f *points1, float *rmse)
79
{
80
    Mat_<float> A(2*npoints, 3), b(2*npoints, 1);
81
    float *a0, *a1;
82
    Point2f p0, p1;
83
84
    for (int i = 0; i < npoints; ++i)
85
    {
86
        a0 = A[2*i];
87
        a1 = A[2*i+1];
88
        p0 = points0[i];
89
        p1 = points1[i];
90
        a0[0] = p0.x; a0[1] = 1; a0[2] = 0;
91
        a1[0] = p0.y; a1[1] = 0; a1[2] = 1;
92
        b(2*i,0) = p1.x;
93
        b(2*i+1,0) = p1.y;
94
    }
95
96
    Mat_<float> sol;
97
    solve(A, b, sol, DECOMP_SVD);
98
99
    if (rmse)
100
        *rmse = static_cast<float>(norm(A*sol, b, NORM_L2) / sqrt(static_cast<double>(npoints)));
101
102
    Mat_<float> M = Mat::eye(3, 3, CV_32F);
103
    M(0,0) = M(1,1) = sol(0,0);
104
    M(0,2) = sol(1,0);
105
    M(1,2) = sol(2,0);
106
    return M;
107
}
108
109
110
static Mat estimateGlobMotionLeastSquaresLinearSimilarity(
111
        int npoints, const Point2f *points0, const Point2f *points1, float *rmse)
112
{
113
    Mat_<float> A(2*npoints, 4), b(2*npoints, 1);
114
    float *a0, *a1;
115
    Point2f p0, p1;
116
117
    for (int i = 0; i < npoints; ++i)
118
    {
119
        a0 = A[2*i];
120
        a1 = A[2*i+1];
121
        p0 = points0[i];
122
        p1 = points1[i];
123
        a0[0] = p0.x; a0[1] = p0.y; a0[2] = 1;  a0[3] = 0;
124
        a1[0] = p0.y; a1[1] = -p0.x; a1[2] = 0; a1[3] = 1;
125
        b(2*i,0) = p1.x;
126
        b(2*i+1,0) = p1.y;
127
    }
128
129
    Mat_<float> sol;
130
    solve(A, b, sol, DECOMP_SVD);
131
132
    if (rmse)
133
        *rmse = static_cast<float>(norm(A*sol, b, NORM_L2) / sqrt(static_cast<double>(npoints)));
134
135
    Mat_<float> M = Mat::eye(3, 3, CV_32F);
136
    M(0,0) = M(1,1) = sol(0,0);
137
    M(0,1) = sol(1,0);
138
    M(1,0) = -sol(1,0);
139
    M(0,2) = sol(2,0);
140
    M(1,2) = sol(3,0);
141
    return M;
142
}
143
144
145
static Mat estimateGlobMotionLeastSquaresAffine(
146
        int npoints, const Point2f *points0, const Point2f *points1, float *rmse)
147
{
148
    Mat_<float> A(2*npoints, 6), b(2*npoints, 1);
149
    float *a0, *a1;
150
    Point2f p0, p1;
151
152
    for (int i = 0; i < npoints; ++i)
153
    {
154
        a0 = A[2*i];
155
        a1 = A[2*i+1];
156
        p0 = points0[i];
157
        p1 = points1[i];
158
        a0[0] = p0.x; a0[1] = p0.y; a0[2] = 1; a0[3] = a0[4] = a0[5] = 0;
159
        a1[0] = a1[1] = a1[2] = 0; a1[3] = p0.x; a1[4] = p0.y; a1[5] = 1;
160
        b(2*i,0) = p1.x;
161
        b(2*i+1,0) = p1.y;
162
    }
163
164
    Mat_<float> sol;
165
    solve(A, b, sol, DECOMP_SVD);
166
167
    if (rmse)
168
        *rmse = static_cast<float>(norm(A*sol, b, NORM_L2) / sqrt(static_cast<double>(npoints)));
169
170
    Mat_<float> M = Mat::eye(3, 3, CV_32F);
171
    for (int i = 0, k = 0; i < 2; ++i)
172
        for (int j = 0; j < 3; ++j, ++k)
173
            M(i,j) = sol(k,0);
174
175
    return M;
176
}
177
178
179
Mat estimateGlobalMotionLeastSquares(
180
        const vector<Point2f> &points0, const vector<Point2f> &points1, int model, float *rmse)
181
{
182
    CV_Assert(points0.size() == points1.size());
183
184
    typedef Mat (*Impl)(int, const Point2f*, const Point2f*, float*);
185
    static Impl impls[] = { estimateGlobMotionLeastSquaresTranslation,
186
                            estimateGlobMotionLeastSquaresTranslationAndScale,
187
                            estimateGlobMotionLeastSquaresLinearSimilarity,
188
                            estimateGlobMotionLeastSquaresAffine };
189
190
    int npoints = static_cast<int>(points0.size());
191
    return impls[model](npoints, &points0[0], &points1[0], rmse);
192
}
193
194
195
Mat estimateGlobalMotionRobust(
196
        const vector<Point2f> &points0, const vector<Point2f> &points1, int model,
197
        const RansacParams &params, float *rmse, int *ninliers)
198
{
199
    CV_Assert(points0.size() == points1.size());
200
201
    typedef Mat (*Impl)(int, const Point2f*, const Point2f*, float*);
202
    static Impl impls[] = { estimateGlobMotionLeastSquaresTranslation,
203
                            estimateGlobMotionLeastSquaresTranslationAndScale,
204
                            estimateGlobMotionLeastSquaresLinearSimilarity,
205
                            estimateGlobMotionLeastSquaresAffine };
206
207
    const int npoints = static_cast<int>(points0.size());
208
    const int niters = static_cast<int>(ceil(log(1 - params.prob) /
209
                                             log(1 - pow(1 - params.eps, params.size))));
210
211
        if (points0.size() < 5 || points1.size() < 5)
212
                return Mat::eye(3, 3, CV_32F);
213
214
    RNG rng(0);
215
    vector<int> indices(params.size);
216
    vector<Point2f> subset0(params.size), subset1(params.size);
217
    vector<Point2f> subset0best(params.size), subset1best(params.size);
218
    Mat_<float> bestM;
219
    int ninliersMax = -1;
220
    Point2f p0, p1;
221
    float x, y;
222
223
    for (int iter = 0; iter < niters; ++iter)
224
    {
225
        for (int i = 0; i < params.size; ++i)
226
        {
227
            bool ok = false;
228
            while (!ok)
229
            {
230
                ok = true;
231
                indices[i] = static_cast<unsigned>(rng) % npoints;
232
                for (int j = 0; j < i; ++j)
233
                    if (indices[i] == indices[j])
234
                        { ok = false; break; }
235
            }
236
        }
237
        for (int i = 0; i < params.size; ++i)
238
        {
239
            subset0[i] = points0[indices[i]];
240
            subset1[i] = points1[indices[i]];
241
        }
242
243
        Mat_<float> M = impls[model](params.size, &subset0[0], &subset1[0], 0);
244
245
        int _ninliers = 0;
246
        for (int i = 0; i < npoints; ++i)
247
        {
248
            p0 = points0[i]; p1 = points1[i];
249
            x = M(0,0)*p0.x + M(0,1)*p0.y + M(0,2);
250
            y = M(1,0)*p0.x + M(1,1)*p0.y + M(1,2);
251
            if (sqr(x - p1.x) + sqr(y - p1.y) < params.thresh * params.thresh)
252
                _ninliers++;
253
        }
254
        if (_ninliers >= ninliersMax)
255
        {
256
            bestM = M;
257
            ninliersMax = _ninliers;
258
            subset0best.swap(subset0);
259
            subset1best.swap(subset1);
260
        }
261
    }
262
263
    if (ninliersMax < params.size)
264
        // compute rmse
265
        bestM = impls[model](params.size, &subset0best[0], &subset1best[0], rmse);
266
    else
267
    {
268
        subset0.resize(ninliersMax);
269
        subset1.resize(ninliersMax);
270
        for (int i = 0, j = 0; i < npoints; ++i)
271
        {
272
            p0 = points0[i]; p1 = points1[i];
273
            x = bestM(0,0)*p0.x + bestM(0,1)*p0.y + bestM(0,2);
274
            y = bestM(1,0)*p0.x + bestM(1,1)*p0.y + bestM(1,2);
275
            if (sqr(x - p1.x) + sqr(y - p1.y) < params.thresh * params.thresh)
276
            {
277
                subset0[j] = p0;
278
                subset1[j] = p1;
279
                j++;
280
            }
281
        }
282
        bestM = impls[model](ninliersMax, &subset0[0], &subset1[0], rmse);
283
    }
284
285
    if (ninliers)
286
        *ninliers = ninliersMax;
287
288
    return bestM;
289
}
290
291
292
PyrLkRobustMotionEstimator::PyrLkRobustMotionEstimator()
293
    : ransacParams_(RansacParams::affine2dMotionStd())
294
{
295
    setDetector(new GoodFeaturesToTrackDetector());
296
    setOptFlowEstimator(new SparsePyrLkOptFlowEstimator());
297
    setMotionModel(AFFINE);
298
    setMaxRmse(0.5f);
299
    setMinInlierRatio(0.1f);
300
}
301
302
303
Mat PyrLkRobustMotionEstimator::estimate(const Mat &frame0, const Mat &frame1)
304
{
305
    detector_->detect(frame0, keypointsPrev_);
306
307
    pointsPrev_.resize(keypointsPrev_.size());
308
    for (size_t i = 0; i < keypointsPrev_.size(); ++i)
309
        pointsPrev_[i] = keypointsPrev_[i].pt;
310
311
    optFlowEstimator_->run(frame0, frame1, pointsPrev_, points_, status_, noArray());
312
313
    size_t npoints = points_.size();
314
    pointsPrevGood_.clear();
315
    pointsPrevGood_.reserve(npoints);
316
    pointsGood_.clear();
317
    pointsGood_.reserve(npoints);
318
    for (size_t i = 0; i < npoints; ++i)
319
    {
320
        if (status_[i])
321
        {
322
            pointsPrevGood_.push_back(pointsPrev_[i]);
323
            pointsGood_.push_back(points_[i]);
324
        }
325
    }
326
327
    float rmse;
328
    int ninliers;
329
    Mat M = estimateGlobalMotionRobust(
330
            pointsPrevGood_, pointsGood_, motionModel_, ransacParams_, &rmse, &ninliers);
331
332
    if (rmse > maxRmse_ || static_cast<float>(ninliers) / pointsGood_.size() < minInlierRatio_)
333
        M = Mat::eye(3, 3, CV_32F);
334
335
    return M;
336
}
337
338
339
Mat getMotion(int from, int to, const Mat *motions, int size)
340
{
341
    Mat M = Mat::eye(3, 3, CV_32F);
342
    if (to > from)
343
    {
344
        for (int i = from; i < to; ++i)
345
            M = at(i, motions, size) * M;
346
    }
347
    else if (from > to)
348
    {
349
        for (int i = to; i < from; ++i)
350
            M = at(i, motions, size) * M;
351
        M = M.inv();
352
    }
353
    return M;
354
}
355
356
357
Mat getMotion(int from, int to, const vector<Mat> &motions)
358
{
359
    return getMotion(from, to, &motions[0], (int)motions.size());
360
}
361
362
} // namespace videostab
363
} // namespace cv