Subversion Repositories seema-scanner

Rev

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