Subversion Repositories seema-scanner

Rev

Rev 121 | Rev 141 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 jakw 1
#include "cvtools.h"
2
 
3
#ifdef _WIN32
4
#include <cstdint>
5
#endif
6
 
7
#include <stdio.h>
8
 
9
namespace cvtools{
10
 
139 jakw 11
// Convert an BGR 3-channel image back into a Bayered image
12
void cvtColorBGRToBayerBG(const cv::Mat &imBGR, cv::Mat &imBayerBG){
13
 
14
    imBayerBG.create(imBGR.size(), CV_8UC1);
15
 
16
 
17
    for(int r=0; r<imBGR.rows; r++){
18
        for(int c=0; c<imBGR.cols; c++){
19
 
20
            bool evenRow = r % 2;
21
            bool evenCol = c % 2;
22
 
23
            if(evenRow & evenCol)
24
                imBayerBG.at<uchar>(r,c) = imBGR.at<cv::Vec3b>(r,c)[0];
25
            else if(!evenRow & !evenCol)
26
                imBayerBG.at<uchar>(r,c) = imBGR.at<cv::Vec3b>(r,c)[2];
27
            else
28
                imBayerBG.at<uchar>(r,c) = imBGR.at<cv::Vec3b>(r,c)[1];
29
 
30
        }
31
 
32
    }
33
 
34
 
35
}
36
 
37
 
121 jakw 38
// Removes matches not satisfying the epipolar constraint.
119 jakw 39
// F is the fundamental matrix.
121 jakw 40
// Works like cv::correctMatches(), except it removes matches with an error distance greater than maxD.
41
void removeIncorrectMatches(const cv::Mat F, const std::vector<cv::Point2f> &q0, const std::vector<cv::Point2f> &q1, const float maxD,
42
                                std::vector<cv::Point2f> q0Correct, std::vector<cv::Point2f> q1Correct){
119 jakw 43
 
121 jakw 44
    int n0 = (int)q0.size(), n1 = (int)q1.size();
45
    q0Correct.reserve(n0);
46
    q1Correct.reserve(n1);
119 jakw 47
 
48
    // Point to line distance
49
//    for( int i = 0; i < n1; i++ ){
121 jakw 50
//        cv::Vec3f p0 = cv::Vec3f(q0[i].x, q0[i].y, 1.0);
51
//        // Epipolar line defined by p0
52
//        cv::Vec3f l = F*p0;
119 jakw 53
//        l /= sqrt(l(0)*l(0) + l(1)*l(1));
54
//        for( int j = 0; j < n2; j++ ){
121 jakw 55
//            cv::Vec3f p1 = cv::Vec3f(q1[i].x, q1[i].y, 1.0);
119 jakw 56
//            // Signed distance to line
121 jakw 57
//            float d = l.dot(p1);
58
//            if(d < maxD){
59
//                q0Correct.push_back(q0[i]);
60
//                q1Correct.push_back(q1[i]);
61
//            }
119 jakw 62
//        }
63
//    }
64
 
65
    // Symmetric epipolar distance
121 jakw 66
    std::vector<cv::Point3f> l0, l1;
67
    cv::computeCorrespondEpilines(q0, 1, F, l0);
68
    cv::computeCorrespondEpilines(q1, 2, F, l1);
119 jakw 69
 
121 jakw 70
    for(int i = 0; i < n0; i++){
71
        cv::Vec3f p0 = cv::Vec3f(q0[i].x, q0[i].y, 1.0);
72
        for(int j = 0; j < n1; j++){
73
            cv::Vec3f p1 = cv::Vec3f(q1[j].x, q1[j].y, 1.0);
74
            float d01 = l0[i].dot(p1);
75
            float d10 = l1[j].dot(p0);
76
            float d = d01*d01 + d10*d10;
77
            if(d < maxD){
78
                q0Correct.push_back(q0[i]);
79
                q1Correct.push_back(q1[i]);
80
            }
119 jakw 81
        }
82
    }
83
 
84
//    // Sampson Error (H&Z, p. 287) (expensive...)
121 jakw 85
//    std::vector<cv::Point3f> p0, p1;
86
//    cv::convertPointsToHomogeneous(q0, p0);
119 jakw 87
//    cv::convertPointsToHomogeneous(q1, p1);
121 jakw 88
//    cv::Mat Fp0Mat = cv::Mat(F)*cv::Mat(p0).reshape(1).t();
89
//    cv::Mat FTp1Mat = cv::Mat(F.t())*cv::Mat(p1).reshape(1).t();
119 jakw 90
//    for( int i = 0; i < n1; i++ ){
121 jakw 91
//        cv::Vec3f Fp0 = Fp0Mat.col(i);
119 jakw 92
//        for( int j = 0; j < n2; j++ ){
121 jakw 93
//            cv::Vec3f FTp1 = FTp1Mat.col(j);
94
//            cv::Matx<float,1,1> p1TFp0 = cv::Matx31f(p1[j]).t()*F*cv::Matx31f(p0[i]);
95
//            float d = p1TFp0(0)*p1TFp0(0) / (Fp0(0)*Fp0(0) + Fp0(1)*Fp0(1) + FTp1(0)*FTp1(0) + FTp1(1)*FTp1(1));
96
//            if(d < maxD){
97
//                q0Correct.push_back(q0[i]);
98
//                q1Correct.push_back(q1[i]);
99
//            }
119 jakw 100
//        }
101
//    }
102
 
121 jakw 103
    return;
119 jakw 104
}
105
 
49 jakw 106
// Lightly modified OpenCV function which accepts a line width argument
50 jakw 107
void drawChessboardCorners(cv::InputOutputArray _image, cv::Size patternSize, cv::InputArray _corners, bool patternWasFound, int line_width){
108
    cv::Mat corners = _corners.getMat();
49 jakw 109
    if( corners.empty() )
110
        return;
50 jakw 111
    cv::Mat image = _image.getMat(); CvMat c_image = _image.getMat();
49 jakw 112
    int nelems = corners.checkVector(2, CV_32F, true);
113
    CV_Assert(nelems >= 0);
114
    cvDrawChessboardCorners( &c_image, patternSize, (CvPoint2D32f*)corners.data,
115
                             nelems, patternWasFound, line_width);
116
}
117
 
120 jakw 118
void rshift(cv::Mat& I, unsigned int shift){
119
 
120
    int nRows = I.rows;
121
    int nCols = I.cols;
122
 
123
    if (I.isContinuous()){
124
        nCols *= nRows;
125
        nRows = 1;
126
    }
127
 
128
    int i,j;
129
    unsigned short* p;
130
    for( i = 0; i < nRows; ++i){
131
        p = I.ptr<unsigned short>(i);
132
        for ( j = 0; j < nCols; ++j){
133
            p[j] = p[j]>>shift;
134
        }
135
    }
136
}
137
 
50 jakw 138
void cvDrawChessboardCorners(CvArr* _image, CvSize pattern_size, CvPoint2D32f* corners, int count, int found, int line_width){
49 jakw 139
    const int shift = 0;
50 jakw 140
    const int radius = 12;
49 jakw 141
    const int r = radius*(1 << shift);
142
    int i;
143
    CvMat stub, *image;
144
    double scale = 1;
145
    int type, cn, line_type;
146
 
147
    image = cvGetMat( _image, &stub );
148
 
149
    type = CV_MAT_TYPE(image->type);
150
    cn = CV_MAT_CN(type);
151
    if( cn != 1 && cn != 3 && cn != 4 )
152
        CV_Error( CV_StsUnsupportedFormat, "Number of channels must be 1, 3 or 4" );
153
 
154
    switch( CV_MAT_DEPTH(image->type) )
155
    {
156
    case CV_8U:
157
        scale = 1;
158
        break;
159
    case CV_16U:
160
        scale = 256;
161
        break;
162
    case CV_32F:
163
        scale = 1./255;
164
        break;
165
    default:
166
        CV_Error( CV_StsUnsupportedFormat,
167
            "Only 8-bit, 16-bit or floating-point 32-bit images are supported" );
168
    }
169
 
170
    line_type = type == CV_8UC1 || type == CV_8UC3 ? CV_AA : 8;
171
 
172
    if( !found )
173
    {
174
        CvScalar color = {{0,0,255}};
175
        if( cn == 1 )
176
            color = cvScalarAll(200);
177
        color.val[0] *= scale;
178
        color.val[1] *= scale;
179
        color.val[2] *= scale;
180
        color.val[3] *= scale;
181
 
182
        for( i = 0; i < count; i++ )
183
        {
184
            CvPoint pt;
185
            pt.x = cvRound(corners[i].x*(1 << shift));
186
            pt.y = cvRound(corners[i].y*(1 << shift));
187
            cvLine( image, cvPoint( pt.x - r, pt.y - r ),
50 jakw 188
                    cvPoint( pt.x + r, pt.y + r ), color, line_width, line_type, shift );
49 jakw 189
            cvLine( image, cvPoint( pt.x - r, pt.y + r),
50 jakw 190
                    cvPoint( pt.x + r, pt.y - r), color, line_width, line_type, shift );
191
            cvCircle( image, pt, r+(1<<shift), color, line_width, line_type, shift );
49 jakw 192
        }
193
    }
194
    else
195
    {
196
        int x, y;
197
        CvPoint prev_pt = {0, 0};
198
        const int line_max = 7;
199
        static const CvScalar line_colors[line_max] =
200
        {
201
            {{0,0,255}},
202
            {{0,128,255}},
203
            {{0,200,200}},
204
            {{0,255,0}},
205
            {{200,200,0}},
206
            {{255,0,0}},
207
            {{255,0,255}}
208
        };
209
 
210
        for( y = 0, i = 0; y < pattern_size.height; y++ )
211
        {
212
            CvScalar color = line_colors[y % line_max];
213
            if( cn == 1 )
214
                color = cvScalarAll(200);
215
            color.val[0] *= scale;
216
            color.val[1] *= scale;
217
            color.val[2] *= scale;
218
            color.val[3] *= scale;
219
 
220
            for( x = 0; x < pattern_size.width; x++, i++ )
221
            {
222
                CvPoint pt;
223
                pt.x = cvRound(corners[i].x*(1 << shift));
224
                pt.y = cvRound(corners[i].y*(1 << shift));
225
 
226
                if( i != 0 )
227
                    cvLine( image, prev_pt, pt, color, 1, line_type, shift );
228
 
229
                cvLine( image, cvPoint(pt.x - r, pt.y - r),
50 jakw 230
                        cvPoint(pt.x + r, pt.y + r), color, line_width, line_type, shift );
49 jakw 231
                cvLine( image, cvPoint(pt.x - r, pt.y + r),
50 jakw 232
                        cvPoint(pt.x + r, pt.y - r), color, line_width, line_type, shift );
233
                cvCircle( image, pt, r+(1<<shift), color, line_width, line_type, shift );
49 jakw 234
                prev_pt = pt;
235
            }
236
        }
237
    }
238
}
239
 
74 jakw 240
// Returns the result of mod(mat(x,y), moduli) for each matrix element
241
cv::Mat modulo(const cv::Mat &mat, float n){
242
 
243
    cv::Mat ret(mat.rows, mat.cols, mat.type());
244
 
245
    for(int row=0; row<ret.rows; row++){
246
        for(int col=0; col<ret.cols; col++){
247
            float val = mat.at<float>(row, col);
248
            // note: std::fmod calculates the remainder, not arithmetic modulo
249
            ret.at<float>(row, col) = val - n * std::floor(val / n);
250
        }
251
    }
252
 
253
    return ret;
254
}
255
 
42 jakw 256
// Convert a 3xN matrix to a vector of Point3fs.
257
void matToPoints3f(const cv::Mat &mat, std::vector<cv::Point3f> &points){
258
 
259
    unsigned int nPoints = mat.cols;
260
    points.resize(nPoints);
261
 
262
    for(unsigned int i=0; i<nPoints; i++)
263
        points[i] = cv::Point3f(mat.at<float>(0, i), mat.at<float>(1, i), mat.at<float>(2, i));
264
}
265
 
266
// Convert a (Dim+1)xN matrix of homogenous points to a DimxN matrix of points in non-homogenous coordinates.
267
void convertMatFromHomogeneous(cv::Mat &src, cv::Mat &dst){
268
    unsigned int N = src.cols;
269
    unsigned int Dim = src.rows-1;
270
    dst.create(Dim, N, src.type());
271
    for(unsigned int i=0; i<N; i++){
272
        for(unsigned int j=0; j<Dim; j++)
273
            dst.at<float>(j,i) = src.at<float>(j,i)/src.at<float>(Dim,i);
274
    }
275
 
276
}
277
 
34 jakw 278
// Function to solve the hand-eye (or eye-in-hand) calibration problem.
279
// Finds [Omega | tau], to minimize ||[R_mark | t_mark][Omega | tau] - [Omega | tau][R | t]||^2
280
// Algorithm according to Tsai, Lenz, A new technique for fully autonomous and efficient 3d robotics hand-eye calibration
281
// DTU, 2014, Jakob Wilm
282
void handEyeCalibrationTsai(const std::vector<cv::Matx33f> R, const std::vector<cv::Vec3f> t, const std::vector<cv::Matx33f> R_mark, const std::vector<cv::Vec3f> t_mark, cv::Matx33f &Omega, cv::Vec3f &tau){
42 jakw 283
 
34 jakw 284
    int N = R.size();
285
    assert(N == R_mark.size());
286
    assert(N == t.size());
287
    assert(N == t_mark.size());
288
 
289
    // construct equations for rotation
290
    cv::Mat A(3*N, 3, CV_32F);
291
    cv::Mat b(3*N, 1, CV_32F);
292
    for(int i=0; i<N; i++){
293
        // angle axis representations
294
        cv::Vec3f rot;
295
        cv::Vec3f rot_mark;
296
        cv::Rodrigues(R[i], rot);
297
        cv::Rodrigues(R_mark[i], rot_mark);
298
 
299
        cv::Vec3f P = 2.0*sin(cv::norm(rot)/2.0)*cv::normalize(rot);
36 jakw 300
//std::cout << "P: " << std::endl << P << std::endl;
34 jakw 301
        cv::Vec3f P_mark = 2.0*sin(cv::norm(rot_mark)/2.0)*cv::normalize(rot_mark);
36 jakw 302
//std::cout << "P_mark: " << std::endl << P_mark << std::endl;
34 jakw 303
        cv::Vec3f sum = P+P_mark;
304
        cv::Mat crossProduct = (cv::Mat_<float>(3,3) << 0.0, -sum(2), sum(1), sum(2), 0.0, -sum(0), -sum(1), sum(0), 0.0);
36 jakw 305
//std::cout << "crossProduct: " << std::endl << crossProduct << std::endl;
34 jakw 306
        crossProduct.copyTo(A.rowRange(i*3, i*3+3));
307
 
308
        cv::Mat(P-P_mark).copyTo(b.rowRange(i*3, i*3+3));
309
    }
310
 
311
    // solve for rotation
36 jakw 312
    cv::Vec3f P_prime;
313
    cv::solve(A, b, P_prime, cv::DECOMP_SVD);
314
    cv::Vec3f P = 2.0*P_prime/(cv::sqrt(1.0 + cv::norm(P_prime)*cv::norm(P_prime)));
34 jakw 315
    float nP = cv::norm(P);
316
    cv::Mat crossProduct = (cv::Mat_<float>(3,3) << 0.0, -P(2), P(1), P(2), 0.0, -P(0), -P(1), P(0), 0.0);
317
    cv::Mat OmegaMat = (1.0-nP*nP/2.0)*cv::Mat::eye(3,3,CV_32F) + 0.5*(cv::Mat(P)*cv::Mat(P).t() + cv::sqrt(4.0 - nP*nP)*crossProduct);
318
    Omega = cv::Matx33f(OmegaMat);
319
 
320
    // construct equations for translation
321
    A.setTo(0.0);
322
    b.setTo(0.0);
323
    for(int i=0; i<N; i++){
324
 
36 jakw 325
        cv::Mat diff = cv::Mat(R_mark[i]) - cv::Mat::eye(3, 3, CV_32F);
34 jakw 326
        diff.copyTo(A.rowRange(i*3, i*3+3));
327
 
36 jakw 328
        cv::Mat diff_mark = cv::Mat(Omega*t[i] - t_mark[i]);
34 jakw 329
        diff_mark.copyTo(b.rowRange(i*3, i*3+3));
330
    }
331
 
332
    // solve for translation
36 jakw 333
    cv::solve(A, b, tau, cv::DECOMP_SVD);
81 jakw 334
 
335
    cv::Mat err_tau = b - (A*cv::Mat(tau));
336
    std::cout << err_tau << std::endl;
34 jakw 337
}
338
 
82 jakw 339
// Function to solve for the rotation axis from sets of 3D point coordinates of flat pattern feature points
340
// Algorithm according to Chen et al., Rotation axis calibration of a turntable using constrained global optimization, Optik 2014
341
// DTU, 2014, Jakob Wilm
342
void rotationAxisCalibration(const std::vector< std::vector<cv::Point3f> > Qcam, const std::vector<cv::Point3f> Qobj, cv::Vec3f &axis, cv::Vec3f &point){
343
 
344
    // number of frames (points on each arch)
345
    int l = Qcam.size();
346
 
347
    // number of points in each frame
348
    int mn = Qobj.size();
349
 
350
    assert(mn == Qcam[0].size());
351
 
352
    // construct matrix for axis determination
353
    cv::Mat M(6, 6, CV_32F, cv::Scalar(0));
354
 
355
    for(int k=0; k<l; k++){
356
        for(int idx=0; idx<mn; idx++){
357
 
83 jakw 358
//            float i = Qobj[idx].x+4;
359
//            float j = Qobj[idx].y+4;
360
            float i = Qobj[idx].x;
361
            float j = Qobj[idx].y;
82 jakw 362
 
363
            float x = Qcam[k][idx].x;
364
            float y = Qcam[k][idx].y;
365
            float z = Qcam[k][idx].z;
366
 
367
            M += (cv::Mat_<float>(6,6) << x*x, x*y, x*z, x, i*x, j*x,
368
                                            0, y*y, y*z, y, i*y, j*y,
369
                                            0,   0, z*z, z, i*z, j*z,
370
                                            0,   0,   0, 1,   i,   j,
371
                                            0,   0,   0, 0, i*i, i*j,
372
                                            0,   0,   0, 0,   0, j*j);
373
 
374
        }
375
    }
91 jakw 376
 
82 jakw 377
    cv::completeSymm(M, false);
91 jakw 378
 
82 jakw 379
    // solve for axis
380
    std::vector<float> lambda;
381
    cv::Mat u;
382
    cv::eigen(M, lambda, u);
383
 
384
    float minLambda = abs(lambda[0]);
385
    int idx = 0;
386
    for(int i=1; i<lambda.size(); i++){
387
        if(abs(lambda[i]) < minLambda){
388
            minLambda = lambda[i];
389
            idx = i;
390
        }
391
    }
392
 
393
    axis = u.row(idx).colRange(0, 3);
91 jakw 394
    axis = cv::normalize(axis);
82 jakw 395
 
83 jakw 396
    float nx = u.at<float>(idx, 0);
397
    float ny = u.at<float>(idx, 1);
398
    float nz = u.at<float>(idx, 2);
399
    float d  = u.at<float>(idx, 3);
400
    float dh = u.at<float>(idx, 4);
401
    float dv = u.at<float>(idx, 5);
82 jakw 402
 
90 jakw 403
//    // Paper version: c is initially eliminated
404
//    cv::Mat A(l*mn, mn+2, CV_32F, cv::Scalar(0.0));
405
//    cv::Mat bb(l*mn, 1, CV_32F);
406
 
407
//    for(int k=0; k<l; k++){
408
//        for(int idx=0; idx<mn; idx++){
409
 
410
//            float i = Qobj[idx].x;
411
//            float j = Qobj[idx].y;
412
 
413
//            float x = Qcam[k][idx].x;
414
//            float y = Qcam[k][idx].y;
415
//            float z = Qcam[k][idx].z;
416
 
417
//            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
418
 
419
//            int row = k*mn+idx;
420
//            A.at<float>(row, 0) = 2*x - (2*z*nx)/nz;
421
//            A.at<float>(row, 1) = 2*y - (2*z*ny)/nz;
422
//            A.at<float>(row, idx+2) = 1.0;
423
 
424
//            bb.at<float>(row, 0) = f + (2*z*d)/nz;
425
//        }
426
//    }
427
 
428
//    // solve for point
429
//    cv::Mat abe;
430
//    cv::solve(A, bb, abe, cv::DECOMP_SVD);
431
 
432
//    float a = abe.at<float>(0, 0);
433
//    float b = abe.at<float>(1, 0);
434
//    float c = -(nx*a+ny*b+d)/nz;
435
 
436
    // Our version: solve simultanously for a,b,c
437
    cv::Mat A(l*mn, mn+3, CV_32F, cv::Scalar(0.0));
83 jakw 438
    cv::Mat bb(l*mn, 1, CV_32F);
82 jakw 439
 
440
    for(int k=0; k<l; k++){
441
        for(int idx=0; idx<mn; idx++){
442
 
443
            float i = Qobj[idx].x;
444
            float j = Qobj[idx].y;
445
 
446
            float x = Qcam[k][idx].x;
447
            float y = Qcam[k][idx].y;
448
            float z = Qcam[k][idx].z;
449
 
450
            float f = x*x + y*y + z*z + (2*x*nx + 2*y*ny + 2*z*nz)*(i*dh + j*dv);
451
 
452
            int row = k*mn+idx;
90 jakw 453
            A.at<float>(row, 0) = 2*x;
454
            A.at<float>(row, 1) = 2*y;
455
            A.at<float>(row, 2) = 2*z;
456
            A.at<float>(row, idx+3) = 1.0;
82 jakw 457
 
90 jakw 458
            bb.at<float>(row, 0) = f;
82 jakw 459
        }
460
    }
461
 
462
    // solve for point
463
    cv::Mat abe;
83 jakw 464
    cv::solve(A, bb, abe, cv::DECOMP_SVD);
82 jakw 465
 
83 jakw 466
    float a = abe.at<float>(0, 0);
467
    float b = abe.at<float>(1, 0);
90 jakw 468
    float c = abe.at<float>(2, 0);
82 jakw 469
 
83 jakw 470
    point[0] = a;
471
    point[1] = b;
472
    point[2] = c;
473
 
82 jakw 474
}
475
 
34 jakw 476
// Function to fit two sets of corresponding pose data.
477
// Finds [Omega | tau], to minimize ||[R_mark | t_mark] - [Omega | tau][R | t]||^2
31 jakw 478
// Algorithm and notation according to Mili Shah, Comparing two sets of corresponding six degree of freedom data, CVIU 2011.
479
// DTU, 2013, Oline V. Olesen, Jakob Wilm
480
void fitSixDofData(const std::vector<cv::Matx33f> R, const std::vector<cv::Vec3f> t, const std::vector<cv::Matx33f> R_mark, const std::vector<cv::Vec3f> t_mark, cv::Matx33f &Omega, cv::Vec3f &tau){
34 jakw 481
 
31 jakw 482
    int N = R.size();
483
    assert(N == R_mark.size());
484
    assert(N == t.size());
485
    assert(N == t_mark.size());
486
 
487
    // Mean translations
488
    cv::Vec3f t_mean;
489
    cv::Vec3f t_mark_mean;
490
    for(int i=0; i<N; i++){
491
        t_mean += 1.0/N * t[i];
492
        t_mark_mean += 1.0/N * t_mark[i];
493
    }
494
 
495
    // Data with mean adjusted translations
496
    cv::Mat X_bar(3, 4*N, CV_32F);
497
    cv::Mat X_mark_bar(3, 4*N, CV_32F);
498
    for(int i=0; i<N; i++){
33 jakw 499
        cv::Mat(R[i]).copyTo(X_bar.colRange(i*4,i*4+3));
500
        cv::Mat(t[i] - t_mean).copyTo(X_bar.col(i*4+3));
501
        cv::Mat(R_mark[i]).copyTo(X_mark_bar.colRange(i*4,i*4+3));
502
        cv::Mat(t_mark[i] - t_mark_mean).copyTo(X_mark_bar.col(i*4+3));
31 jakw 503
    }
33 jakw 504
    //std::cout << X_bar << std::endl;
31 jakw 505
    // SVD
33 jakw 506
    cv::Mat W, U, VT;
31 jakw 507
    cv::SVDecomp(X_bar*X_mark_bar.t(), W, U, VT);
508
 
509
    cv::Matx33f D = cv::Matx33f::eye();
510
    if(cv::determinant(VT*U) < 0)
511
        D(3,3) = -1;
512
 
513
    // Best rotation
33 jakw 514
    Omega = cv::Matx33f(cv::Mat(VT.t()))*D*cv::Matx33f(cv::Mat(U.t()));
31 jakw 515
 
516
    // Best translation
517
    tau = t_mark_mean - Omega*t_mean;
518
 
519
}
520
 
1 jakw 521
// Forward distortion of points. The inverse of the undistortion in cv::initUndistortRectifyMap().
522
// Inspired by Pascal Thomet, http://code.opencv.org/issues/1387#note-11
523
// Convention for distortion parameters: http://www.vision.caltech.edu/bouguetj/calib_doc/htmls/parameters.html
524
void initDistortMap(const cv::Matx33f cameraMatrix, const cv::Vec<float, 5> distCoeffs, const cv::Size size, cv::Mat &map1, cv::Mat &map2){
525
 
526
    float fx = cameraMatrix(0,0);
527
    float fy = cameraMatrix(1,1);
528
    float ux = cameraMatrix(0,2);
529
    float uy = cameraMatrix(1,2);
530
 
531
    float k1 = distCoeffs[0];
532
    float k2 = distCoeffs[1];
533
    float p1 = distCoeffs[2];
534
    float p2 = distCoeffs[3];
535
    float k3 = distCoeffs[4];
536
 
537
    map1.create(size, CV_32F);
538
    map2.create(size, CV_32F);
539
 
540
    for(int col = 0; col < size.width; col++){
541
        for(int row = 0; row < size.height; row++){
542
 
543
            // move origo to principal point and convert using focal length
544
            float x = (col-ux)/fx;
545
            float y = (row-uy)/fy;
546
 
547
            float xCorrected, yCorrected;
548
 
549
            //Step 1 : correct distortion
550
            float r2 = x*x + y*y;
551
            //radial
552
            xCorrected = x * (1. + k1*r2 + k2*r2*r2 + k3*r2*r2*r2);
553
            yCorrected = y * (1. + k1*r2 + k2*r2*r2 + k3*r2*r2*r2);
554
            //tangential
555
            xCorrected = xCorrected + (2.*p1*x*y + p2*(r2+2.*x*x));
556
            yCorrected = yCorrected + (p1*(r2+2.*y*y) + 2.*p2*x*y);
557
 
558
            //convert back to pixel coordinates
559
            float col_displaced = xCorrected * fx + ux;
560
            float row_displaced = yCorrected * fy + uy;
561
 
562
            // correct the vector in the opposite direction
563
            map1.at<float>(row,col) = col+(col-col_displaced);
564
            map2.at<float>(row,col) = row +(row-row_displaced);
565
        }
566
    }
567
}
568
 
569
// Downsample a texture which was created in virtual column/row space for a diamond pixel array projector
570
cv::Mat diamondDownsample(cv::Mat &pattern){
571
 
572
    cv::Mat pattern_diamond(pattern.rows,pattern.cols/2,CV_8UC3);
573
 
574
    for(unsigned int col = 0; col < pattern_diamond.cols; col++){
575
        for(unsigned int row = 0; row < pattern_diamond.rows; row++){
576
 
577
            pattern_diamond.at<cv::Vec3b>(row,col)=pattern.at<cv::Vec3b>(row,col*2+row%2);
578
        }
579
    }
580
 
581
    return pattern_diamond;
582
 
583
}
584
 
585
 
586
void mouseCallback(int evt, int x, int y, int flags, void* param){
587
    cv::Mat *im = (cv::Mat*) param;
588
    if (evt == CV_EVENT_LBUTTONDOWN) {
589
        if(im->type() == CV_8UC3){
590
            printf("%d %d: %d, %d, %d\n",
591
                   x, y,
592
                   (int)(*im).at<cv::Vec3b>(y, x)[0],
593
                    (int)(*im).at<cv::Vec3b>(y, x)[1],
594
                    (int)(*im).at<cv::Vec3b>(y, x)[2]);
595
        } else if (im->type() == CV_32F) {
596
            printf("%d %d: %f\n",
597
                   x, y,
598
                   im->at<float>(y, x));
599
        }
600
    }
601
}
602
 
603
void imshow(const char *windowName, cv::Mat im, unsigned int x, unsigned int y){
604
 
605
    // Imshow
606
    if(!cvGetWindowHandle(windowName)){
607
        int windowFlags = CV_GUI_EXPANDED | CV_WINDOW_KEEPRATIO;
608
        cv::namedWindow(windowName, windowFlags);
609
        cv::moveWindow(windowName, x, y);
610
    }
611
    cv::imshow(windowName, im);
612
}
613
 
614
void imagesc(const char *windowName, cv::Mat im){
615
 
616
    // Imshow with scaled image
617
 
618
 
619
}
620
 
621
cv::Mat histimage(cv::Mat histogram){
622
 
623
    cv::Mat histImage(512, 640, CV_8UC3, cv::Scalar(0));
624
 
625
    // Normalize the result to [ 2, histImage.rows-2 ]
626
    cv::normalize(histogram, histogram, 2, histImage.rows-2, cv::NORM_MINMAX, -1, cv::Mat());
627
 
628
    float bin_w = (float)histImage.cols/(float)histogram.rows;
629
 
630
    // Draw main histogram
631
    for(int i = 1; i < histogram.rows-10; i++){
632
        cv::line(histImage, cv::Point( bin_w*(i-1), histImage.rows - cvRound(histogram.at<float>(i-1)) ),
633
                 cv::Point( bin_w*(i), histImage.rows - cvRound(histogram.at<float>(i)) ),
634
                 cv::Scalar(255, 255, 255), 2, 4);
635
    }
636
 
637
    // Draw red max
638
    for(int i = histogram.rows-10; i < histogram.rows; i++){
639
        cv::line(histImage, cv::Point( bin_w*(i-1), histImage.rows - cvRound(histogram.at<float>(i-1)) ),
640
                 cv::Point( bin_w*(i), histImage.rows - cvRound(histogram.at<float>(i)) ),
641
                 cv::Scalar(0, 0, 255), 2, 4);
642
    }
643
 
644
    return histImage;
645
}
646
 
647
void hist(const char *windowName, cv::Mat histogram, unsigned int x, unsigned int y){
648
 
649
    // Display
650
    imshow(windowName, histimage(histogram), x, y);
651
    cv::Point(1,2);
652
}
653
 
654
 
655
void writeMat(cv::Mat const& mat, const char* filename, const char* varName, bool bgr2rgb){
656
    /*!
657
         *  \author Philip G. Lee <rocketman768@gmail.com>
658
         *  Write \b mat into \b filename
659
         *  in uncompressed .mat format (Level 5 MATLAB) for Matlab.
660
         *  The variable name in matlab will be \b varName. If
661
         *  \b bgr2rgb is true and there are 3 channels, swaps 1st and 3rd
662
         *  channels in the output. This is needed because OpenCV matrices
663
         *  are bgr, while Matlab is rgb. This has been tested to work with
664
         *  3-channel single-precision floating point matrices, and I hope
665
         *  it works on other types/channels, but not exactly sure.
666
         *  Documentation at <http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf>
667
         */
668
    int textLen = 116;
669
    char* text;
670
    int subsysOffsetLen = 8;
671
    char* subsysOffset;
672
    int verLen = 2;
673
    char* ver;
674
    char flags;
675
    int bytes;
676
    int padBytes;
677
    int bytesPerElement;
678
    int i,j,k,k2;
679
    bool doBgrSwap;
680
    char mxClass;
681
    int32_t miClass;
682
    uchar const* rowPtr;
683
    uint32_t tmp32;
684
    float tmp;
685
    FILE* fp;
686
 
687
    // Matlab constants.
688
    const uint16_t MI = 0x4d49; // Contains "MI" in ascii.
689
    const int32_t miINT8 = 1;
690
    const int32_t miUINT8 = 2;
691
    const int32_t miINT16 = 3;
692
    const int32_t miUINT16 = 4;
693
    const int32_t miINT32 = 5;
694
    const int32_t miUINT32 = 6;
695
    const int32_t miSINGLE = 7;
696
    const int32_t miDOUBLE = 9;
697
    const int32_t miMATRIX = 14;
698
    const char mxDOUBLE_CLASS = 6;
699
    const char mxSINGLE_CLASS = 7;
700
    const char mxINT8_CLASS = 8;
701
    const char mxUINT8_CLASS = 9;
702
    const char mxINT16_CLASS = 10;
703
    const char mxUINT16_CLASS = 11;
704
    const char mxINT32_CLASS = 12;
705
    const char mxUINT32_CLASS = 13;
706
    const uint64_t zero = 0; // Used for padding.
707
 
708
    fp = fopen( filename, "wb" );
709
 
710
    if( fp == 0 )
711
        return;
712
 
713
    const int rows = mat.rows;
714
    const int cols = mat.cols;
715
    const int chans = mat.channels();
716
 
717
    doBgrSwap = (chans==3) && bgr2rgb;
718
 
719
    // I hope this mapping is right :-/
720
    switch( mat.depth() ){
721
    case CV_8U:
722
        mxClass = mxUINT8_CLASS;
723
        miClass = miUINT8;
724
        bytesPerElement = 1;
725
        break;
726
    case CV_8S:
727
        mxClass = mxINT8_CLASS;
728
        miClass = miINT8;
729
        bytesPerElement = 1;
730
        break;
731
    case CV_16U:
732
        mxClass = mxUINT16_CLASS;
733
        miClass = miUINT16;
734
        bytesPerElement = 2;
735
        break;
736
    case CV_16S:
737
        mxClass = mxINT16_CLASS;
738
        miClass = miINT16;
739
        bytesPerElement = 2;
740
        break;
741
    case CV_32S:
742
        mxClass = mxINT32_CLASS;
743
        miClass = miINT32;
744
        bytesPerElement = 4;
745
        break;
746
    case CV_32F:
747
        mxClass = mxSINGLE_CLASS;
748
        miClass = miSINGLE;
749
        bytesPerElement = 4;
750
        break;
751
    case CV_64F:
752
        mxClass = mxDOUBLE_CLASS;
753
        miClass = miDOUBLE;
754
        bytesPerElement = 8;
755
        break;
756
    default:
757
        return;
758
    }
759
 
760
    //==================Mat-file header (128 bytes, page 1-5)==================
761
    text = new char[textLen]; // Human-readable text.
762
    memset( text, ' ', textLen );
763
    text[textLen-1] = '\0';
764
    const char* t = "MATLAB 5.0 MAT-file, Platform: PCWIN";
765
    memcpy( text, t, strlen(t) );
766
 
767
    subsysOffset = new char[subsysOffsetLen]; // Zeros for us.
768
    memset( subsysOffset, 0x00, subsysOffsetLen );
769
    ver = new char[verLen];
770
    ver[0] = 0x00;
771
    ver[1] = 0x01;
772
 
773
    fwrite( text, 1, textLen, fp );
774
    fwrite( subsysOffset, 1, subsysOffsetLen, fp );
775
    fwrite( ver, 1, verLen, fp );
776
    // Endian indicator. MI will show up as "MI" on big-endian
777
    // systems and "IM" on little-endian systems.
778
    fwrite( &MI, 2, 1, fp );
779
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
780
 
781
    //===================Data element tag (8 bytes, page 1-8)==================
782
    bytes = 16 + 24 + (8 + strlen(varName) + (8-(strlen(varName)%8))%8)
783
            + (8 + rows*cols*chans*bytesPerElement);
784
    fwrite( &miMATRIX, 4, 1, fp ); // Data type.
785
    fwrite( &bytes, 4, 1, fp); // Data size in bytes.
786
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
787
 
788
    //====================Array flags (16 bytes, page 1-15)====================
789
    bytes = 8;
790
    fwrite( &miUINT32, 4, 1, fp );
791
    fwrite( &bytes, 4, 1, fp );
792
    flags = 0x00; // Complex, logical, and global flags all off.
793
 
794
    tmp32 = 0;
795
    tmp32 = (flags << 8 ) | (mxClass);
796
    fwrite( &tmp32, 4, 1, fp );
797
 
798
    fwrite( &zero, 4, 1, fp ); // Padding to 64-bit boundary.
799
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
800
 
801
    //===============Dimensions subelement (24 bytes, page 1-17)===============
802
    bytes = 12;
803
    fwrite( &miINT32, 4, 1, fp );
804
    fwrite( &bytes, 4, 1, fp );
805
 
806
    fwrite( &rows, 4, 1, fp );
807
    fwrite( &cols, 4, 1, fp );
808
    fwrite( &chans, 4, 1, fp );
809
    fwrite( &zero, 4, 1, fp ); // Padding to 64-bit boundary.
810
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
811
 
812
    //==Array name (8 + strlen(varName) + (8-(strlen(varName)%8))%8 bytes, page 1-17)==
813
    bytes = strlen(varName);
814
 
815
    fwrite( &miINT8, 4, 1, fp );
816
    fwrite( &bytes, 4, 1, fp );
817
    fwrite( varName, 1, bytes, fp );
818
 
819
    // Pad to nearest 64-bit boundary.
820
    padBytes = (8-(bytes%8))%8;
821
    fwrite( &zero, 1, padBytes, fp );
822
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
823
 
824
    //====Matrix data (rows*cols*chans*bytesPerElement+8 bytes, page 1-20)=====
825
    bytes = rows*cols*chans*bytesPerElement;
826
    fwrite( &miClass, 4, 1, fp );
827
    fwrite( &bytes, 4, 1, fp );
828
 
829
    for( k = 0; k < chans; ++k )
830
    {
831
        if( doBgrSwap )
832
        {
833
            k2 = (k==0)? 2 : ((k==2)? 0 : 1);
834
        }
835
        else
836
            k2 = k;
837
 
838
        for( j = 0; j < cols; ++j )
839
        {
840
            for( i = 0; i < rows; ++i )
841
            {
842
                rowPtr = mat.data + mat.step*i;
843
                fwrite( rowPtr + (chans*j + k2)*bytesPerElement, bytesPerElement, 1, fp );
844
            }
845
        }
846
    }
847
 
848
    // Pad to 64-bit boundary.
849
    padBytes = (8-(bytes%8))%8;
850
    fwrite( &zero, 1, padBytes, fp );
851
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
852
 
853
    fclose(fp);
854
    delete[] text;
855
    delete[] subsysOffset;
856
    delete[] ver;
857
}
858
 
859
 
860
 
861
 
862
 
863
}