Subversion Repositories seema-scanner

Rev

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