omnidir.cpp 82 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 45 46 47 48
/*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) 2015, Baisheng Lai (laibaisheng@gmail.com), Zhejiang University,
// all rights reserved.
//
// 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*/

/**
 * This module was accepted as a GSoC 2015 project for OpenCV, authored by
 * Baisheng Lai, mentored by Bo Li.
 *
 * The omnidirectional camera in this module is denoted by the catadioptric
 * model. Please refer to Mei's paper for details of the camera model:
 *
49 50
 *      C. Mei and P. Rives, "Single view point omnidirectional camera
 *      calibration from planar grids", in ICRA 2007.
51 52 53 54
 *
 * The implementation of the calibration part is based on Li's calibration
 * toolbox:
 *
55
 *     B. Li, L. Heng, K. Kevin  and M. Pollefeys, "A Multiple-Camera System
56 57 58 59
 *     Calibration Toolbox Using A Feature Descriptor-Based Calibration
 *     Pattern", in IROS 2013.
 */
#include "precomp.hpp"
60
#include "opencv2/ccalib/omnidir.hpp"
61 62
#include <fstream>
#include <iostream>
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
namespace cv { namespace
{
    struct JacobianRow
    {
        Matx13d dom,dT;
        Matx12d df;
        double ds;
        Matx12d dc;
        double dxi;
        Matx14d dkp;    // distortion k1,k2,p1,p2
    };
}}

/////////////////////////////////////////////////////////////////////////////
//////// projectPoints
void cv::omnidir::projectPoints(InputArray objectPoints, OutputArray imagePoints,
                InputArray rvec, InputArray tvec, InputArray K, double xi, InputArray D, OutputArray jacobian)
{

82 83 84 85 86 87
    CV_Assert(objectPoints.type() == CV_64FC3 || objectPoints.type() == CV_32FC3);
    CV_Assert((rvec.depth() == CV_64F || rvec.depth() == CV_32F) && rvec.total() == 3);
    CV_Assert((tvec.depth() == CV_64F || tvec.depth() == CV_32F) && tvec.total() == 3);
    CV_Assert((K.type() == CV_64F || K.type() == CV_32F) && K.size() == Size(3,3));
    CV_Assert((D.type() == CV_64F || D.type() == CV_32F) && D.total() == 4);

88
    imagePoints.create(objectPoints.size(), CV_MAKETYPE(objectPoints.depth(), 2));
89

90
    int n = (int)objectPoints.total();
91 92 93

    Vec3d om = rvec.depth() == CV_32F ? (Vec3d)*rvec.getMat().ptr<Vec3f>() : *rvec.getMat().ptr<Vec3d>();
    Vec3d T  = tvec.depth() == CV_32F ? (Vec3d)*tvec.getMat().ptr<Vec3f>() : *tvec.getMat().ptr<Vec3d>();
94 95

    Vec2d f,c;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    double s;
    if (K.depth() == CV_32F)
    {
        Matx33f Kc = K.getMat();
        f = Vec2f(Kc(0,0), Kc(1,1));
        c = Vec2f(Kc(0,2),Kc(1,2));
        s = (double)Kc(0,1);
    }
    else
    {
        Matx33d Kc = K.getMat();
        f = Vec2d(Kc(0,0), Kc(1,1));
        c = Vec2d(Kc(0,2),Kc(1,2));
        s = Kc(0,1);
    }
111

112 113 114 115 116
    Vec4d kp = D.depth() == CV_32F ? (Vec4d)*D.getMat().ptr<Vec4f>() : *D.getMat().ptr<Vec4d>();
    //Vec<double, 4> kp= (Vec<double,4>)*D.getMat().ptr<Vec<double,4> >();

    const Vec3d* Xw_alld = objectPoints.getMat().ptr<Vec3d>();
    const Vec3f* Xw_allf = objectPoints.getMat().ptr<Vec3f>();
117
    Vec2d* xpd = imagePoints.getMat().ptr<Vec2d>();
118
    Vec2f* xpf = imagePoints.getMat().ptr<Vec2f>();
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137

    Matx33d R;
    Matx<double, 3, 9> dRdom;
    Rodrigues(om, R, dRdom);

    JacobianRow *Jn = 0;
    if (jacobian.needed())
    {
        int nvars = 2+2+1+4+3+3+1; // f,c,s,kp,om,T,xi
        jacobian.create(2*int(n), nvars, CV_64F);
        Jn = jacobian.getMat().ptr<JacobianRow>(0);
    }

    double k1=kp[0],k2=kp[1];
    double p1 = kp[2], p2 = kp[3];

    for (int i = 0; i < n; i++)
    {
        // convert to camera coordinate
138
        Vec3d Xw = objectPoints.depth() == CV_32F ? (Vec3d)Xw_allf[i] : Xw_alld[i];
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

        Vec3d Xc = (Vec3d)(R*Xw + T);

        // convert to unit sphere
        Vec3d Xs = Xc/cv::norm(Xc);

        // convert to normalized image plane
        Vec2d xu = Vec2d(Xs[0]/(Xs[2]+xi), Xs[1]/(Xs[2]+xi));

        // add distortion
        Vec2d xd;
        double r2 = xu[0]*xu[0]+xu[1]*xu[1];
        double r4 = r2*r2;

        xd[0] = xu[0]*(1+k1*r2+k2*r4) + 2*p1*xu[0]*xu[1] + p2*(r2+2*xu[0]*xu[0]);
        xd[1] = xu[1]*(1+k1*r2+k2*r4) + p1*(r2+2*xu[1]*xu[1]) + 2*p2*xu[0]*xu[1];

        // convert to pixel coordinate
157 158 159 160 161 162 163 164 165 166 167 168 169 170
        Vec2d final;
        final[0] = f[0]*xd[0]+s*xd[1]+c[0];
        final[1] = f[1]*xd[1]+c[1];

        if (objectPoints.depth() == CV_32F)
        {
            xpf[i] = final;
        }
        else
        {
            xpd[i] = final;
        }
        /*xpd[i][0] = f[0]*xd[0]+s*xd[1]+c[0];
        xpd[i][1] = f[1]*xd[1]+c[1];*/
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 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

        if (jacobian.needed())
        {
            double dXcdR_a[] = {Xw[0],Xw[1],Xw[2],0,0,0,0,0,0,
                                0,0,0,Xw[0],Xw[1],Xw[2],0,0,0,
                                0,0,0,0,0,0,Xw[0],Xw[1],Xw[2]};
            Matx<double,3, 9> dXcdR(dXcdR_a);
            Matx33d dXcdom = dXcdR * dRdom.t();
            double r_1 = 1.0/norm(Xc);
            double r_3 = pow(r_1,3);
            Matx33d dXsdXc(r_1-Xc[0]*Xc[0]*r_3, -(Xc[0]*Xc[1])*r_3, -(Xc[0]*Xc[2])*r_3,
                           -(Xc[0]*Xc[1])*r_3, r_1-Xc[1]*Xc[1]*r_3, -(Xc[1]*Xc[2])*r_3,
                           -(Xc[0]*Xc[2])*r_3, -(Xc[1]*Xc[2])*r_3, r_1-Xc[2]*Xc[2]*r_3);
            Matx23d dxudXs(1/(Xs[2]+xi),    0,    -Xs[0]/(Xs[2]+xi)/(Xs[2]+xi),
                           0,    1/(Xs[2]+xi),    -Xs[1]/(Xs[2]+xi)/(Xs[2]+xi));
            // pre-compute some reusable things
            double temp1 = 2*k1*xu[0] + 4*k2*xu[0]*r2;
            double temp2 = 2*k1*xu[1] + 4*k2*xu[1]*r2;
            Matx22d dxddxu(k2*r4+6*p2*xu[0]+2*p1*xu[1]+xu[0]*temp1+k1*r2+1,    2*p1*xu[0]+2*p2*xu[1]+xu[0]*temp2,
                           2*p1*xu[0]+2*p2*xu[1]+xu[1]*temp1,    k2*r4+2*p2*xu[0]+6*p1*xu[1]+xu[1]*temp2+k1*r2+1);
            Matx22d dxpddxd(f[0], s,
                            0, f[1]);
            Matx23d dxpddXc = dxpddxd * dxddxu * dxudXs * dXsdXc;

            // derivative of xpd respect to om
            Matx23d dxpddom = dxpddXc * dXcdom;
            Matx33d dXcdT(1.0,0.0,0.0,
                          0.0,1.0,0.0,
                          0.0,0.0,1.0);
            // derivative of xpd respect to T

            Matx23d dxpddT = dxpddXc * dXcdT;
            Matx21d dxudxi(-Xs[0]/(Xs[2]+xi)/(Xs[2]+xi),
                           -Xs[1]/(Xs[2]+xi)/(Xs[2]+xi));

            // derivative of xpd respect to xi
            Matx21d dxpddxi = dxpddxd * dxddxu * dxudxi;
            Matx<double,2,4> dxddkp(xu[0]*r2, xu[0]*r4, 2*xu[0]*xu[1], r2+2*xu[0]*xu[0],
                                    xu[1]*r2, xu[1]*r4, r2+2*xu[1]*xu[1], 2*xu[0]*xu[1]);

            // derivative of xpd respect to kp
            Matx<double,2,4> dxpddkp = dxpddxd * dxddkp;

            // derivative of xpd respect to f
            Matx22d dxpddf(xd[0], 0,
                           0, xd[1]);

            // derivative of xpd respect to c
            Matx22d dxpddc(1, 0,
                           0, 1);

            Jn[0].dom = dxpddom.row(0);
            Jn[1].dom = dxpddom.row(1);
            Jn[0].dT = dxpddT.row(0);
            Jn[1].dT = dxpddT.row(1);
            Jn[0].dkp = dxpddkp.row(0);
            Jn[1].dkp = dxpddkp.row(1);
            Jn[0].dxi = dxpddxi(0,0);
            Jn[1].dxi = dxpddxi(1,0);
            Jn[0].df = dxpddf.row(0);
            Jn[1].df = dxpddf.row(1);
            Jn[0].dc = dxpddc.row(0);
            Jn[1].dc = dxpddc.row(1);
            Jn[0].ds = xd[1];
            Jn[1].ds = 0;
            Jn += 2;
         }
    }
}

/////////////////////////////////////////////////////////////////////////////
//////// undistortPoints
void cv::omnidir::undistortPoints( InputArray distorted, OutputArray undistorted,
244
    InputArray K, InputArray D, InputArray xi, InputArray R)
245
{
246 247 248 249 250 251
    CV_Assert(distorted.type() == CV_64FC2 || distorted.type() == CV_32FC2);
    CV_Assert(R.empty() || (!R.empty() && (R.size() == Size(3, 3) || R.total() * R.channels() == 3)
        && (R.depth() == CV_64F || R.depth() == CV_32F)));
    CV_Assert((D.depth() == CV_64F || D.depth() == CV_32F) && D.total() == 4);
    CV_Assert(K.size() == Size(3, 3) && (K.depth() == CV_64F || K.depth() == CV_32F));
    CV_Assert(xi.total() == 1 && (xi.depth() == CV_64F || xi.depth() == CV_32F));
252

253
    undistorted.create(distorted.size(), distorted.type());
254 255

    cv::Vec2d f, c;
baisheng lai's avatar
baisheng lai committed
256
    double s = 0.0;
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    if (K.depth() == CV_32F)
    {
        Matx33f camMat = K.getMat();
        f = Vec2f(camMat(0,0), camMat(1,1));
        c = Vec2f(camMat(0,2), camMat(1,2));
        s = (double)camMat(0,1);
    }
    else if (K.depth() == CV_64F)
    {
        Matx33d camMat = K.getMat();
        f = Vec2d(camMat(0,0), camMat(1,1));
        c = Vec2d(camMat(0,2), camMat(1,2));
        s = camMat(0,1);
    }

    Vec4d kp = D.depth()==CV_32F ? (Vec4d)*D.getMat().ptr<Vec4f>():(Vec4d)*D.getMat().ptr<Vec4d>();
273 274 275
    Vec2d k = Vec2d(kp[0], kp[1]);
    Vec2d p = Vec2d(kp[2], kp[3]);

276
    double _xi = xi.depth() == CV_32F ? (double)*xi.getMat().ptr<float>() : *xi.getMat().ptr<double>();
277 278 279 280 281 282 283 284 285 286 287 288 289 290
    cv::Matx33d RR = cv::Matx33d::eye();
    // R is om
    if(!R.empty() && R.total()*R.channels() == 3)
    {
        cv::Vec3d rvec;
        R.getMat().convertTo(rvec, CV_64F);
        cv::Rodrigues(rvec, RR);
    }
    else if (!R.empty() && R.size() == Size(3,3))
    {
        R.getMat().convertTo(RR, CV_64F);
    }

    const cv::Vec2d *srcd = distorted.getMat().ptr<cv::Vec2d>();
291 292
    const cv::Vec2f *srcf = distorted.getMat().ptr<cv::Vec2f>();

293
    cv::Vec2d *dstd = undistorted.getMat().ptr<cv::Vec2d>();
294
    cv::Vec2f *dstf = undistorted.getMat().ptr<cv::Vec2f>();
295 296 297 298

    int n = (int)distorted.total();
    for (int i = 0; i < n; i++)
    {
299
        Vec2d pi = distorted.depth() == CV_32F ? (Vec2d)srcf[i]:(Vec2d)srcd[i];    // image point
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        Vec2d pp((pi[0]*f[1]-c[0]*f[1]-s*(pi[1]-c[1]))/(f[0]*f[1]), (pi[1]-c[1])/f[1]); //plane
        Vec2d pu = pp;    // points without distortion

        // remove distortion iteratively
        for (int j = 0; j < 20; j++)
        {
            double r2 = pu[0]*pu[0] + pu[1]*pu[1];
            double r4 = r2*r2;
            pu[0] = (pp[0] - 2*p[0]*pu[0]*pu[1] - p[1]*(r2+2*pu[0]*pu[0])) / (1 + k[0]*r2 + k[1]*r4);
            pu[1] = (pp[1] - 2*p[1]*pu[0]*pu[1] - p[0]*(r2+2*pu[1]*pu[1])) / (1 + k[0]*r2 + k[1]*r4);
        }

        // project to unit sphere
        double r2 = pu[0]*pu[0] + pu[1]*pu[1];
        double a = (r2 + 1);
315 316
        double b = 2*_xi*r2;
        double cc = r2*_xi*_xi-1;
317
        double Zs = (-b + sqrt(b*b - 4*a*cc))/(2*a);
318
        Vec3d Xw = Vec3d(pu[0]*(Zs + _xi), pu[1]*(Zs +_xi), Zs);
319 320 321 322 323 324 325 326

        // rotate
        Xw = RR * Xw;

        // project back to sphere
        Vec3d Xs = Xw / cv::norm(Xw);

        // reproject to camera plane
327 328 329 330 331 332 333 334 335
        Vec3d ppu = Vec3d(Xs[0]/(Xs[2]+_xi), Xs[1]/(Xs[2]+_xi), 1.0);
        if (undistorted.depth() == CV_32F)
        {
            dstf[i] = Vec2f((float)ppu[0], (float)ppu[1]);
        }
        else if (undistorted.depth() == CV_64F)
        {
            dstd[i] = Vec2d(ppu[0], ppu[1]);
        }
336 337 338 339 340 341
    }
}


/////////////////////////////////////////////////////////////////////////////
//////// cv::omnidir::initUndistortRectifyMap
342 343
void cv::omnidir::initUndistortRectifyMap(InputArray K, InputArray D, InputArray xi, InputArray R, InputArray P,
    const cv::Size& size, int m1type, OutputArray map1, OutputArray map2, int flags)
344 345 346 347 348 349 350 351 352 353 354
{
    CV_Assert( m1type == CV_16SC2 || m1type == CV_32F || m1type <=0 );
    map1.create( size, m1type <= 0 ? CV_16SC2 : m1type );
    map2.create( size, map1.type() == CV_16SC2 ? CV_16UC1 : CV_32F );

    CV_Assert((K.depth() == CV_32F || K.depth() == CV_64F) && (D.depth() == CV_32F || D.depth() == CV_64F));
    CV_Assert(K.size() == Size(3, 3) && (D.empty() || D.total() == 4));
    CV_Assert(P.empty()|| (P.depth() == CV_32F || P.depth() == CV_64F));
    CV_Assert(P.empty() || P.size() == Size(3, 3) || P.size() == Size(4, 3));
    CV_Assert(R.empty() || (R.depth() == CV_32F || R.depth() == CV_64F));
    CV_Assert(R.empty() || R.size() == Size(3, 3) || R.total() * R.channels() == 3);
355 356 357
    CV_Assert(flags == RECTIFY_PERSPECTIVE || flags == RECTIFY_CYLINDRICAL || flags == RECTIFY_LONGLATI
        || flags == RECTIFY_STEREOGRAPHIC);
    CV_Assert(xi.total() == 1 && (xi.depth() == CV_32F || xi.depth() == CV_64F));
358 359 360 361 362 363 364 365

    cv::Vec2d f, c;
    double s;
    if (K.depth() == CV_32F)
    {
        Matx33f camMat = K.getMat();
        f = Vec2f(camMat(0, 0), camMat(1, 1));
        c = Vec2f(camMat(0, 2), camMat(1, 2));
366
        s = (double)camMat(0,1);
367 368 369 370 371 372 373 374 375 376 377 378
    }
    else
    {
        Matx33d camMat = K.getMat();
        f = Vec2d(camMat(0, 0), camMat(1, 1));
        c = Vec2d(camMat(0, 2), camMat(1, 2));
        s = camMat(0,1);
    }

    Vec4d kp = Vec4d::all(0);
    if (!D.empty())
        kp = D.depth() == CV_32F ? (Vec4d)*D.getMat().ptr<Vec4f>(): *D.getMat().ptr<Vec4d>();
379
    double _xi = xi.depth() == CV_32F ? (double)*xi.getMat().ptr<float>() : *xi.getMat().ptr<double>();
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    Vec2d k = Vec2d(kp[0], kp[1]);
    Vec2d p = Vec2d(kp[2], kp[3]);
    cv::Matx33d RR  = cv::Matx33d::eye();
    if (!R.empty() && R.total() * R.channels() == 3)
    {
        cv::Vec3d rvec;
        R.getMat().convertTo(rvec, CV_64F);
        cv::Rodrigues(rvec, RR);
    }
    else if (!R.empty() && R.size() == Size(3, 3))
        R.getMat().convertTo(RR, CV_64F);

    cv::Matx33d PP = cv::Matx33d::eye();
    if (!P.empty())
        P.getMat().colRange(0, 3).convertTo(PP, CV_64F);
    else
        PP = K.getMat();

398 399 400
    cv::Matx33d iKR = (PP*RR).inv(cv::DECOMP_SVD);
    cv::Matx33d iK = PP.inv(cv::DECOMP_SVD);
    cv::Matx33d iR = RR.inv(cv::DECOMP_SVD);
401

402
    if (flags == omnidir::RECTIFY_PERSPECTIVE)
403
    {
404
        for (int i = 0; i < size.height; ++i)
405
        {
406 407 408 409 410 411 412 413 414
            float* m1f = map1.getMat().ptr<float>(i);
            float* m2f = map2.getMat().ptr<float>(i);
            short*  m1 = (short*)m1f;
            ushort* m2 = (ushort*)m2f;

            double _x = i*iKR(0, 1) + iKR(0, 2),
                   _y = i*iKR(1, 1) + iKR(1, 2),
                   _w = i*iKR(2, 1) + iKR(2, 2);
            for(int j = 0; j < size.width; ++j, _x+=iKR(0,0), _y+=iKR(1,0), _w+=iKR(2,0))
415
            {
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
                // project back to unit sphere
                double r = sqrt(_x*_x + _y*_y + _w*_w);
                double Xs = _x / r;
                double Ys = _y / r;
                double Zs = _w / r;
                // project to image plane
                double xu = Xs / (Zs + _xi),
                    yu = Ys / (Zs + _xi);
                // add distortion
                double r2 = xu*xu + yu*yu;
                double r4 = r2*r2;
                double xd = (1+k[0]*r2+k[1]*r4)*xu + 2*p[0]*xu*yu + p[1]*(r2+2*xu*xu);
                double yd = (1+k[0]*r2+k[1]*r4)*yu + p[0]*(r2+2*yu*yu) + 2*p[1]*xu*yu;
                // to image pixel
                double u = f[0]*xd + s*yd + c[0];
                double v = f[1]*yd + c[1];

                if( m1type == CV_16SC2 )
                {
                    int iu = cv::saturate_cast<int>(u*cv::INTER_TAB_SIZE);
                    int iv = cv::saturate_cast<int>(v*cv::INTER_TAB_SIZE);
                    m1[j*2+0] = (short)(iu >> cv::INTER_BITS);
                    m1[j*2+1] = (short)(iv >> cv::INTER_BITS);
                    m2[j] = (ushort)((iv & (cv::INTER_TAB_SIZE-1))*cv::INTER_TAB_SIZE + (iu & (cv::INTER_TAB_SIZE-1)));
                }
                else if( m1type == CV_32FC1 )
                {
                    m1f[j] = (float)u;
                    m2f[j] = (float)v;
                }
446
            }
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        }
    }
    else if(flags == omnidir::RECTIFY_CYLINDRICAL || flags == omnidir::RECTIFY_LONGLATI ||
        flags == omnidir::RECTIFY_STEREOGRAPHIC)
    {
        for (int i = 0; i < size.height; ++i)
        {
            float* m1f = map1.getMat().ptr<float>(i);
            float* m2f = map2.getMat().ptr<float>(i);
            short*  m1 = (short*)m1f;
            ushort* m2 = (ushort*)m2f;

            // for RECTIFY_LONGLATI, theta and h are longittude and latitude
            double theta = i*iK(0, 1) + iK(0, 2),
                   h     = i*iK(1, 1) + iK(1, 2);

            for (int j = 0; j < size.width; ++j, theta+=iK(0,0), h+=iK(1,0))
464
            {
baisheng lai's avatar
baisheng lai committed
465
                double _xt = 0.0, _yt = 0.0, _wt = 0.0;
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
                if (flags == omnidir::RECTIFY_CYLINDRICAL)
                {
                    //_xt = std::sin(theta);
                    //_yt = h;
                    //_wt = std::cos(theta);
                    _xt = std::cos(theta);
                    _yt = std::sin(theta);
                    _wt = h;
                }
                else if (flags == omnidir::RECTIFY_LONGLATI)
                {
                    _xt = -std::cos(theta);
                    _yt = -std::sin(theta) * std::cos(h);
                    _wt = std::sin(theta) * std::sin(h);
                }
                else if (flags == omnidir::RECTIFY_STEREOGRAPHIC)
                {
                    double a = theta*theta + h*h + 4;
                    double b = -2*theta*theta - 2*h*h;
baisheng lai's avatar
baisheng lai committed
485
                    double c2 = theta*theta + h*h -4;
486

baisheng lai's avatar
baisheng lai committed
487
                    _yt = (-b-std::sqrt(b*b - 4*a*c2))/(2*a);
488 489 490 491 492 493 494 495 496 497 498 499 500
                    _xt = theta*(1 - _yt) / 2;
                    _wt = h*(1 - _yt) / 2;
                }
                double _x = iR(0,0)*_xt + iR(0,1)*_yt + iR(0,2)*_wt;
                double _y = iR(1,0)*_xt + iR(1,1)*_yt + iR(1,2)*_wt;
                double _w = iR(2,0)*_xt + iR(2,1)*_yt + iR(2,2)*_wt;

                double r = sqrt(_x*_x + _y*_y + _w*_w);
                double Xs = _x / r;
                double Ys = _y / r;
                double Zs = _w / r;
                // project to image plane
                double xu = Xs / (Zs + _xi),
501
                       yu = Ys / (Zs + _xi);
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
                // add distortion
                double r2 = xu*xu + yu*yu;
                double r4 = r2*r2;
                double xd = (1+k[0]*r2+k[1]*r4)*xu + 2*p[0]*xu*yu + p[1]*(r2+2*xu*xu);
                double yd = (1+k[0]*r2+k[1]*r4)*yu + p[0]*(r2+2*yu*yu) + 2*p[1]*xu*yu;
                // to image pixel
                double u = f[0]*xd + s*yd + c[0];
                double v = f[1]*yd + c[1];

                if( m1type == CV_16SC2 )
                {
                    int iu = cv::saturate_cast<int>(u*cv::INTER_TAB_SIZE);
                    int iv = cv::saturate_cast<int>(v*cv::INTER_TAB_SIZE);
                    m1[j*2+0] = (short)(iu >> cv::INTER_BITS);
                    m1[j*2+1] = (short)(iv >> cv::INTER_BITS);
                    m2[j] = (ushort)((iv & (cv::INTER_TAB_SIZE-1))*cv::INTER_TAB_SIZE + (iu & (cv::INTER_TAB_SIZE-1)));
                }
                else if( m1type == CV_32FC1 )
                {
                    m1f[j] = (float)u;
                    m2f[j] = (float)v;
                }
524 525 526 527 528 529 530 531 532
            }
        }
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::omnidir::undistortImage

void cv::omnidir::undistortImage(InputArray distorted, OutputArray undistorted,
533
    InputArray K, InputArray D, InputArray xi, int flags, InputArray Knew, const Size& new_size, InputArray R)
534
{
535
    Size size = new_size.empty() ? distorted.size() : new_size;
536 537

    cv::Mat map1, map2;
538
    omnidir::initUndistortRectifyMap(K, D, xi, R, Knew, size, CV_16SC2, map1, map2, flags);
539 540 541 542 543 544
    cv::remap(distorted, undistorted, map1, map2, INTER_LINEAR, BORDER_CONSTANT);
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::omnidir::internal::initializeCalibration

545
void cv::omnidir::internal::initializeCalibration(InputArrayOfArrays patternPoints, InputArrayOfArrays imagePoints, Size size,
546
    OutputArrayOfArrays omAll, OutputArrayOfArrays tAll, OutputArray K, double& xi, OutputArray idx)
547 548 549 550 551 552 553 554 555 556
{
    // For details please refer to Section III from Li's IROS 2013 paper

    double u0 = size.width / 2;
    double v0 = size.height / 2;

    int n_img = (int)imagePoints.total();

    std::vector<cv::Vec3d> v_omAll(n_img), v_tAll(n_img);

557
    std::vector<double> gammaAll(n_img);
558 559 560 561 562

    K.create(3, 3, CV_64F);
    Mat _K;
    for (int image_idx = 0; image_idx < n_img; ++image_idx)
    {
563 564 565 566 567 568 569 570 571 572
        cv::Mat objPoints, imgPoints;
		patternPoints.getMat(image_idx).copyTo(objPoints);
		imagePoints.getMat(image_idx).copyTo(imgPoints);

		int n_point = imgPoints.rows * imgPoints.cols;
		if (objPoints.rows != n_point)
			objPoints = objPoints.reshape(3, n_point);
		if (imgPoints.rows != n_point)
			imgPoints = imgPoints.reshape(2, n_point);

573
        // objectPoints should be 3-channel data, imagePoints should be 2-channel data
574
        CV_Assert(objPoints.type() == CV_64FC3 && imgPoints.type() == CV_64FC2 );
575 576 577 578 579

        std::vector<cv::Mat> xy, uv;
        cv::split(objPoints, xy);
        cv::split(imgPoints, uv);

580

581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
        cv::Mat x = xy[0].reshape(1, n_point), y = xy[1].reshape(1, n_point),
                u = uv[0].reshape(1, n_point) - u0, v = uv[1].reshape(1, n_point) - v0;

        cv::Mat sqrRho = u.mul(u) + v.mul(v);
        // compute extrinsic parameters
        cv::Mat M(n_point, 6, CV_64F);
        Mat(-v.mul(x)).copyTo(M.col(0));
        Mat(-v.mul(y)).copyTo(M.col(1));
        Mat(u.mul(x)).copyTo(M.col(2));
        Mat(u.mul(y)).copyTo(M.col(3));
        Mat(-v).copyTo(M.col(4));
        Mat(u).copyTo(M.col(5));

        Mat W,U,V;
        cv::SVD::compute(M, W, U, V,SVD::FULL_UV);
        V = V.t();

        double miniReprojectError = 1e5;
599
        // the signs of r1, r2, r3 are unknown, so they can be flipped.
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 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
        for (int coef = 1; coef >= -1; coef-=2)
        {
            double r11 = V.at<double>(0, 5) * coef;
            double r12 = V.at<double>(1, 5) * coef;
            double r21 = V.at<double>(2, 5) * coef;
            double r22 = V.at<double>(3, 5) * coef;
            double t1 = V.at<double>(4, 5) * coef;
            double t2 = V.at<double>(5, 5) * coef;

            Mat roots;
            double r31s;
            solvePoly(Matx13d(-(r11*r12+r21*r22)*(r11*r12+r21*r22), r11*r11+r21*r21-r12*r12-r22*r22, 1), roots);

            if (roots.at<Vec2d>(0)[0] > 0)
                r31s = sqrt(roots.at<Vec2d>(0)[0]);
            else
                r31s = sqrt(roots.at<Vec2d>(1)[0]);

            for (int coef2 = 1; coef2 >= -1; coef2-=2)
            {
                double r31 = r31s * coef2;
                double r32 = -(r11*r12 + r21*r22) / r31;

                cv::Vec3d r1(r11, r21, r31);
                cv::Vec3d r2(r12, r22, r32);
                cv::Vec3d t(t1, t2, 0);
                double scale = 1 / cv::norm(r1);
                r1 = r1 * scale;
                r2 = r2 * scale;
                t = t * scale;

                // compute intrisic parameters
                // Form equations in Scaramuzza's paper
                // A Toolbox for Easily Calibrating Omnidirectional Cameras
                Mat A(n_point*2, 3, CV_64F);
                Mat((r1[1]*x + r2[1]*y + t[1])/2).copyTo(A.rowRange(0, n_point).col(0));
                Mat((r1[0]*x + r2[0]*y + t[0])/2).copyTo(A.rowRange(n_point, 2*n_point).col(0));
                Mat(-A.col(0).rowRange(0, n_point).mul(sqrRho)).copyTo(A.col(1).rowRange(0, n_point));
                Mat(-A.col(0).rowRange(n_point, 2*n_point).mul(sqrRho)).copyTo(A.col(1).rowRange(n_point, 2*n_point));
                Mat(-v).copyTo(A.rowRange(0, n_point).col(2));
                Mat(-u).copyTo(A.rowRange(n_point, 2*n_point).col(2));

                // Operation to avoid bad numerical-condition of A
                Vec3d maxA, minA;
                for (int j = 0; j < A.cols; j++)
                {
                    cv::minMaxLoc(cv::abs(A.col(j)), &minA[j], &maxA[j]);
                    A.col(j) = A.col(j) / maxA[j];
                }

                Mat B(n_point*2 , 1, CV_64F);
                Mat(v.mul(r1[2]*x + r2[2]*y)).copyTo(B.rowRange(0, n_point));
                Mat(u.mul(r1[2]*x + r2[2]*y)).copyTo(B.rowRange(n_point, 2*n_point));

                Mat res = A.inv(DECOMP_SVD) * B;
                res = res.mul(1/Mat(maxA));

                double gamma = sqrt(res.at<double>(0) / res.at<double>(1));
                t[2] = res.at<double>(2);

                cv::Vec3d r3 = r1.cross(r2);

                Matx33d R(r1[0], r2[0], r3[0],
                          r1[1], r2[1], r3[1],
                          r1[2], r2[2], r3[2]);
                Vec3d om;
                Rodrigues(R, om);

                // project pattern points to images
                Mat projedImgPoints;
                Matx33d Kc(gamma, 0, u0, 0, gamma, v0, 0, 0, 1);

672
                // reproject error
673
                cv::omnidir::projectPoints(objPoints, projedImgPoints, om, t, Kc, 1, Matx14d(0, 0, 0, 0), cv::noArray());
674
                double reprojectError = omnidir::internal::computeMeanReproErr(imgPoints, projedImgPoints);
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

                // if this reproject error is smaller
                if (reprojectError < miniReprojectError)
                {
                    miniReprojectError = reprojectError;
                    v_omAll[image_idx] = om;
                    v_tAll[image_idx] = t;
                    gammaAll[image_idx] = gamma;
                }
            }
        }
    }

    // filter initial results whose reproject errors are too large
    std::vector<double> reProjErrorFilter,v_gammaFilter;
    std::vector<Vec3d> omFilter, tFilter;
    double gammaFinal = 0;

    // choose median value
    size_t n = gammaAll.size() / 2;
    std::nth_element(gammaAll.begin(), gammaAll.begin()+n, gammaAll.end());
    gammaFinal = gammaAll[n];

    _K = Mat(Matx33d(gammaFinal, 0, u0, 0, gammaFinal, v0, 0, 0, 1));
    _K.convertTo(K, CV_64F);
700
    std::vector<int> _idx;
701 702 703 704 705
    // recompute reproject error using the final gamma
    for (int i = 0; i< n_img; i++)
    {
        Mat _projected;
        cv::omnidir::projectPoints(patternPoints.getMat(i), _projected, v_omAll[i], v_tAll[i], _K, 1, Matx14d(0, 0, 0, 0), cv::noArray());
706 707
        double _error = omnidir::internal::computeMeanReproErr(imagePoints.getMat(i), _projected);
        if(_error < 100)
708
        {
709
            _idx.push_back(i);
710 711 712 713 714
            omFilter.push_back(v_omAll[i]);
            tFilter.push_back(v_tAll[i]);
        }
    }

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
    if (idx.needed())
    {
        idx.create(1, (int)_idx.size(), CV_32S);
        Mat idx_m = idx.getMat();
        for (int j = 0; j < (int)idx_m.total(); j++)
        {
            idx_m.at<int>(j) = _idx[j];
        }
    }

    if(omAll.kind() == _InputArray::STD_VECTOR_MAT)
    {
        for (int i = 0; i < (int)omFilter.size(); ++i)
        {
            omAll.getMat(i) = Mat(omFilter[i]);
            tAll.getMat(i) = Mat(tFilter[i]);
        }
    }
    else
    {
        cv::Mat(omFilter).convertTo(omAll, CV_64FC3);
        cv::Mat(tFilter).convertTo(tAll, CV_64FC3);
    }
    xi = 1;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::omnidir::internal::initializeStereoCalibration

744
void cv::omnidir::internal::initializeStereoCalibration(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
745 746 747 748 749 750 751 752 753 754
    const Size& size1, const Size& size2, OutputArray om, OutputArray T, OutputArrayOfArrays omL, OutputArrayOfArrays tL, OutputArray K1, OutputArray D1, OutputArray K2, OutputArray D2,
    double &xi1, double &xi2, int flags, OutputArray idx)
{
    Mat idx1, idx2;
    Matx33d _K1, _K2;
    Matx14d _D1, _D2;
    Mat _xi1m, _xi2m;

    std::vector<Vec3d> omAllTemp1, omAllTemp2, tAllTemp1, tAllTemp2;

755 756
    omnidir::calibrate(objectPoints, imagePoints1, size1, _K1, _xi1m, _D1, omAllTemp1, tAllTemp1, flags, TermCriteria(3, 100, 1e-6), idx1);
    omnidir::calibrate(objectPoints, imagePoints2, size2, _K2, _xi2m, _D2, omAllTemp2, tAllTemp2, flags, TermCriteria(3, 100, 1e-6), idx2);
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839

    // find the intersection idx
    Mat interIdx1, interIdx2, interOri;

    getInterset(idx1, idx2, interIdx1, interIdx2, interOri);
    if (idx.empty())
        idx.create(1, (int)interOri.total(), CV_32S);
    interOri.copyTo(idx.getMat());

    int n_inter = (int)interIdx1.total();

    std::vector<Vec3d> omAll1(n_inter), omAll2(n_inter), tAll1(n_inter), tAll2(n_inter);
    for(int i = 0; i < (int)interIdx1.total(); ++i)
    {
        omAll1[i] = omAllTemp1[interIdx1.at<int>(i)];
        tAll1[i] = tAllTemp1[interIdx1.at<int>(i)];
        omAll2[i] = omAllTemp2[interIdx2.at<int>(i)];
        tAll2[i] = tAllTemp2[interIdx2.at<int>(i)];
    }

    // initialize R,T
    Mat omEstAll(1, n_inter, CV_64FC3), tEstAll(1, n_inter, CV_64FC3);
    Mat R1, R2, T1, T2, omLR, TLR, RLR;
    for (int i = 0; i < n_inter; ++i)
    {
        Rodrigues(omAll1[i], R1);
        Rodrigues(omAll2[i], R2);
        T1 = Mat(tAll1[i]).reshape(1, 3);
        T2 = Mat(tAll2[i]).reshape(1, 3);
        RLR = R2 * R1.t();
        TLR = T2 - RLR*T1;
        Rodrigues(RLR, omLR);
        omLR.reshape(3, 1).copyTo(omEstAll.col(i));
        TLR.reshape(3, 1).copyTo(tEstAll.col(i));
    }
    Vec3d omEst = internal::findMedian3(omEstAll);
    Vec3d tEst = internal::findMedian3(tEstAll);

    Mat(omEst).copyTo(om.getMat());
    Mat(tEst).copyTo(T.getMat());

    if (omL.empty())
    {
        omL.create((int)omAll1.size(), 1, CV_64FC3);
    }
    if (tL.empty())
    {
        tL.create((int)tAll1.size(), 1, CV_64FC3);
    }

    if(omL.kind() == _InputArray::STD_VECTOR_MAT)
    {
        for(int i = 0; i < n_inter; ++i)
        {
            omL.create(3, 1, CV_64F, i, true);
            tL.create(3, 1, CV_64F, i, true);
            omL.getMat(i) = Mat(omAll1[i]);
            tL.getMat(i) = Mat(tAll1[i]);
        }
    }
    else
    {
        cv::Mat(omAll1).convertTo(omL, CV_64FC3);
        cv::Mat(tAll1).convertTo(tL, CV_64FC3);
    }
    if (K1.empty())
    {
        K1.create(3, 3, CV_64F);
        K2.create(3, 3, CV_64F);
    }
    if (D1.empty())
    {
        D1.create(1, 4, CV_64F);
        D2.create(1, 4, CV_64F);
    }
    Mat(_K1).copyTo(K1.getMat());
    Mat(_K2).copyTo(K2.getMat());

    Mat(_D1).copyTo(D1.getMat());
    Mat(_D2).copyTo(D2.getMat());

    xi1 = _xi1m.at<double>(0);
    xi2 = _xi2m.at<double>(0);
840
}
841

842 843 844 845
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// cv::omnidir::internal::computeJacobian

void cv::omnidir::internal::computeJacobian(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints,
846
    InputArray parameters, Mat& JTJ_inv, Mat& JTE, int flags, double epsilon)
847 848 849 850 851 852 853 854 855
{
    CV_Assert(!objectPoints.empty() && objectPoints.type() == CV_64FC3);
    CV_Assert(!imagePoints.empty() && imagePoints.type() == CV_64FC2);

    int n = (int)objectPoints.total();

    Mat JTJ = Mat::zeros(10 + 6*n, 10 + 6*n, CV_64F);
    JTJ_inv = Mat::zeros(10 + 6*n, 10 + 6*n, CV_64F);
    JTE = Mat::zeros(10 + 6*n, 1, CV_64F);
856 857 858 859

    int nPointsAll = 0;
    for (int i = 0; i < n; ++i)
    {
baisheng lai's avatar
baisheng lai committed
860
        nPointsAll += (int)objectPoints.getMat(i).total();
861 862 863 864
    }

    Mat J = Mat::zeros(2*nPointsAll, 10+6*n, CV_64F);
    Mat exAll = Mat::zeros(2*nPointsAll, 10+6*n, CV_64F);
865 866 867 868 869 870 871 872 873
    double *para = parameters.getMat().ptr<double>();
    Matx33d K(para[6*n], para[6*n+2], para[6*n+3],
        0,    para[6*n+1], para[6*n+4],
        0,    0,  1);
    Matx14d D(para[6*n+6], para[6*n+7], para[6*n+8], para[6*n+9]);
    double xi = para[6*n+5];
    for (int i = 0; i < n; i++)
    {
        Mat objPoints, imgPoints, om, T;
874 875 876 877
		objectPoints.getMat(i).copyTo(objPoints);
		imagePoints.getMat(i).copyTo(imgPoints);
		objPoints = objPoints.reshape(3, objPoints.rows*objPoints.cols);
		imgPoints = imgPoints.reshape(2, imgPoints.rows*imgPoints.cols);
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901

        om = parameters.getMat().colRange(i*6, i*6+3);
        T = parameters.getMat().colRange(i*6+3, (i+1)*6);
        Mat imgProj, jacobian;
        omnidir::projectPoints(objPoints, imgProj, om, T, K, xi, D, jacobian);
        Mat projError = imgPoints - imgProj;

        // The intrinsic part of Jacobian
        Mat JIn(jacobian.rows, 10, CV_64F);
        Mat JEx(jacobian.rows, 6, CV_64F);

        jacobian.colRange(6, 16).copyTo(JIn);
        jacobian.colRange(0, 6).copyTo(JEx);

        JTJ(Rect(6*n, 6*n, 10, 10)) = JTJ(Rect(6*n, 6*n, 10, 10)) + JIn.t()*JIn;

        JTJ(Rect(i*6, i*6, 6, 6)) = JEx.t() * JEx;

        Mat JExTIn = JEx.t() * JIn;

        JExTIn.copyTo(JTJ(Rect(6*n, i*6, 10, 6)));

        Mat(JIn.t()*JEx).copyTo(JTJ(Rect(i*6, 6*n, 6, 10)));

baisheng lai's avatar
baisheng lai committed
902 903
        JTE(Rect(0, 6*n, 1, 10)) = JTE(Rect(0, 6*n,1, 10)) + JIn.t() * projError.reshape(1, 2*(int)projError.total());
        JTE(Rect(0, i*6, 1, 6)) = JEx.t() * projError.reshape(1, 2*(int)projError.total());
904

905 906 907 908 909 910 911
        //int nPoints = objectPoints.getMat(i).total();
        //JIn.copyTo(J(Rect(6*n, i*nPoints*2, 10, nPoints*2)));
        //JEx.copyTo(J(Rect(6*i, i*nPoints*2, 6, nPoints*2)));
        //projError.reshape(1, 2*projError.rows).copyTo(exAll.rowRange(i*2*nPoints, (i+1)*2*nPoints));
    }
    //JTJ = J.t()*J;
    //JTE = J.t()*exAll;
912 913 914 915 916 917
    std::vector<int> _idx(6*n+10, 1);
    flags2idx(flags, _idx, n);

    subMatrix(JTJ, JTJ, _idx, _idx);
    subMatrix(JTE, JTE, std::vector<int>(1, 1), _idx);
    // in case JTJ is singular
918 919 920 921 922 923 924 925 926 927
	//SVD svd(JTJ, SVD::NO_UV);
	//double cond = svd.w.at<double>(0)/svd.w.at<double>(5);

	//if (cond_JTJ.needed())
	//{
	//	cond_JTJ.create(1, 1, CV_64F);
	//	cond_JTJ.getMat().at<double>(0) = cond;
	//}

    //double epsilon = 1e-4*std::exp(cond);
928 929 930 931
    JTJ_inv = Mat(JTJ+epsilon).inv();
}

void cv::omnidir::internal::computeJacobianStereo(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
932
    InputArray parameters, Mat& JTJ_inv, Mat& JTE, int flags, double epsilon)
933 934 935 936 937 938 939
{
    CV_Assert(!objectPoints.empty() && objectPoints.type() == CV_64FC3);
    CV_Assert(!imagePoints1.empty() && imagePoints1.type() == CV_64FC2);
    CV_Assert(!imagePoints2.empty() && imagePoints2.type() == CV_64FC2);
    CV_Assert((imagePoints1.total() == imagePoints2.total()) && (imagePoints1.total() == objectPoints.total()));

    // compute Jacobian matrix by naive way
baisheng lai's avatar
baisheng lai committed
940 941
    int n_img = (int)objectPoints.total();
    int n_points = (int)objectPoints.getMat(0).total();
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
    Mat J = Mat::zeros(4 * n_points * n_img, 20 + 6 * (n_img + 1), CV_64F);
    Mat exAll = Mat::zeros(4 * n_points * n_img, 1, CV_64F);
    double *para = parameters.getMat().ptr<double>();
    int offset1 = (n_img + 1) * 6;
    int offset2 = offset1 + 10;
    Matx33d K1(para[offset1], para[offset1+2], para[offset1+3],
        0,    para[offset1+1], para[offset1+4],
        0,    0,  1);
    Matx14d D1(para[offset1+6], para[offset1+7], para[offset1+8], para[offset1+9]);
    double xi1 = para[offset1+5];

    Matx33d K2(para[offset2], para[offset2+2], para[offset2+3],
        0,    para[offset2+1], para[offset2+4],
        0,    0,  1);
    Matx14d D2(para[offset2+6], para[offset2+7], para[offset2+8], para[offset2+9]);
    double xi2 = para[offset2+5];

baisheng lai's avatar
baisheng lai committed
959 960
    Mat om = parameters.getMat().reshape(1, 1).colRange(0, 3);
    Mat T = parameters.getMat().reshape(1, 1).colRange(3, 6);
961 962 963

    for (int i = 0; i < n_img; i++)
    {
baisheng lai's avatar
baisheng lai committed
964
        Mat objPointsi, imgPoints1i, imgPoints2i, om1, T1;
965 966 967 968 969 970 971 972 973
        objectPoints.getMat(i).copyTo(objPointsi);
        imagePoints1.getMat(i).copyTo(imgPoints1i);
        imagePoints2.getMat(i).copyTo(imgPoints2i);
        objPointsi = objPointsi.reshape(3, objPointsi.rows*objPointsi.cols);
        imgPoints1i = imgPoints1i.reshape(2, imgPoints1i.rows*imgPoints1i.cols);
        imgPoints2i = imgPoints2i.reshape(2, imgPoints2i.rows*imgPoints2i.cols);

        om1 = parameters.getMat().reshape(1, 1).colRange((1 + i) * 6, (1 + i) * 6 + 3);
        T1 = parameters.getMat().reshape(1, 1).colRange((1 + i) * 6 + 3, (i + 1) * 6 + 6);
baisheng lai's avatar
baisheng lai committed
974

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996

        Mat imgProj1, imgProj2, jacobian1, jacobian2;

        // jacobian for left image
        cv::omnidir::projectPoints(objPointsi, imgProj1, om1, T1, K1, xi1, D1, jacobian1);
        Mat projError1 = imgPoints1i - imgProj1;
        //Mat JIn1(jacobian1.rows, 10, CV_64F);
        //Mat JEx1(jacobian1.rows, 6, CV_64F);
        jacobian1.colRange(6, 16).copyTo(J(Rect(6*(n_img+1), i*n_points*4, 10, n_points*2)));
        jacobian1.colRange(0, 6).copyTo(J(Rect(6+i*6, i*n_points*4, 6, n_points*2)));
        projError1.reshape(1, 2*n_points).copyTo(exAll.rowRange(i*4*n_points, (i*4+2)*n_points));

        //jacobian for right image
        Mat om2, T2, dom2dom1, dom2dT1, dom2dom, dom2dT, dT2dom1, dT2dT1, dT2dom, dT2dT;
        cv::omnidir::internal::compose_motion(om1, T1, om, T, om2, T2, dom2dom1, dom2dT1, dom2dom, dom2dT, dT2dom1, dT2dT1, dT2dom, dT2dT);
        cv::omnidir::projectPoints(objPointsi, imgProj2, om2, T2, K2, xi2, D2, jacobian2);
        Mat projError2 = imgPoints2i - imgProj2;
        projError2.reshape(1, 2*n_points).copyTo(exAll.rowRange((i*4+2)*n_points, (i*4+4)*n_points));
        Mat dxrdom = jacobian2.colRange(0, 3) * dom2dom + jacobian2.colRange(3, 6) * dT2dom;
        Mat dxrdT = jacobian2.colRange(0, 3) * dom2dT + jacobian2.colRange(3, 6) * dT2dT;
        Mat dxrdom1 = jacobian2.colRange(0, 3) * dom2dom1 + jacobian2.colRange(3, 6) * dT2dom1;
        Mat dxrdT1 = jacobian2.colRange(0, 3) * dom2dT1 + jacobian2.colRange(3, 6) * dT2dT1;
997

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
        dxrdom.copyTo(J(Rect(0, (i*4+2)*n_points, 3, n_points*2)));
        dxrdT.copyTo(J(Rect(3, (i*4+2)*n_points, 3, n_points*2)));
        dxrdom1.copyTo(J(Rect(6+i*6, (i*4+2)*n_points, 3, n_points*2)));
        dxrdT1.copyTo(J(Rect(6+i*6+3, (i*4+2)*n_points, 3, n_points*2)));
        jacobian2.colRange(6, 16).copyTo(J(Rect(6*(n_img+1)+10, (4*i+2)*n_points, 10, n_points*2)));
    }

    std::vector<int> _idx(6*(n_img+1)+20, 1);
    flags2idxStereo(flags, _idx, n_img);

    Mat JTJ = J.t()*J;
    JTE = J.t()*exAll;
    subMatrix(JTJ, JTJ, _idx, _idx);
    subMatrix(JTE, JTE, std::vector<int>(1, 1), _idx);
baisheng lai's avatar
baisheng lai committed
1012

1013 1014 1015
    JTJ_inv = Mat(JTJ+epsilon).inv();
}

1016 1017 1018 1019 1020 1021 1022 1023 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 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
// This function is from fisheye.cpp
void cv::omnidir::internal::compose_motion(InputArray _om1, InputArray _T1, InputArray _om2, InputArray _T2, Mat& om3, Mat& T3, Mat& dom3dom1,
    Mat& dom3dT1, Mat& dom3dom2, Mat& dom3dT2, Mat& dT3dom1, Mat& dT3dT1, Mat& dT3dom2, Mat& dT3dT2)
{
    Mat om1 = _om1.getMat();
    Mat om2 = _om2.getMat();
    Mat T1 = _T1.getMat().reshape(1, 3);
    Mat T2 = _T2.getMat().reshape(1, 3);

    //% Rotations:
    Mat R1, R2, R3, dR1dom1(9, 3, CV_64FC1), dR2dom2;
    Rodrigues(om1, R1, dR1dom1);
    Rodrigues(om2, R2, dR2dom2);
    //JRodriguesMatlab(dR1dom1, dR1dom1);
    //JRodriguesMatlab(dR2dom2, dR2dom2);
    dR1dom1 = dR1dom1.t();
    dR2dom2 = dR2dom2.t();

    R3 = R2 * R1;
    Mat dR3dR2, dR3dR1;
    //dAB(R2, R1, dR3dR2, dR3dR1);
    matMulDeriv(R2, R1, dR3dR2, dR3dR1);

    Mat dom3dR3;
    Rodrigues(R3, om3, dom3dR3);
    //JRodriguesMatlab(dom3dR3, dom3dR3);
    dom3dR3 = dom3dR3.t();
    dom3dom1 = dom3dR3 * dR3dR1 * dR1dom1;
    dom3dom2 = dom3dR3 * dR3dR2 * dR2dom2;
    dom3dT1 = Mat::zeros(3, 3, CV_64FC1);
    dom3dT2 = Mat::zeros(3, 3, CV_64FC1);

    //% Translations:
    Mat T3t = R2 * T1;
    Mat dT3tdR2, dT3tdT1;
    //dAB(R2, T1, dT3tdR2, dT3tdT1);
    matMulDeriv(R2, T1, dT3tdR2, dT3tdT1);
    Mat dT3tdom2 = dT3tdR2 * dR2dom2;
    T3 = T3t + T2;
    dT3dT1 = dT3tdT1;
    dT3dT2 = Mat::eye(3, 3, CV_64FC1);
    dT3dom2 = dT3tdom2;
    dT3dom1 = Mat::zeros(3, 3, CV_64FC1);
}

1061
double cv::omnidir::calibrate(InputArrayOfArrays patternPoints, InputArrayOfArrays imagePoints, Size size,
1062
    InputOutputArray K, InputOutputArray xi, InputOutputArray D, OutputArrayOfArrays omAll, OutputArrayOfArrays tAll,
1063
    int flags, TermCriteria criteria, OutputArray idx)
1064 1065
{
    CV_Assert(!patternPoints.empty() && !imagePoints.empty() && patternPoints.total() == imagePoints.total());
1066 1067 1068
    CV_Assert((patternPoints.type() == CV_64FC3 && imagePoints.type() == CV_64FC2) ||
        (patternPoints.type() == CV_32FC3 && imagePoints.type() == CV_32FC2));
    CV_Assert(patternPoints.getMat(0).channels() == 3 && imagePoints.getMat(0).channels() == 2);
1069 1070 1071
    CV_Assert((!K.empty() && K.size() == Size(3,3)) || K.empty());
    CV_Assert((!D.empty() && D.total() == 4) || D.empty());
    CV_Assert((!xi.empty() && xi.total() == 1) || xi.empty());
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    CV_Assert((!omAll.empty() && omAll.depth() == patternPoints.depth()) || omAll.empty());
    CV_Assert((!tAll.empty() && tAll.depth() == patternPoints.depth()) || tAll.empty());
    int depth = patternPoints.depth();

    std::vector<Mat> _patternPoints, _imagePoints;

    for (int i = 0; i < (int)patternPoints.total(); ++i)
    {
        _patternPoints.push_back(patternPoints.getMat(i));
        _imagePoints.push_back(imagePoints.getMat(i));
        if (depth == CV_32F)
        {
            _patternPoints[i].convertTo(_patternPoints[i], CV_64FC3);
            _imagePoints[i].convertTo(_imagePoints[i], CV_64FC2);
        }
    }
1088 1089 1090

    double _xi;
    // initialization
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    std::vector<Vec3d> _omAll, _tAll;
    Matx33d _K;
    Matx14d _D;
    Mat _idx;
    cv::omnidir::internal::initializeCalibration(_patternPoints, _imagePoints, size, _omAll, _tAll, _K, _xi, _idx);
    std::vector<Mat> _patternPointsTmp = _patternPoints;
    std::vector<Mat> _imagePointsTmp = _imagePoints;

    _patternPoints.clear();
    _imagePoints.clear();
    // erase
    for (int i = 0; i < (int)_idx.total(); i++)
    {
        _patternPoints.push_back(_patternPointsTmp[_idx.at<int>(i)]);
        _imagePoints.push_back(_imagePointsTmp[_idx.at<int>(i)]);
    }

    int n = (int)_patternPoints.size();
1109 1110
    Mat finalParam(1, 10 + 6*n, CV_64F);
    Mat currentParam(1, 10 + 6*n, CV_64F);
1111
    cv::omnidir::internal::encodeParameters(_K, _omAll, _tAll, Mat::zeros(1,4,CV_64F), _xi, currentParam);
1112 1113

    // optimization
1114
    const double alpha_smooth = 0.01;
1115 1116 1117 1118 1119 1120 1121 1122
    //const double thresh_cond = 1e6;
    double change = 1;
    for(int iter = 0; ; ++iter)
    {
        if ((criteria.type == 1 && iter >= criteria.maxCount)  ||
            (criteria.type == 2 && change <= criteria.epsilon) ||
            (criteria.type == 3 && (change <= criteria.epsilon || iter >= criteria.maxCount)))
            break;
1123
        double alpha_smooth2 = 1 - std::pow(1 - alpha_smooth, (double)iter + 1.0);
1124
        Mat JTJ_inv, JTError;
1125 1126
		double epsilon = 0.01 * std::pow(0.9, (double)iter/10);
        cv::omnidir::internal::computeJacobian(_patternPoints, _imagePoints, currentParam, JTJ_inv, JTError, flags, epsilon);
1127

1128
        // Gauss - Newton
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
        Mat G = alpha_smooth2*JTJ_inv * JTError;

        omnidir::internal::fillFixed(G, flags, n);

        finalParam = currentParam + G.t();

        change = norm(G) / norm(currentParam);

        currentParam = finalParam.clone();

1139
        cv::omnidir::internal::decodeParameters(currentParam, _K, _omAll, _tAll, _D, _xi);
baisheng lai's avatar
baisheng lai committed
1140
        //double repr = internal::computeMeanReproErr(_patternPoints, _imagePoints, _K, _D, _xi, _omAll, _tAll);
1141
    }
1142
    cv::omnidir::internal::decodeParameters(currentParam, _K, _omAll, _tAll, _D, _xi);
1143

baisheng lai's avatar
baisheng lai committed
1144
    //double repr = internal::computeMeanReproErr(_patternPoints, _imagePoints, _K, _D, _xi, _omAll, _tAll);
1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    if (omAll.needed())
    {
        omAll.create((int)_omAll.size(), 1, CV_64FC3);
    }
    if (tAll.needed())
    {
        tAll.create((int)_tAll.size(), 1, CV_64FC3);
    }
    if (omAll.kind() == _InputArray::STD_VECTOR_MAT)
    {
        for (int i = 0; i < n; ++i)
        {
            omAll.create(3, 1, CV_64F, i, true);
            tAll.create(3, 1, CV_64F, i, true);
            Mat tmpom = Mat(_omAll[i]);
            Mat tmpt = Mat(_tAll[i]);
            tmpom.convertTo(tmpom, CV_64F);
            tmpt.convertTo(tmpt, CV_64F);
            tmpom.copyTo(omAll.getMat(i));
            tmpt.copyTo(tAll.getMat(i));
        }
    }
    else
    {
        Mat(_omAll).convertTo(omAll, CV_64FC3);
        Mat(_tAll).convertTo(tAll, CV_64FC3);
    }

    if(K.empty())
    {
        K.create(3, 3, CV_64F);
    }
    if (D.empty())
    {
        D.create(1, 4, CV_64F);
    }

    Mat(_K).convertTo(K.getMat(), K.empty()? CV_64F : K.type());
    Mat(_D).convertTo(D.getMat(), D.empty() ? CV_64F: D.type());

    if (xi.empty())
1187
    {
1188
        xi.create(1, 1, CV_64F);
1189 1190 1191
    }
    Mat xi_m = Mat(1, 1, CV_64F);
    xi_m.at<double>(0) = _xi;
1192 1193 1194 1195
    xi_m.convertTo(xi.getMat(), xi.empty() ? CV_64F : xi.type());

    if (idx.needed())
    {
baisheng lai's avatar
baisheng lai committed
1196
        idx.create(1, (int)_idx.total(), CV_32S);
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
        _idx.copyTo(idx.getMat());
    }

    Vec2d std_error;
    double rms;
    Mat errors;
    cv::omnidir::internal::estimateUncertainties(_patternPoints, _imagePoints, finalParam, errors, std_error, rms, flags);
    return rms;
}

double cv::omnidir::stereoCalibrate(InputOutputArrayOfArrays objectPoints, InputOutputArrayOfArrays imagePoints1, InputOutputArrayOfArrays imagePoints2,
    const Size& imageSize1, const Size& imageSize2, InputOutputArray K1, InputOutputArray xi1, InputOutputArray D1, InputOutputArray K2, InputOutputArray xi2,
    InputOutputArray D2, OutputArray om, OutputArray T, OutputArrayOfArrays omL, OutputArrayOfArrays tL, int flags, TermCriteria criteria, OutputArray idx)
{
    CV_Assert(!objectPoints.empty() && (objectPoints.type() == CV_64FC3 || objectPoints.type() == CV_32FC3));
    CV_Assert(!imagePoints1.empty() && (imagePoints1.type() == CV_64FC2 || imagePoints1.type() == CV_32FC2));
    CV_Assert(!imagePoints2.empty() && (imagePoints2.type() == CV_64FC2 || imagePoints2.type() == CV_32FC2));

    CV_Assert(((flags & CALIB_USE_GUESS) && !K1.empty() && !D1.empty() && !K2.empty() && !D2.empty()) || !(flags & CALIB_USE_GUESS));

    int depth = objectPoints.depth();

1219 1220
    std::vector<Mat> _objectPoints, _imagePoints1, _imagePoints2,
					_objectPointsFilt, _imagePoints1Filt, _imagePoints2Filt;
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    for (int i = 0; i < (int)objectPoints.total(); ++i)
    {
        _objectPoints.push_back(objectPoints.getMat(i));
        _imagePoints1.push_back(imagePoints1.getMat(i));
        _imagePoints2.push_back(imagePoints2.getMat(i));
        if (depth == CV_32F)
        {
            _objectPoints[i].convertTo(_objectPoints[i], CV_64FC3);
            _imagePoints1[i].convertTo(_imagePoints1[i], CV_64FC2);
            _imagePoints2[i].convertTo(_imagePoints2[i], CV_64FC2);
        }
    }

    Matx33d _K1, _K2;
    Matx14d _D1, _D2;

    double _xi1, _xi2;

    std::vector<Vec3d> _omL, _TL;
    Vec3d _om, _T;

    // initializaition
    Mat _idx;
    internal::initializeStereoCalibration(_objectPoints, _imagePoints1, _imagePoints2, imageSize1, imageSize2, _om, _T, _omL, _TL, _K1, _D1, _K2, _D2, _xi1, _xi2, flags, _idx);
    if(idx.needed())
    {
        idx.create(1, (int)_idx.total(), CV_32S);
        _idx.copyTo(idx.getMat());
    }
1250 1251 1252 1253 1254 1255
	for (int i = 0; i < (int)_idx.total(); ++i)
	{
		_objectPointsFilt.push_back(_objectPoints[_idx.at<int>(i)]);
		_imagePoints1Filt.push_back(_imagePoints1[_idx.at<int>(i)]);
		_imagePoints2Filt.push_back(_imagePoints2[_idx.at<int>(i)]);
	}
1256

1257
    int n = (int)_objectPointsFilt.size();
1258 1259 1260
    Mat finalParam(1, 10 + 6*n, CV_64F);
    Mat currentParam(1, 10 + 6*n, CV_64F);

baisheng lai's avatar
baisheng lai committed
1261 1262
    //double repr1 = internal::computeMeanReproErrStereo(_objectPoints, _imagePoints1, _imagePoints2, _K1, _K2, _D1, _D2, _xi1, _xi2, _om,
    //    _T, _omL, _TL);
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    cv::omnidir::internal::encodeParametersStereo(_K1, _K2, _om, _T, _omL, _TL, _D1, _D2, _xi1, _xi2, currentParam);

    // optimization
    const double alpha_smooth = 0.01;
    double change = 1;
    for(int iter = 0; ; ++iter)
    {
        if ((criteria.type == 1 && iter >= criteria.maxCount)  ||
            (criteria.type == 2 && change <= criteria.epsilon) ||
            (criteria.type == 3 && (change <= criteria.epsilon || iter >= criteria.maxCount)))
            break;
        double alpha_smooth2 = 1 - std::pow(1 - alpha_smooth, (double)iter + 1.0);
        Mat JTJ_inv, JTError;
1276
		double epsilon = 0.01 * std::pow(0.9, (double)iter/10);
1277

1278 1279
        cv::omnidir::internal::computeJacobianStereo(_objectPointsFilt, _imagePoints1Filt, _imagePoints2Filt, currentParam,
			JTJ_inv, JTError, flags, epsilon);
1280

1281
        // Gauss - Newton
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
        Mat G = alpha_smooth2*JTJ_inv * JTError;

        omnidir::internal::fillFixedStereo(G, flags, n);

        finalParam = currentParam + G.t();

        change = norm(G) / norm(currentParam);

        currentParam = finalParam.clone();
        cv::omnidir::internal::decodeParametersStereo(currentParam, _K1, _K2, _om, _T, _omL, _TL, _D1, _D2, _xi1, _xi2);
baisheng lai's avatar
baisheng lai committed
1292 1293
        //double repr = internal::computeMeanReproErrStereo(_objectPoints, _imagePoints1, _imagePoints2, _K1, _K2, _D1, _D2, _xi1, _xi2, _om,
        //    _T, _omL, _TL);
1294 1295 1296

    }
    cv::omnidir::internal::decodeParametersStereo(finalParam, _K1, _K2, _om, _T, _omL, _TL, _D1, _D2, _xi1, _xi2);
baisheng lai's avatar
baisheng lai committed
1297 1298
    //double repr = internal::computeMeanReproErrStereo(_objectPoints, _imagePoints1, _imagePoints2, _K1, _K2, _D1, _D2, _xi1, _xi2, _om,
    //    _T, _omL, _TL);
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

    if (K1.empty())
    {
        K1.create(3, 3, CV_64F);
        D1.create(1, 4, CV_64F);
        K2.create(3, 3, CV_64F);
        D2.create(1, 4, CV_64F);
    }
    if (om.empty())
    {
1309 1310
        om.create(3, 1, CV_64F);
        T.create(3, 1, CV_64F);
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    }
    if (omL.empty())
    {
        omL.create(1, n, CV_64FC3);
        tL.create(1, n, CV_64FC3);
    }

    Mat(_K1).convertTo(K1.getMat(), K1.empty() ? CV_64F : K1.type());
    Mat(_D1).convertTo(D1.getMat(), D1.empty() ? CV_64F : D1.type());
    Mat(_K2).convertTo(K2.getMat(), K2.empty() ? CV_64F : K2.type());
    Mat(_D2).convertTo(D2.getMat(), D2.empty() ? CV_64F : D2.type());

    Mat(_om).convertTo(om.getMat(), om.empty() ? CV_64F: om.type());
    Mat(_T).convertTo(T.getMat(), T.empty() ? CV_64F: T.type());

    if (omL.needed())
    {
        omL.create((int)_omL.size(), 1, CV_64FC3);
    }
    if (tL.needed())
    {
        tL.create((int)_TL.size(), 1, CV_64FC3);
    }

    if (omL.kind() == _InputArray::STD_VECTOR_MAT)
    {
        for (int i = 0; i < n; ++i)
        {
            omL.create(3, 1, CV_64F, i, true);
            tL.create(3, 1, CV_64F, i, true);
            Mat(_omL[i]).copyTo(omL.getMat(i));
            Mat(_TL[i]).copyTo(tL.getMat(i));
        }
    }
    else
    {
        Mat(_omL).convertTo(omL, omL.empty() ? CV_64FC3 : omL.type());
        Mat(_TL).convertTo(tL, tL.empty() ? CV_64FC3 : tL.type());
    }

    Mat xi1_m = Mat(1, 1, CV_64F),
        xi2_m = Mat(1, 1, CV_64F);
    xi1_m.at<double>(0) = _xi1;
    xi2_m.at<double>(0) = _xi2;

    if (xi1.empty())
    {
        xi1.create(1, 1, CV_64F);
    }
    if (xi2.empty())
    {
        xi2.create(1, 1, CV_64F);
    }
    xi1_m.convertTo(xi1, xi1.empty() ? CV_64F : xi1.type());
    xi2_m.convertTo(xi2, xi2.empty() ? CV_64F : xi2.type());

    // compute uncertainty
1368 1369 1370
    Vec2d std_error;
    double rms;
    Mat errors;
1371

1372 1373
    cv::omnidir::internal::estimateUncertaintiesStereo(_objectPointsFilt, _imagePoints1Filt, _imagePoints2Filt,
		finalParam, errors, std_error, rms, flags);
1374 1375 1376
    return rms;
}

1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
void cv::omnidir::stereoReconstruct(InputArray image1, InputArray image2, InputArray K1, InputArray D1,
    InputArray xi1, InputArray K2, InputArray D2, InputArray xi2, InputArray R, InputArray T, int flag,
    int numDisparities, int SADWindowSize, OutputArray disparity, OutputArray image1Rec, OutputArray image2Rec,
    const Size& newSize, InputArray Knew, OutputArray pointCloud, int pointType)
{
    CV_Assert(!K1.empty() && K1.size() == Size(3,3) && (K1.type() == CV_64F || K1.type() == CV_32F));
    CV_Assert(!K2.empty() && K2.size() == Size(3,3) && (K2.type() == CV_64F || K2.type() == CV_32F));
    CV_Assert(!D1.empty() && D1.total() == 4 && (D1.type() == CV_64F || D1.type() == CV_32F));
    CV_Assert(!D2.empty() && D2.total() == 4 && (D2.type() == CV_64F || D2.type() == CV_32F));
    CV_Assert(!R.empty() && (R.size() == Size(3,3) || R.total() == 3) && (R.type() == CV_64F || R.type() == CV_32F));
    CV_Assert(!T.empty() && T.total() == 3 && (T.type() == CV_64F || T.type() == CV_32F));
    CV_Assert(!image1.empty() && (image1.type() == CV_8U || image1.type() == CV_8UC3));
    CV_Assert(!image2.empty() && (image2.type() == CV_8U || image2.type() == CV_8UC3));
    CV_Assert(flag == omnidir::RECTIFY_LONGLATI || flag == omnidir::RECTIFY_PERSPECTIVE);

    Mat _K1, _D1, _K2, _D2, _R, _T;

    K1.getMat().convertTo(_K1, CV_64F);
    K2.getMat().convertTo(_K2, CV_64F);
    D1.getMat().convertTo(_D1, CV_64F);
    D2.getMat().convertTo(_D2, CV_64F);
    T.getMat().reshape(1, 3).convertTo(_T, CV_64F);

    if (R.size() == Size(3, 3))
    {
        R.getMat().convertTo(_R, CV_64F);
    }
    else if (R.total() == 3)
    {
        Rodrigues(R.getMat(), _R);
        _R.convertTo(_R, CV_64F);
    }
    // stereo rectify so that stereo matching can be applied in one line
    Mat R1, R2;
    stereoRectify(_R, _T, R1, R2);
    Mat undis1, undis2;
    Matx33d _Knew = Matx33d(_K1);
    if (!Knew.empty())
    {
        Knew.getMat().convertTo(_Knew, CV_64F);
    }

    undistortImage(image1.getMat(), undis1, _K1, _D1, xi1, flag, _Knew, newSize, R1);
    undistortImage(image2.getMat(), undis2, _K2, _D2, xi2, flag, _Knew, newSize, R2);

    undis1.copyTo(image1Rec);
    undis2.copyTo(image2Rec);

    // stereo matching by semi-global
    Mat _disMap;
    int channel = image1.channels();

    //cv::StereoSGBM matching(0, numDisparities, SADWindowSize, 8*channel*SADWindowSize*SADWindowSize, 32*channel*SADWindowSize*SADWindowSize);
    //matching(undis1, undis2, _depthMap);
	Ptr<StereoSGBM> sgbm = StereoSGBM::create(0, numDisparities, SADWindowSize, 8 * channel*SADWindowSize*SADWindowSize, 32 * channel*SADWindowSize*SADWindowSize);

	sgbm->compute(undis1, undis2, _disMap);

    // some regions of image1 is black, the corresponding regions of disparity map is also invalid.
    Mat realDis;
	_disMap.convertTo(_disMap, CV_32F);
    Mat(_disMap/16.0f).convertTo(realDis, CV_32F);

    Mat grayImg, binaryImg, idx;
    if (undis1.channels() == 3)
    {
        cvtColor(undis1, grayImg, COLOR_RGB2GRAY);
    }
    else
    {
        grayImg = undis1;
    }

    binaryImg = (grayImg <= 0);
    findNonZero(binaryImg, idx);
    for (int i = 0; i < (int)idx.total(); ++i)
    {
        Vec2i _idx = idx.at<Vec2i>(i);
        realDis.at<float>(_idx[1], _idx[0]) = 0.0f;
    }

    disparity.create(realDis.size(), realDis.type());
    realDis.copyTo(disparity.getMat());

    std::vector<Vec3f> _pointCloud;
    std::vector<Vec6f> _pointCloudColor;
    double baseline = cv::norm(T);
    double f = _Knew(0, 0);
    Matx33d K_inv = _Knew.inv();

    std::vector<Mat> rgb;
    if (undis1.channels() == 3)
    {
        split(undis1, rgb);
    }

    if (pointCloud.needed())
    {
        for (int i = 0; i < newSize.width; ++i)
        {
            for(int j = 0; j < newSize.height; ++j)
            {
                Vec3f point;
                Vec6f pointColor;
                if (realDis.at<float>(j, i) > 15)
                {
                    float depth = float(baseline * f /realDis.at<float>(j, i));
                    // for RECTIFY_PERSPECTIVE, (x,y) are image plane points,
                    // for RECTIFY_LONGLATI, (x,y) are (theta, phi) angles
                    float x = float(K_inv(0,0) * i + K_inv(0,1) * j + K_inv(0,2));
                    float y = float(K_inv(1,0) * i + K_inv(1,1) * j + K_inv(1,2));
                    if (flag == omnidir::RECTIFY_LONGLATI)
                    {
                        point = Vec3f((float)-std::cos(x), (float)(-std::sin(x)*std::cos(y)), (float)(std::sin(x)*std::sin(y))) * depth;
                    }
                    else if(flag == omnidir::RECTIFY_PERSPECTIVE)
                    {
                        point = Vec3f(float(x), float(y), 1.0f) * depth;
                    }
                    if (pointType == XYZ)
                    {
                        _pointCloud.push_back(point);
                    }
                    else if (pointType == XYZRGB)
                    {
                        pointColor[0] = point[0];
                        pointColor[1] = point[1];
                        pointColor[2] = point[2];

                        if (undis1.channels() == 1)
                        {
                            pointColor[3] = float(undis1.at<uchar>(j, i));
                            pointColor[4] = pointColor[3];
                            pointColor[5] = pointColor[3];
                        }
                        else if (undis1.channels() == 3)
                        {
                            pointColor[3] = rgb[0].at<uchar>(j, i);
                            pointColor[4] = rgb[1].at<uchar>(j, i);
                            pointColor[5] = rgb[2].at<uchar>(j, i);
                        }
                        _pointCloudColor.push_back(pointColor);
                    }
                }
            }
        }
baisheng lai's avatar
baisheng lai committed
1523

1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
        if (pointType == XYZ)
        {
            Mat(_pointCloud).convertTo(pointCloud, CV_MAKE_TYPE(CV_32F, 3));
        }
        else if (pointType == XYZRGB)
        {
            Mat(_pointCloudColor).convertTo(pointCloud, CV_MAKE_TYPE(CV_32F, 6));
        }
    }
}

void cv::omnidir::internal::encodeParameters(InputArray K, InputArrayOfArrays omAll, InputArrayOfArrays tAll, InputArray distoaration, double xi, OutputArray parameters)
1536 1537 1538
{
    CV_Assert(K.type() == CV_64F && K.size() == Size(3,3));
    CV_Assert(distoaration.total() == 4 && distoaration.type() == CV_64F);
baisheng lai's avatar
baisheng lai committed
1539
    int n = (int)omAll.total();
1540
    Mat _omAll = omAll.getMat(), _tAll = tAll.getMat();
1541

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
    Matx33d _K = K.getMat();
    Vec4d _D = (Vec4d)distoaration.getMat();
    parameters.create(1, 10+6*n,CV_64F);
    Mat _params = parameters.getMat();
    for (int i = 0; i < n; i++)
    {
        Mat(_omAll.at<Vec3d>(i)).reshape(1, 1).copyTo(_params.colRange(i*6, i*6+3));
        Mat(_tAll.at<Vec3d>(i)).reshape(1, 1).copyTo(_params.colRange(i*6+3, (i+1)*6));
    }

    _params.at<double>(0, 6*n) = _K(0,0);
    _params.at<double>(0, 6*n+1) = _K(1,1);
    _params.at<double>(0, 6*n+2) = _K(0,1);
    _params.at<double>(0, 6*n+3) = _K(0,2);
    _params.at<double>(0, 6*n+4) = _K(1,2);
    _params.at<double>(0, 6*n+5) = xi;
    _params.at<double>(0, 6*n+6) = _D[0];
    _params.at<double>(0, 6*n+7) = _D[1];
    _params.at<double>(0, 6*n+8) = _D[2];
    _params.at<double>(0, 6*n+9) = _D[3];
}

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
void cv::omnidir::internal::encodeParametersStereo(InputArray K1, InputArray K2, InputArray om, InputArray T, InputArrayOfArrays omL, InputArrayOfArrays tL,
    InputArray D1, InputArray D2, double xi1, double xi2, OutputArray parameters)
{
    CV_Assert(!K1.empty() && K1.type() == CV_64F && K1.size() == Size(3,3));
    CV_Assert(!K2.empty() && K2.type() == CV_64F && K2.size() == Size(3,3));
    CV_Assert(!om.empty() && om.type() == CV_64F && om.total() == 3);
    CV_Assert(!T.empty() && T.type() == CV_64F && T.total() == 3);
    CV_Assert(omL.total() == tL.total() && omL.type() == CV_64FC3 && tL.type() == CV_64FC3);
    CV_Assert(D1.type() == CV_64F && D1.total() == 4 && D2.type() == CV_64F && D2.total() == 4);

    int n = (int)omL.total();
    // om, T, omL, tL, intrinsic left, intrinsic right
    parameters.create(1, 20 + 6 * (n + 1), CV_64F);

    Mat _params = parameters.getMat();

    om.getMat().reshape(1, 1).copyTo(_params.colRange(0, 3));
    T.getMat().reshape(1, 1).copyTo(_params.colRange(3, 6));
    for(int i = 0; i < n; ++i)
    {
        Mat(omL.getMat().at<Vec3d>(i)).reshape(1, 1).copyTo(_params.colRange(6 + i*6, 6 + i*6 + 3));
        Mat(tL.getMat().at<Vec3d>(i)).reshape(1, 1).copyTo(_params.colRange(6 + i*6 + 3, 6 + i*6 + 6));
    }

    Matx33d _K1 = K1.getMat();
    Matx33d _K2 = K2.getMat();
    Vec4d _D1 = D1.getMat();
    Vec4d _D2 = D2.getMat();
    _params.at<double>(0, 6*(n+1)) = _K1(0,0);
    _params.at<double>(0, 6*(n+1)+1) = _K1(1,1);
    _params.at<double>(0, 6*(n+1)+2) = _K1(0,1);
    _params.at<double>(0, 6*(n+1)+3) = _K1(0,2);
    _params.at<double>(0, 6*(n+1)+4) = _K1(1,2);
    _params.at<double>(0, 6*(n+1)+5) = xi1;
    _params.at<double>(0, 6*(n+1)+6) = _D1[0];
    _params.at<double>(0, 6*(n+1)+7) = _D1[1];
    _params.at<double>(0, 6*(n+1)+8) = _D1[2];
    _params.at<double>(0, 6*(n+1)+9) = _D1[3];

    _params.at<double>(0, 6*(n+1)+10) = _K2(0,0);
    _params.at<double>(0, 6*(n+1)+11) = _K2(1,1);
    _params.at<double>(0, 6*(n+1)+12) = _K2(0,1);
    _params.at<double>(0, 6*(n+1)+13) = _K2(0,2);
    _params.at<double>(0, 6*(n+1)+14) = _K2(1,2);
    _params.at<double>(0, 6*(n+1)+15) = xi2;
    _params.at<double>(0, 6*(n+1)+16) = _D2[0];
    _params.at<double>(0, 6*(n+1)+17) = _D2[1];
    _params.at<double>(0, 6*(n+1)+18) = _D2[2];
    _params.at<double>(0, 6*(n+1)+19) = _D2[3];
}


 void cv::omnidir::internal::decodeParameters(InputArray parameters, OutputArray K, OutputArrayOfArrays omAll, OutputArrayOfArrays tAll, OutputArray distoration, double& xi)
1617 1618 1619 1620
 {
    if(K.empty())
        K.create(3,3,CV_64F);
    Matx33d _K;
1621
    int n = (int)(parameters.total()-10)/6;
1622 1623 1624 1625 1626 1627 1628
    if(omAll.empty())
        omAll.create(1, n, CV_64FC3);
    if(tAll.empty())
        tAll.create(1, n, CV_64FC3);
    if(distoration.empty())
        distoration.create(1, 4, CV_64F);
    Matx14d _D = distoration.getMat();
1629
    Mat param = parameters.getMat();
1630 1631 1632 1633 1634 1635
    double *para = param.ptr<double>();
    _K = Matx33d(para[6*n], para[6*n+2], para[6*n+3],
        0,    para[6*n+1], para[6*n+4],
        0,    0,  1);
    _D  = Matx14d(para[6*n+6], para[6*n+7], para[6*n+8], para[6*n+9]);
    xi = para[6*n+5];
1636
    std::vector<Vec3d> _omAll(n), _tAll(n);
1637 1638
    for (int i = 0; i < n; i++)
    {
1639 1640
        _omAll[i] = Vec3d(param.colRange(i*6, i*6+3));
        _tAll[i] = Vec3d(param.colRange(i*6+3, i*6+6));
1641 1642 1643 1644
    }
    Mat(_D).convertTo(distoration, CV_64F);
    Mat(_K).convertTo(K, CV_64F);

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    if (omAll.kind() == _InputArray::STD_VECTOR_MAT)
    {
        for (int i = 0; i < n; ++i)
        {
            Mat(_omAll[i]).copyTo(omAll.getMat(i));
            Mat(_tAll[i]).copyTo(tAll.getMat(i));
        }
    }
    else
    {
        Mat(_omAll).convertTo(omAll, CV_64FC3);
        Mat(_tAll).convertTo(tAll, CV_64FC3);
    }
}

 void cv::omnidir::internal::decodeParametersStereo(InputArray parameters, OutputArray K1, OutputArray K2, OutputArray om, OutputArray T, OutputArrayOfArrays omL,
     OutputArrayOfArrays tL, OutputArray D1, OutputArray D2, double& xi1, double& xi2)
 {
    if(K1.empty())
        K1.create(3, 3, CV_64F);
    if(K2.empty())
        K2.create(3, 3, CV_64F);
    if(om.empty())
        om.create(3, 1, CV_64F);
    if(T.empty())
        T.create(3, 1, CV_64F);

baisheng lai's avatar
baisheng lai committed
1672
    int n = ((int)parameters.total() - 20) / 6 - 1;
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725

    if(omL.empty())
        omL.create(1, n, CV_64FC3);
    if(tL.empty())
        tL.create(1, n, CV_64FC3);
    if(D1.empty())
        D1.create(1, 4, CV_64F);
    if(D2.empty())
        D2.create(1, 4, CV_64F);

    Mat param = parameters.getMat().reshape(1, 1);
    param.colRange(0, 3).reshape(1, 3).copyTo(om.getMat());
    param.colRange(3, 6).reshape(1, 3).copyTo(T.getMat());
    std::vector<Vec3d> _omL, _tL;

    for(int i = 0; i < n; i++)
    {
        _omL.push_back(Vec3d(param.colRange(6 + i*6, 6 + i*6 + 3)));
        _tL.push_back(Vec3d(param.colRange(6 + i*6 + 3, 6 + i*6 + 6)));
    }

    double* para = param.ptr<double>();
    int offset1 = (n + 1)*6;
    Matx33d _K1(para[offset1], para[offset1+2], para[offset1+3],
                0,      para[offset1+1],     para[offset1+4],
                0,          0,                  1);
    xi1 = para[offset1+5];
    Matx14d _D1(para[offset1+6], para[offset1+7], para[offset1+8], para[offset1+9]);

    int offset2 = (n + 1)*6 + 10;
    Matx33d _K2(para[offset2], para[offset2+2], para[offset2+3],
                0,      para[offset2+1],     para[offset2+4],
                0,          0,                  1);
    xi2 = para[offset2+5];
    Matx14d _D2(para[offset2+6], para[offset2+7], para[offset2+8], para[offset2+9]);

    Mat(_K1).convertTo(K1, CV_64F);
    Mat(_D1).convertTo(D1, CV_64F);
    Mat(_K2).convertTo(K2, CV_64F);
    Mat(_D2).convertTo(D2, CV_64F);
    if(omL.kind() == _InputArray::STD_VECTOR_MAT)
    {
        for(int i = 0; i < n; ++i)
        {
            Mat(_omL[i]).copyTo(omL.getMat(i));
            Mat(_tL[i]).copyTo(tL.getMat(i));
        }
    }
    else
    {
        Mat(_omL).convertTo(omL, CV_64FC3);
        Mat(_tL).convertTo(tL, CV_64FC3);
    }
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
 }

void cv::omnidir::internal::estimateUncertainties(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, InputArray parameters,
    Mat& errors, Vec2d& std_error, double& rms, int flags)
{
    CV_Assert(!objectPoints.empty() && objectPoints.type() == CV_64FC3);
    CV_Assert(!imagePoints.empty() && imagePoints.type() == CV_64FC2);
    CV_Assert(!parameters.empty() && parameters.type() == CV_64F);

    int n = (int) objectPoints.total();
    // assume every image has the same number of objectpoints
1737 1738 1739
    int nPointsAll = 0;
    for (int i = 0; i < n; ++i)
    {
baisheng lai's avatar
baisheng lai committed
1740
        nPointsAll += (int)objectPoints.getMat(i).total();
1741
    }
1742

1743
    Mat reprojError = Mat(nPointsAll, 1, CV_64FC2);
1744 1745 1746 1747 1748 1749 1750

    double* para = parameters.getMat().ptr<double>();
    Matx33d K(para[6*n], para[6*n+2], para[6*n+3],
              0,    para[6*n+1], para[6*n+4],
              0,    0,  1);
    Matx14d D(para[6*n+6], para[6*n+7], para[6*n+8], para[6*n+9]);
    double xi = para[6*n+5];
1751
    int nPointsAccu = 0;
1752 1753 1754

    for(int i=0; i < n; ++i)
    {
1755 1756 1757 1758 1759
		Mat imgPoints, objPoints;
		imagePoints.getMat(i).copyTo(imgPoints);
		objectPoints.getMat(i).copyTo(objPoints);
		imgPoints = imgPoints.reshape(2, imgPoints.rows*imgPoints.cols);
		objPoints = objPoints.reshape(3, objPoints.rows*objPoints.cols);
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769

        Mat om = parameters.getMat().colRange(i*6, i*6+3);
        Mat T = parameters.getMat().colRange(i*6+3, (i+1)*6);

        Mat x;
        omnidir::projectPoints(objPoints, x, om, T, K, xi, D, cv::noArray());

        Mat errorx = (imgPoints - x);

        //reprojError.rowRange(errorx.rows*i, errorx.rows*(i+1)) = errorx.clone();
1770 1771
        errorx.copyTo(reprojError.rowRange(nPointsAccu, nPointsAccu + (int)errorx.total()));
        nPointsAccu += (int)errorx.total();
1772 1773 1774 1775 1776
    }

    meanStdDev(reprojError, noArray(), std_error);
    std_error *= sqrt((double)reprojError.total()/((double)reprojError.total() - 1.0));

1777 1778 1779 1780
    Mat sigma_x;
    meanStdDev(reprojError.reshape(1,1), noArray(), sigma_x);
    sigma_x *= sqrt(2.0*(double)reprojError.total()/(2.0*(double)reprojError.total() - 1.0));
    double s = sigma_x.at<double>(0);
1781 1782

    Mat _JTJ_inv, _JTE;
1783
    computeJacobian(objectPoints, imagePoints, parameters, _JTJ_inv, _JTE, flags, 0.0);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
    sqrt(_JTJ_inv, _JTJ_inv);

    errors = 3 * s * _JTJ_inv.diag();

    rms = 0;
    const Vec2d* ptr_ex = reprojError.ptr<Vec2d>();
    for (int i = 0; i < (int)reprojError.total(); i++)
    {
        rms += ptr_ex[i][0] * ptr_ex[i][0] + ptr_ex[i][1] * ptr_ex[i][1];
    }

    rms /= (double)reprojError.total();
    rms = sqrt(rms);
}

1799 1800 1801 1802 1803 1804 1805
// estimateUncertaintiesStereo
void cv::omnidir::internal::estimateUncertaintiesStereo(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2,
    InputArray parameters, Mat& errors, Vec2d& std_error, double& rms, int flags)
{
    CV_Assert(!objectPoints.empty() && objectPoints.type() == CV_64FC3);
    CV_Assert(!imagePoints1.empty() && imagePoints1.type() == CV_64FC2 && imagePoints1.total() == objectPoints.total());
    CV_Assert(!imagePoints2.empty() && imagePoints2.type() == CV_64FC2 && imagePoints1.total() == imagePoints2.total());
baisheng lai's avatar
baisheng lai committed
1806
    int n_img = (int)objectPoints.total();
1807 1808 1809 1810 1811 1812 1813 1814 1815
    CV_Assert((int)parameters.total() == (6*(n_img+1)+20));

    Mat _K1, _K2, _D1, _D2;
    Vec3d _om, _T;
    std::vector<Vec3d> _omL(n_img), _tL(n_img);
    Mat _parameters = parameters.getMat().reshape(1, 1);
    double _xi1, _xi2;
    internal::decodeParametersStereo(_parameters, _K1, _K2, _om, _T, _omL, _tL, _D1, _D2, _xi1, _xi2);

baisheng lai's avatar
baisheng lai committed
1816
    int n_points = (int)objectPoints.getMat(0).total();
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
    Mat reprojErrorAll = Mat::zeros(2*n_points*n_img, 1, CV_64FC2);

    // error for left image
    for (int i = 0; i < n_img; ++i)
    {
        Mat objPointsi, imgPointsi;
        objectPoints.getMat(i).copyTo(objPointsi);
        imagePoints1.getMat(i).copyTo(imgPointsi);
        objPointsi = objPointsi.reshape(3, objPointsi.rows*objPointsi.cols);
        imgPointsi = imgPointsi.reshape(2, imgPointsi.rows*imgPointsi.cols);

        Mat x;
        omnidir::projectPoints(objPointsi, x, _omL[i], _tL[i], _K1, _xi1, _D1, cv::noArray());

        Mat errorx = imgPointsi - x;

        errorx.copyTo(reprojErrorAll.rowRange(i*2*n_points, (i*2+1)*n_points));
    }
    // error for right image
    for (int i = 0; i < n_img; ++i)
    {
        Mat objPointsi, imgPointsi;
        objectPoints.getMat(i).copyTo(objPointsi);
        imagePoints2.getMat(i).copyTo(imgPointsi);
        objPointsi = objPointsi.reshape(3, objPointsi.rows*objPointsi.cols);
        imgPointsi = imgPointsi.reshape(2, imgPointsi.rows*imgPointsi.cols);

        Mat x;
        Mat _R, _R2, _R1, _T2, _T1, _om2;
        Rodrigues(_om, _R);
        Rodrigues(_omL[i], _R1);
        _T1 = Mat(_tL[i]);
        _R2 = _R * _R1;
        _T2 = _R * _T1 + Mat(_T);
        Rodrigues(_R2, _om2);

        omnidir::projectPoints(objPointsi, x, _om2, _T2, _K2, _xi2, _D2, cv::noArray());

        Mat errorx = imgPointsi - x;

        errorx.copyTo(reprojErrorAll.rowRange((i*2+1)*n_points, (i+1)*2*n_points));
    }

    meanStdDev(reprojErrorAll, cv::noArray(), std_error);
    std_error *= sqrt((double)reprojErrorAll.total()/((double)reprojErrorAll.total() - 1.0));

    Mat sigma_x;
    meanStdDev(reprojErrorAll.reshape(1,1), noArray(), sigma_x);
    sigma_x *= sqrt(2.0*(double)reprojErrorAll.total()/(2.0*(double)reprojErrorAll.total() - 1.0));
    double s = sigma_x.at<double>(0);

    Mat _JTJ_inv, _JTE;
1869
    computeJacobianStereo(objectPoints, imagePoints1, imagePoints2, _parameters, _JTJ_inv, _JTE, flags, 0.0);
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
    cv::sqrt(_JTJ_inv, _JTJ_inv);

    errors = 3 * s * _JTJ_inv.diag();

    rms = 0;

    const Vec2d* ptr_ex = reprojErrorAll.ptr<Vec2d>();
    for (int i = 0; i < (int)reprojErrorAll.total(); i++)
    {
        rms += ptr_ex[i][0] * ptr_ex[i][0] + ptr_ex[i][1] * ptr_ex[i][1];
    }
    rms /= (double)reprojErrorAll.total();
    rms = sqrt(rms);
}

1885
//
1886
double cv::omnidir::internal::computeMeanReproErr(InputArrayOfArrays imagePoints, InputArrayOfArrays proImagePoints)
1887 1888 1889 1890 1891 1892 1893 1894
{
    CV_Assert(!imagePoints.empty() && imagePoints.type()==CV_64FC2);
    CV_Assert(!proImagePoints.empty() && proImagePoints.type() == CV_64FC2);
    CV_Assert(imagePoints.total() == proImagePoints.total());

    int n = (int)imagePoints.total();
    double reprojError = 0;
    int totalPoints = 0;
1895
    if (imagePoints.kind() == _InputArray::STD_VECTOR_MAT)
1896
    {
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
        for (int i = 0; i < n; i++)
        {
			Mat x, proj_x;
			imagePoints.getMat(i).copyTo(x);
			proImagePoints.getMat(i).copyTo(proj_x);
			Mat errorI = x.reshape(2, x.rows*x.cols) - proj_x.reshape(2, proj_x.rows*proj_x.cols);
            //Mat errorI = imagePoints.getMat(i) - proImagePoints.getMat(i);
            totalPoints += (int)errorI.total();
            Vec2d* ptr_err = errorI.ptr<Vec2d>();
            for (int j = 0; j < (int)errorI.total(); j++)
            {
                reprojError += sqrt(ptr_err[j][0]*ptr_err[j][0] + ptr_err[j][1]*ptr_err[j][1]);
            }
        }
    }
    else
    {
		Mat x, proj_x;
		imagePoints.getMat().copyTo(x);
		proImagePoints.getMat().copyTo(proj_x);
		Mat errorI = x.reshape(2, x.rows*x.cols) - proj_x.reshape(2, proj_x.rows*proj_x.cols);
        //Mat errorI = imagePoints.getMat() - proImagePoints.getMat();
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
        totalPoints += (int)errorI.total();
        Vec2d* ptr_err = errorI.ptr<Vec2d>();
        for (int j = 0; j < (int)errorI.total(); j++)
        {
            reprojError += sqrt(ptr_err[j][0]*ptr_err[j][0] + ptr_err[j][1]*ptr_err[j][1]);
        }
    }
    double meanReprojError = reprojError / totalPoints;
    return meanReprojError;
}

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995
double cv::omnidir::internal::computeMeanReproErr(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, InputArray K, InputArray D, double xi, InputArrayOfArrays omAll,
    InputArrayOfArrays tAll)
{
    CV_Assert(objectPoints.total() == imagePoints.total());
    CV_Assert(!objectPoints.empty() && objectPoints.type() == CV_64FC3);
    CV_Assert(!imagePoints.empty() && imagePoints.type() == CV_64FC2);
    std::vector<Mat> proImagePoints;
    int n = (int)objectPoints.total();
    Mat _omAll = omAll.getMat();
    Mat _tAll = tAll.getMat();
    for(int i = 0; i < n; ++i)
    {
        Mat imgPoint;
        //cv::omnidir::projectPoints(objetPoints.getMat(i), imgPoint, omAll.getMat(i), tAll.getMat(i), K.getMat(), xi, D.getMat(), noArray());
        cv::omnidir::projectPoints(objectPoints.getMat(i), imgPoint, _omAll.at<Vec3d>(i), _tAll.at<Vec3d>(i), K.getMat(), xi, D.getMat(), noArray());
        proImagePoints.push_back(imgPoint);
    }

    return internal::computeMeanReproErr(imagePoints, proImagePoints);
}

double cv::omnidir::internal::computeMeanReproErrStereo(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, InputArray K1, InputArray K2,
    InputArray D1, InputArray D2, double xi1, double xi2, InputArray om, InputArray T, InputArrayOfArrays omL, InputArrayOfArrays TL)
{
    CV_Assert(objectPoints.total() == imagePoints1.total() && imagePoints1.total() == imagePoints2.total());
    CV_Assert(!objectPoints.empty() && objectPoints.type() == CV_64FC3);
    CV_Assert(!imagePoints1.empty() && imagePoints1.type() == CV_64FC2);
    CV_Assert(!imagePoints2.empty() && imagePoints2.type() == CV_64FC2);

    std::vector<Mat> proImagePoints1, proImagePoints2;
    int n = (int)objectPoints.total();
    Mat _omL = omL.getMat(), _TL = TL.getMat();
    Mat _om = om.getMat(), _R, _T = T.getMat();
    Rodrigues(_om, _R);
    Mat _K1 = K1.getMat(), _K2 = K2.getMat();
    Mat _D1 = D1.getMat(), _D2 = D2.getMat();

    // reprojection error for left image
    for (int i = 0; i < n; ++i)
    {
        Mat imgPoints;
        cv::omnidir::projectPoints(objectPoints.getMat(i), imgPoints, _omL.at<Vec3d>(i), _TL.at<Vec3d>(i), _K1, xi1, _D1, cv::noArray());
        proImagePoints1.push_back(imgPoints);
    }

    // reprojection error for right image
    for (int i = 0; i < n; ++i)
    {
        Mat imgPoints;
        Mat _omRi,_RRi,_TRi,_RLi, _TLi;
        Rodrigues(_omL.at<Vec3d>(i), _RLi);
        _TLi = Mat(_TL.at<Vec3d>(i)).reshape(1, 3);
        _RRi = _R * _RLi;
        _TRi = _R * _TLi + _T;
        Rodrigues(_RRi, _omRi);
        cv::omnidir::projectPoints(objectPoints.getMat(i), imgPoints, _omRi, _TRi, _K2, xi2, _D2, cv::noArray());
        proImagePoints2.push_back(imgPoints);
    }
    double reProErr1 = internal::computeMeanReproErr(imagePoints1, proImagePoints1);
    double reProErr2 = internal::computeMeanReproErr(imagePoints2, proImagePoints2);

    double reProErr = (reProErr1 + reProErr2) / 2.0;
    //double reProErr = reProErr1*reProErr1 + reProErr2* reProErr2;
    return reProErr;
}

1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
// This function is from fisheye.cpp
void cv::omnidir::internal::subMatrix(const Mat& src, Mat& dst, const std::vector<int>& cols, const std::vector<int>& rows)
{
    CV_Assert(src.type() == CV_64FC1);

    int nonzeros_cols = cv::countNonZero(cols);
    Mat tmp(src.rows, nonzeros_cols, CV_64FC1);

    for (int i = 0, j = 0; i < (int)cols.size(); i++)
    {
        if (cols[i])
        {
            src.col(i).copyTo(tmp.col(j++));
        }
    }

    int nonzeros_rows  = cv::countNonZero(rows);
    Mat tmp1(nonzeros_rows, nonzeros_cols, CV_64FC1);
    for (int i = 0, j = 0; i < (int)rows.size(); i++)
    {
        if (rows[i])
        {
            tmp.row(i).copyTo(tmp1.row(j++));
        }
    }

    dst = tmp1.clone();
}

void cv::omnidir::internal::flags2idx(int flags, std::vector<int>& idx, int n)
{
2027
    idx = std::vector<int>(6*n+10,1);
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    int _flags = flags;
    if(_flags >= omnidir::CALIB_FIX_CENTER)
    {
        idx[6*n+3] = 0;
        idx[6*n+4] = 0;
        _flags -= omnidir::CALIB_FIX_CENTER;
    }
    if(_flags >= omnidir::CALIB_FIX_GAMMA)
    {
        idx[6*n] = 0;
        idx[6*n+1] = 0;
        _flags -= omnidir::CALIB_FIX_GAMMA;
    }
    if(_flags >= omnidir::CALIB_FIX_XI)
    {
        idx[6*n + 5] = 0;
        _flags -= omnidir::CALIB_FIX_XI;
    }
    if(_flags >= omnidir::CALIB_FIX_P2)
    {
        idx[6*n + 9] = 0;
        _flags -= omnidir::CALIB_FIX_P2;
    }
    if(_flags >= omnidir::CALIB_FIX_P1)
    {
        idx[6*n + 8] = 0;
        _flags -= omnidir::CALIB_FIX_P1;
    }
    if(_flags >= omnidir::CALIB_FIX_K2)
    {
        idx[6*n + 7] = 0;
        _flags -= omnidir::CALIB_FIX_K2;
    }
    if(_flags >= omnidir::CALIB_FIX_K1)
    {
        idx[6*n + 6] = 0;
        _flags -= omnidir::CALIB_FIX_K1;
    }
    if(_flags >= omnidir::CALIB_FIX_SKEW)
    {
        idx[6*n + 2] = 0;
    }
}

2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
void cv::omnidir::internal::flags2idxStereo(int flags, std::vector<int>& idx, int n)
{
    idx = std::vector<int>(6*(n+1)+20, 1);
    int _flags = flags;
    int offset1 = 6*(n+1);
    int offset2 = offset1 + 10;
    if(_flags >= omnidir::CALIB_FIX_CENTER)
    {
        idx[offset1+3] = 0;
        idx[offset1+4] = 0;
        idx[offset2+3] = 0;
        idx[offset2+4] = 0;
        _flags -= omnidir::CALIB_FIX_CENTER;
    }
    if(_flags >= omnidir::CALIB_FIX_GAMMA)
    {
        idx[offset1] = 0;
        idx[offset1+1] = 0;
        idx[offset2] = 0;
        idx[offset2+1] = 0;
        _flags -= omnidir::CALIB_FIX_GAMMA;
    }
    if(_flags >= omnidir::CALIB_FIX_XI)
    {
        idx[offset1 + 5] = 0;
        idx[offset2 + 5] = 0;
        _flags -= omnidir::CALIB_FIX_XI;
    }
    if(_flags >= omnidir::CALIB_FIX_P2)
    {
        idx[offset1 + 9] = 0;
        idx[offset2 + 9] = 0;
        _flags -= omnidir::CALIB_FIX_P2;
    }
    if(_flags >= omnidir::CALIB_FIX_P1)
    {
        idx[offset1 + 8] = 0;
        idx[offset2 + 8] = 0;
        _flags -= omnidir::CALIB_FIX_P1;
    }
    if(_flags >= omnidir::CALIB_FIX_K2)
    {
        idx[offset1 + 7] = 0;
        idx[offset2 + 7] = 0;
        _flags -= omnidir::CALIB_FIX_K2;
    }
    if(_flags >= omnidir::CALIB_FIX_K1)
    {
        idx[offset1 + 6] = 0;
        idx[offset2 + 6] = 0;
        _flags -= omnidir::CALIB_FIX_K1;
    }
    if(_flags >= omnidir::CALIB_FIX_SKEW)
    {
        idx[offset1 + 2] = 0;
        idx[offset2 + 2] = 0;
    }
}

// fill in zerso for fixed parameters
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
void cv::omnidir::internal::fillFixed(Mat&G, int flags, int n)
{
    Mat tmp = G.clone();
    std::vector<int> idx(6*n + 10, 1);
    flags2idx(flags, idx, n);
    G.release();
    G.create(6*n +10, 1, CV_64F);
    G = cv::Mat::zeros(6*n +10, 1, CV_64F);
    for (int i = 0,j=0; i < (int)idx.size(); i++)
    {
        if (idx[i])
        {
            G.at<double>(i) = tmp.at<double>(j++);
        }
    }
}

2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
void cv::omnidir::internal::fillFixedStereo(Mat& G, int flags, int n)
{
    Mat tmp = G.clone();
    std::vector<int> idx(6*(n+1)+20, 1);
    flags2idxStereo(flags, idx, n);
    G.release();
    G.create(6 * (n+1) + 20, 1, CV_64F);
    G = cv::Mat::zeros(6* (n + 1) + 20, 1, CV_64F);
    for (int i = 0,j=0; i < (int)idx.size(); i++)
    {
        if (idx[i])
        {
            G.at<double>(i) = tmp.at<double>(j++);
        }
    }
}
2165

2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
double cv::omnidir::internal::findMedian(const Mat& row)
{
    CV_Assert(!row.empty() && row.rows == 1 && row.type() == CV_64F);
    Mat tmp = row.clone();
    cv::sort(tmp, tmp, 0);
    if((int)tmp.total()%2 == 0)
        return tmp.at<double>((int)tmp.total() / 2);
    else
        return 0.5 * (tmp.at<double>((int)tmp.total() / 2) + tmp.at<double>((int)tmp.total()/2 - 1));
}
2176

2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227
cv::Vec3d cv::omnidir::internal::findMedian3(InputArray mat)
{
    CV_Assert(mat.depth() == CV_64F && mat.getMat().rows == 1);
    Mat M = Mat(mat.getMat().t()).reshape(1).t();
    return Vec3d(findMedian(M.row(0)), findMedian(M.row(1)), findMedian(M.row(2)));
}

void cv::omnidir::stereoRectify(InputArray R, InputArray T, OutputArray R1, OutputArray R2)
{
    CV_Assert((R.size() == Size(3,3) || R.total() == 3) && (R.depth() == CV_32F || R.depth() == CV_64F));
    CV_Assert(T.total() == 3  && (T.depth() == CV_32F || T.depth() == CV_64F));

    Mat _R, _T;
    if (R.size() == Size(3, 3))
    {
        R.getMat().convertTo(_R, CV_64F);
    }
    else if (R.total() == 3)
    {
        Rodrigues(R.getMat(), _R);
        _R.convertTo(_R, CV_64F);
    }

    T.getMat().reshape(1, 3).convertTo(_T, CV_64F);

    R1.create(3, 3, CV_64F);
    Mat _R1 = R1.getMat();
    R2.create(3, 3, CV_64F);
    Mat _R2 = R2.getMat();

    Mat R21 = _R.t();
    Mat T21 = -_R.t() * _T;

    Mat e1, e2, e3;
    e1 = T21.t() / norm(T21);
    e2 = Mat(Matx13d(T21.at<double>(1)*-1, T21.at<double>(0), 0.0));
    e2 = e2 / norm(e2);
    e3 = e1.cross(e2);
    e3 = e3 / norm(e3);
    e1.copyTo(_R1.row(0));
    e2.copyTo(_R1.row(1));
    e3.copyTo(_R1.row(2));
    _R2 = R21 * _R1;

}

void cv::omnidir::internal::getInterset(InputArray idx1, InputArray idx2, OutputArray inter1, OutputArray inter2,
    OutputArray inter_ori)
{
    Mat _idx1 = idx1.getMat();
    Mat _idx2 = idx2.getMat();
2228

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
    int n1 = (int)idx1.total();
    int n2 = (int)idx2.total();

    std::vector<int> _inter1, _inter2, _inter_ori;
    for (int i = 0; i < n1; ++i)
    {
        for (int j = 0; j < n2; ++j)
        {
            if(_idx1.at<int>(i) == _idx2.at<int>(j))
            {
                _inter1.push_back(i);
                _inter2.push_back(j);
                _inter_ori.push_back(_idx1.at<int>(i));
            }
        }
    }

    inter1.create(1, (int)_inter1.size(), CV_32S);
    inter2.create(1, (int)_inter2.size(), CV_32S);
    inter_ori.create(1, (int)_inter_ori.size(), CV_32S);

    for (int i = 0; i < (int)_inter1.size(); ++i)
    {
        inter1.getMat().at<int>(i) = _inter1[i];
    }
    for (int i = 0; i < (int)_inter2.size(); ++i)
    {
        inter2.getMat().at<int>(i) = _inter2[i];
    }
    for (int i = 0; i < (int)_inter_ori.size(); ++i)
    {
        inter_ori.getMat().at<int>(i) = _inter_ori[i];
    }
2262
}