Subversion Repositories seema-scanner

Rev

Rev 36 | Rev 49 | 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
 
42 jakw 11
// Convert a 3xN matrix to a vector of Point3fs.
12
void matToPoints3f(const cv::Mat &mat, std::vector<cv::Point3f> &points){
13
 
14
    unsigned int nPoints = mat.cols;
15
    points.resize(nPoints);
16
 
17
    for(unsigned int i=0; i<nPoints; i++)
18
        points[i] = cv::Point3f(mat.at<float>(0, i), mat.at<float>(1, i), mat.at<float>(2, i));
19
}
20
 
21
// Convert a (Dim+1)xN matrix of homogenous points to a DimxN matrix of points in non-homogenous coordinates.
22
void convertMatFromHomogeneous(cv::Mat &src, cv::Mat &dst){
23
    unsigned int N = src.cols;
24
    unsigned int Dim = src.rows-1;
25
    dst.create(Dim, N, src.type());
26
    for(unsigned int i=0; i<N; i++){
27
        for(unsigned int j=0; j<Dim; j++)
28
            dst.at<float>(j,i) = src.at<float>(j,i)/src.at<float>(Dim,i);
29
    }
30
 
31
}
32
 
34 jakw 33
// Function to solve the hand-eye (or eye-in-hand) calibration problem.
34
// Finds [Omega | tau], to minimize ||[R_mark | t_mark][Omega | tau] - [Omega | tau][R | t]||^2
35
// Algorithm according to Tsai, Lenz, A new technique for fully autonomous and efficient 3d robotics hand-eye calibration
36
// DTU, 2014, Jakob Wilm
37
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 38
 
34 jakw 39
    int N = R.size();
40
    assert(N == R_mark.size());
41
    assert(N == t.size());
42
    assert(N == t_mark.size());
43
 
44
    // construct equations for rotation
45
    cv::Mat A(3*N, 3, CV_32F);
46
    cv::Mat b(3*N, 1, CV_32F);
47
    for(int i=0; i<N; i++){
48
        // angle axis representations
49
        cv::Vec3f rot;
50
        cv::Vec3f rot_mark;
51
        cv::Rodrigues(R[i], rot);
52
        cv::Rodrigues(R_mark[i], rot_mark);
53
 
54
        cv::Vec3f P = 2.0*sin(cv::norm(rot)/2.0)*cv::normalize(rot);
36 jakw 55
//std::cout << "P: " << std::endl << P << std::endl;
34 jakw 56
        cv::Vec3f P_mark = 2.0*sin(cv::norm(rot_mark)/2.0)*cv::normalize(rot_mark);
36 jakw 57
//std::cout << "P_mark: " << std::endl << P_mark << std::endl;
34 jakw 58
        cv::Vec3f sum = P+P_mark;
59
        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 60
//std::cout << "crossProduct: " << std::endl << crossProduct << std::endl;
34 jakw 61
        crossProduct.copyTo(A.rowRange(i*3, i*3+3));
62
 
63
        cv::Mat(P-P_mark).copyTo(b.rowRange(i*3, i*3+3));
64
    }
65
 
66
    // solve for rotation
36 jakw 67
    cv::Vec3f P_prime;
68
    cv::solve(A, b, P_prime, cv::DECOMP_SVD);
69
    cv::Vec3f P = 2.0*P_prime/(cv::sqrt(1.0 + cv::norm(P_prime)*cv::norm(P_prime)));
34 jakw 70
    float nP = cv::norm(P);
71
    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);
72
    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);
73
    Omega = cv::Matx33f(OmegaMat);
74
 
75
    // construct equations for translation
76
    A.setTo(0.0);
77
    b.setTo(0.0);
78
    for(int i=0; i<N; i++){
79
 
36 jakw 80
        cv::Mat diff = cv::Mat(R_mark[i]) - cv::Mat::eye(3, 3, CV_32F);
34 jakw 81
        diff.copyTo(A.rowRange(i*3, i*3+3));
82
 
36 jakw 83
        cv::Mat diff_mark = cv::Mat(Omega*t[i] - t_mark[i]);
34 jakw 84
        diff_mark.copyTo(b.rowRange(i*3, i*3+3));
85
    }
86
 
87
    // solve for translation
36 jakw 88
    cv::solve(A, b, tau, cv::DECOMP_SVD);
34 jakw 89
}
90
 
91
// Function to fit two sets of corresponding pose data.
92
// Finds [Omega | tau], to minimize ||[R_mark | t_mark] - [Omega | tau][R | t]||^2
31 jakw 93
// Algorithm and notation according to Mili Shah, Comparing two sets of corresponding six degree of freedom data, CVIU 2011.
94
// DTU, 2013, Oline V. Olesen, Jakob Wilm
95
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 96
 
31 jakw 97
    int N = R.size();
98
    assert(N == R_mark.size());
99
    assert(N == t.size());
100
    assert(N == t_mark.size());
101
 
102
    // Mean translations
103
    cv::Vec3f t_mean;
104
    cv::Vec3f t_mark_mean;
105
    for(int i=0; i<N; i++){
106
        t_mean += 1.0/N * t[i];
107
        t_mark_mean += 1.0/N * t_mark[i];
108
    }
109
 
110
    // Data with mean adjusted translations
111
    cv::Mat X_bar(3, 4*N, CV_32F);
112
    cv::Mat X_mark_bar(3, 4*N, CV_32F);
113
    for(int i=0; i<N; i++){
33 jakw 114
        cv::Mat(R[i]).copyTo(X_bar.colRange(i*4,i*4+3));
115
        cv::Mat(t[i] - t_mean).copyTo(X_bar.col(i*4+3));
116
        cv::Mat(R_mark[i]).copyTo(X_mark_bar.colRange(i*4,i*4+3));
117
        cv::Mat(t_mark[i] - t_mark_mean).copyTo(X_mark_bar.col(i*4+3));
31 jakw 118
    }
33 jakw 119
    //std::cout << X_bar << std::endl;
31 jakw 120
    // SVD
33 jakw 121
    cv::Mat W, U, VT;
31 jakw 122
    cv::SVDecomp(X_bar*X_mark_bar.t(), W, U, VT);
123
 
124
    cv::Matx33f D = cv::Matx33f::eye();
125
    if(cv::determinant(VT*U) < 0)
126
        D(3,3) = -1;
127
 
128
    // Best rotation
33 jakw 129
    Omega = cv::Matx33f(cv::Mat(VT.t()))*D*cv::Matx33f(cv::Mat(U.t()));
31 jakw 130
 
131
    // Best translation
132
    tau = t_mark_mean - Omega*t_mean;
133
 
134
}
135
 
1 jakw 136
// Forward distortion of points. The inverse of the undistortion in cv::initUndistortRectifyMap().
137
// Inspired by Pascal Thomet, http://code.opencv.org/issues/1387#note-11
138
// Convention for distortion parameters: http://www.vision.caltech.edu/bouguetj/calib_doc/htmls/parameters.html
139
void initDistortMap(const cv::Matx33f cameraMatrix, const cv::Vec<float, 5> distCoeffs, const cv::Size size, cv::Mat &map1, cv::Mat &map2){
140
 
141
    float fx = cameraMatrix(0,0);
142
    float fy = cameraMatrix(1,1);
143
    float ux = cameraMatrix(0,2);
144
    float uy = cameraMatrix(1,2);
145
 
146
    float k1 = distCoeffs[0];
147
    float k2 = distCoeffs[1];
148
    float p1 = distCoeffs[2];
149
    float p2 = distCoeffs[3];
150
    float k3 = distCoeffs[4];
151
 
152
    map1.create(size, CV_32F);
153
    map2.create(size, CV_32F);
154
 
155
    for(int col = 0; col < size.width; col++){
156
        for(int row = 0; row < size.height; row++){
157
 
158
            // move origo to principal point and convert using focal length
159
            float x = (col-ux)/fx;
160
            float y = (row-uy)/fy;
161
 
162
            float xCorrected, yCorrected;
163
 
164
            //Step 1 : correct distortion
165
            float r2 = x*x + y*y;
166
            //radial
167
            xCorrected = x * (1. + k1*r2 + k2*r2*r2 + k3*r2*r2*r2);
168
            yCorrected = y * (1. + k1*r2 + k2*r2*r2 + k3*r2*r2*r2);
169
            //tangential
170
            xCorrected = xCorrected + (2.*p1*x*y + p2*(r2+2.*x*x));
171
            yCorrected = yCorrected + (p1*(r2+2.*y*y) + 2.*p2*x*y);
172
 
173
            //convert back to pixel coordinates
174
            float col_displaced = xCorrected * fx + ux;
175
            float row_displaced = yCorrected * fy + uy;
176
 
177
            // correct the vector in the opposite direction
178
            map1.at<float>(row,col) = col+(col-col_displaced);
179
            map2.at<float>(row,col) = row +(row-row_displaced);
180
        }
181
    }
182
}
183
 
184
// Downsample a texture which was created in virtual column/row space for a diamond pixel array projector
185
cv::Mat diamondDownsample(cv::Mat &pattern){
186
 
187
    cv::Mat pattern_diamond(pattern.rows,pattern.cols/2,CV_8UC3);
188
 
189
    for(unsigned int col = 0; col < pattern_diamond.cols; col++){
190
        for(unsigned int row = 0; row < pattern_diamond.rows; row++){
191
 
192
            pattern_diamond.at<cv::Vec3b>(row,col)=pattern.at<cv::Vec3b>(row,col*2+row%2);
193
        }
194
    }
195
 
196
    return pattern_diamond;
197
 
198
}
199
 
200
 
201
void mouseCallback(int evt, int x, int y, int flags, void* param){
202
    cv::Mat *im = (cv::Mat*) param;
203
    if (evt == CV_EVENT_LBUTTONDOWN) {
204
        if(im->type() == CV_8UC3){
205
            printf("%d %d: %d, %d, %d\n",
206
                   x, y,
207
                   (int)(*im).at<cv::Vec3b>(y, x)[0],
208
                    (int)(*im).at<cv::Vec3b>(y, x)[1],
209
                    (int)(*im).at<cv::Vec3b>(y, x)[2]);
210
        } else if (im->type() == CV_32F) {
211
            printf("%d %d: %f\n",
212
                   x, y,
213
                   im->at<float>(y, x));
214
        }
215
    }
216
}
217
 
218
void imshow(const char *windowName, cv::Mat im, unsigned int x, unsigned int y){
219
 
220
    // Imshow
221
    if(!cvGetWindowHandle(windowName)){
222
        int windowFlags = CV_GUI_EXPANDED | CV_WINDOW_KEEPRATIO;
223
        cv::namedWindow(windowName, windowFlags);
224
        cv::moveWindow(windowName, x, y);
225
    }
226
    cv::imshow(windowName, im);
227
}
228
 
229
void imagesc(const char *windowName, cv::Mat im){
230
 
231
    // Imshow with scaled image
232
 
233
 
234
}
235
 
236
cv::Mat histimage(cv::Mat histogram){
237
 
238
    cv::Mat histImage(512, 640, CV_8UC3, cv::Scalar(0));
239
 
240
    // Normalize the result to [ 2, histImage.rows-2 ]
241
    cv::normalize(histogram, histogram, 2, histImage.rows-2, cv::NORM_MINMAX, -1, cv::Mat());
242
 
243
    float bin_w = (float)histImage.cols/(float)histogram.rows;
244
 
245
    // Draw main histogram
246
    for(int i = 1; i < histogram.rows-10; i++){
247
        cv::line(histImage, cv::Point( bin_w*(i-1), histImage.rows - cvRound(histogram.at<float>(i-1)) ),
248
                 cv::Point( bin_w*(i), histImage.rows - cvRound(histogram.at<float>(i)) ),
249
                 cv::Scalar(255, 255, 255), 2, 4);
250
    }
251
 
252
    // Draw red max
253
    for(int i = histogram.rows-10; i < histogram.rows; i++){
254
        cv::line(histImage, cv::Point( bin_w*(i-1), histImage.rows - cvRound(histogram.at<float>(i-1)) ),
255
                 cv::Point( bin_w*(i), histImage.rows - cvRound(histogram.at<float>(i)) ),
256
                 cv::Scalar(0, 0, 255), 2, 4);
257
    }
258
 
259
    return histImage;
260
}
261
 
262
void hist(const char *windowName, cv::Mat histogram, unsigned int x, unsigned int y){
263
 
264
    // Display
265
    imshow(windowName, histimage(histogram), x, y);
266
    cv::Point(1,2);
267
}
268
 
269
 
270
void writeMat(cv::Mat const& mat, const char* filename, const char* varName, bool bgr2rgb){
271
    /*!
272
         *  \author Philip G. Lee <rocketman768@gmail.com>
273
         *  Write \b mat into \b filename
274
         *  in uncompressed .mat format (Level 5 MATLAB) for Matlab.
275
         *  The variable name in matlab will be \b varName. If
276
         *  \b bgr2rgb is true and there are 3 channels, swaps 1st and 3rd
277
         *  channels in the output. This is needed because OpenCV matrices
278
         *  are bgr, while Matlab is rgb. This has been tested to work with
279
         *  3-channel single-precision floating point matrices, and I hope
280
         *  it works on other types/channels, but not exactly sure.
281
         *  Documentation at <http://www.mathworks.com/help/pdf_doc/matlab/matfile_format.pdf>
282
         */
283
    int textLen = 116;
284
    char* text;
285
    int subsysOffsetLen = 8;
286
    char* subsysOffset;
287
    int verLen = 2;
288
    char* ver;
289
    char flags;
290
    int bytes;
291
    int padBytes;
292
    int bytesPerElement;
293
    int i,j,k,k2;
294
    bool doBgrSwap;
295
    char mxClass;
296
    int32_t miClass;
297
    uchar const* rowPtr;
298
    uint32_t tmp32;
299
    float tmp;
300
    FILE* fp;
301
 
302
    // Matlab constants.
303
    const uint16_t MI = 0x4d49; // Contains "MI" in ascii.
304
    const int32_t miINT8 = 1;
305
    const int32_t miUINT8 = 2;
306
    const int32_t miINT16 = 3;
307
    const int32_t miUINT16 = 4;
308
    const int32_t miINT32 = 5;
309
    const int32_t miUINT32 = 6;
310
    const int32_t miSINGLE = 7;
311
    const int32_t miDOUBLE = 9;
312
    const int32_t miMATRIX = 14;
313
    const char mxDOUBLE_CLASS = 6;
314
    const char mxSINGLE_CLASS = 7;
315
    const char mxINT8_CLASS = 8;
316
    const char mxUINT8_CLASS = 9;
317
    const char mxINT16_CLASS = 10;
318
    const char mxUINT16_CLASS = 11;
319
    const char mxINT32_CLASS = 12;
320
    const char mxUINT32_CLASS = 13;
321
    const uint64_t zero = 0; // Used for padding.
322
 
323
    fp = fopen( filename, "wb" );
324
 
325
    if( fp == 0 )
326
        return;
327
 
328
    const int rows = mat.rows;
329
    const int cols = mat.cols;
330
    const int chans = mat.channels();
331
 
332
    doBgrSwap = (chans==3) && bgr2rgb;
333
 
334
    // I hope this mapping is right :-/
335
    switch( mat.depth() ){
336
    case CV_8U:
337
        mxClass = mxUINT8_CLASS;
338
        miClass = miUINT8;
339
        bytesPerElement = 1;
340
        break;
341
    case CV_8S:
342
        mxClass = mxINT8_CLASS;
343
        miClass = miINT8;
344
        bytesPerElement = 1;
345
        break;
346
    case CV_16U:
347
        mxClass = mxUINT16_CLASS;
348
        miClass = miUINT16;
349
        bytesPerElement = 2;
350
        break;
351
    case CV_16S:
352
        mxClass = mxINT16_CLASS;
353
        miClass = miINT16;
354
        bytesPerElement = 2;
355
        break;
356
    case CV_32S:
357
        mxClass = mxINT32_CLASS;
358
        miClass = miINT32;
359
        bytesPerElement = 4;
360
        break;
361
    case CV_32F:
362
        mxClass = mxSINGLE_CLASS;
363
        miClass = miSINGLE;
364
        bytesPerElement = 4;
365
        break;
366
    case CV_64F:
367
        mxClass = mxDOUBLE_CLASS;
368
        miClass = miDOUBLE;
369
        bytesPerElement = 8;
370
        break;
371
    default:
372
        return;
373
    }
374
 
375
    //==================Mat-file header (128 bytes, page 1-5)==================
376
    text = new char[textLen]; // Human-readable text.
377
    memset( text, ' ', textLen );
378
    text[textLen-1] = '\0';
379
    const char* t = "MATLAB 5.0 MAT-file, Platform: PCWIN";
380
    memcpy( text, t, strlen(t) );
381
 
382
    subsysOffset = new char[subsysOffsetLen]; // Zeros for us.
383
    memset( subsysOffset, 0x00, subsysOffsetLen );
384
    ver = new char[verLen];
385
    ver[0] = 0x00;
386
    ver[1] = 0x01;
387
 
388
    fwrite( text, 1, textLen, fp );
389
    fwrite( subsysOffset, 1, subsysOffsetLen, fp );
390
    fwrite( ver, 1, verLen, fp );
391
    // Endian indicator. MI will show up as "MI" on big-endian
392
    // systems and "IM" on little-endian systems.
393
    fwrite( &MI, 2, 1, fp );
394
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
395
 
396
    //===================Data element tag (8 bytes, page 1-8)==================
397
    bytes = 16 + 24 + (8 + strlen(varName) + (8-(strlen(varName)%8))%8)
398
            + (8 + rows*cols*chans*bytesPerElement);
399
    fwrite( &miMATRIX, 4, 1, fp ); // Data type.
400
    fwrite( &bytes, 4, 1, fp); // Data size in bytes.
401
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
402
 
403
    //====================Array flags (16 bytes, page 1-15)====================
404
    bytes = 8;
405
    fwrite( &miUINT32, 4, 1, fp );
406
    fwrite( &bytes, 4, 1, fp );
407
    flags = 0x00; // Complex, logical, and global flags all off.
408
 
409
    tmp32 = 0;
410
    tmp32 = (flags << 8 ) | (mxClass);
411
    fwrite( &tmp32, 4, 1, fp );
412
 
413
    fwrite( &zero, 4, 1, fp ); // Padding to 64-bit boundary.
414
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
415
 
416
    //===============Dimensions subelement (24 bytes, page 1-17)===============
417
    bytes = 12;
418
    fwrite( &miINT32, 4, 1, fp );
419
    fwrite( &bytes, 4, 1, fp );
420
 
421
    fwrite( &rows, 4, 1, fp );
422
    fwrite( &cols, 4, 1, fp );
423
    fwrite( &chans, 4, 1, fp );
424
    fwrite( &zero, 4, 1, fp ); // Padding to 64-bit boundary.
425
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
426
 
427
    //==Array name (8 + strlen(varName) + (8-(strlen(varName)%8))%8 bytes, page 1-17)==
428
    bytes = strlen(varName);
429
 
430
    fwrite( &miINT8, 4, 1, fp );
431
    fwrite( &bytes, 4, 1, fp );
432
    fwrite( varName, 1, bytes, fp );
433
 
434
    // Pad to nearest 64-bit boundary.
435
    padBytes = (8-(bytes%8))%8;
436
    fwrite( &zero, 1, padBytes, fp );
437
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
438
 
439
    //====Matrix data (rows*cols*chans*bytesPerElement+8 bytes, page 1-20)=====
440
    bytes = rows*cols*chans*bytesPerElement;
441
    fwrite( &miClass, 4, 1, fp );
442
    fwrite( &bytes, 4, 1, fp );
443
 
444
    for( k = 0; k < chans; ++k )
445
    {
446
        if( doBgrSwap )
447
        {
448
            k2 = (k==0)? 2 : ((k==2)? 0 : 1);
449
        }
450
        else
451
            k2 = k;
452
 
453
        for( j = 0; j < cols; ++j )
454
        {
455
            for( i = 0; i < rows; ++i )
456
            {
457
                rowPtr = mat.data + mat.step*i;
458
                fwrite( rowPtr + (chans*j + k2)*bytesPerElement, bytesPerElement, 1, fp );
459
            }
460
        }
461
    }
462
 
463
    // Pad to 64-bit boundary.
464
    padBytes = (8-(bytes%8))%8;
465
    fwrite( &zero, 1, padBytes, fp );
466
    //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
467
 
468
    fclose(fp);
469
    delete[] text;
470
    delete[] subsysOffset;
471
    delete[] ver;
472
}
473
 
474
 
475
 
476
 
477
 
478
}