Subversion Repositories seema-scanner

Rev

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

Rev Author Line No. Line
103 jakw 1
#include "AlgorithmGrayCodeHorzVert.h"
95 jakw 2
#include <cmath>
96 jakw 3
#include <assert.h>
95 jakw 4
#include "cvtools.h"
5
 
6
#ifndef log2f
7
#define log2f(x) (log(x)/log(2.0))
8
#endif
9
 
10
//using namespace std;
11
 
12
/*
13
 * The purpose of this function is to convert an unsigned
14
 * binary number to reflected binary Gray code.
15
 *
16
 * The operator >> is shift right. The operator ^ is exclusive or.
17
 * Source: http://en.wikipedia.org/wiki/Gray_code
18
 */
19
static unsigned int binaryToGray(unsigned int num) {
20
    return (num >> 1) ^ num;
21
}
22
 
23
/*
24
 * From Wikipedia: http://en.wikipedia.org/wiki/Gray_code
25
 * The purpose of this function is to convert a reflected binary
26
 * Gray code number to a binary number.
27
 */
28
static unsigned int grayToBinary(unsigned int num){
29
    unsigned int mask;
30
    for(mask = num >> 1; mask != 0; mask = mask >> 1)
31
        num = num ^ mask;
32
    return num;
33
}
34
 
35
/*
36
 * Return the Nth bit of an unsigned integer number
37
 */
38
static bool getBit(int decimal, int N){
39
 
40
    return decimal & 1 << (N-1);
41
}
42
 
43
/*
44
 * Return the number of bits set in an integer
45
 */
46
static int countBits(int n) {
47
  unsigned int c; // c accumulates the total bits set in v
48
  for (c = 0; n>0; c++)
49
    n &= n - 1; // clear the least significant bit set
50
  return c;
51
}
52
 
53
/*
54
 * Return the position of the least significant bit that is set
55
 */
56
static int leastSignificantBitSet(int x){
57
  if(x == 0)
58
      return 0;
59
 
60
  int val = 1;
61
  while(x>>=1)
62
      val++;
63
 
64
  return val;
65
}
66
 
67
//static int get_bit(int decimal, int N){
68
 
69
//    // Shifting the 1 for N-1 bits
70
//    int constant = 1 << (N-1);
71
 
72
//    // If the bit is set, return 1
73
//    if( decimal & constant )
74
//        return 1;
75
//    else
76
//        return 0;
77
//}
78
 
79
static inline unsigned int powi(int num, unsigned int exponent){
80
 
81
    if(exponent == 0)
82
        return 1;
83
 
84
    float res = num;
85
    for(unsigned int i=0; i<exponent-1; i++)
86
        res *= num;
87
 
88
    return res;
89
}
90
 
91
static inline unsigned int twopowi(unsigned int exponent){
92
 
93
    return 1 << exponent;
94
}
95
 
96
// Algorithm
103 jakw 97
AlgorithmGrayCodeHorzVert::AlgorithmGrayCodeHorzVert(unsigned int _screenCols, unsigned int _screenRows) : Algorithm(_screenCols, _screenRows){
95 jakw 98
 
99
    NbitsHorz = ceilf(log2f((float)screenCols));
100
    NbitsVert =  ceilf(log2f((float)screenRows));
101
    N = 2 + (NbitsHorz+NbitsVert)*2;
102
 
103
    // all on pattern
104
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
105
    patterns.push_back(allOn);
106
 
107
    // all off pattern
108
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
109
    patterns.push_back(allOff);
110
 
111
 
112
    // horizontally encoding patterns
113
    for(unsigned int p=0; p<NbitsHorz; p++){
114
        cv::Mat pattern(1, screenCols, CV_8UC3);
115
        cv::Mat patternInv(1, screenCols, CV_8UC3);
116
 
117
        for(unsigned int j=0; j<screenCols; j++){
118
 
119
            unsigned int jGray = binaryToGray(j);
120
            // Amplitude of channels
96 jakw 121
            int bit = (int)getBit(jGray, NbitsHorz-p);
95 jakw 122
            pattern.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
123
            int invBit = bit^1;
124
            patternInv.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
125
        }
126
        patterns.push_back(pattern);
127
        patterns.push_back(patternInv);
128
    }
129
 
130
    // vertical encoding patterns
131
    for(unsigned int p=0; p<NbitsVert; p++){
132
        cv::Mat pattern(screenRows, 1, CV_8UC3);
133
        cv::Mat patternInv(screenRows, 1, CV_8UC3);
134
 
135
        for(unsigned int j=0; j<screenRows; j++){
136
 
137
            unsigned int jGray = binaryToGray(j);
138
            // Amplitude of channels
96 jakw 139
            int bit = (int)getBit(jGray, NbitsVert-p);
95 jakw 140
            pattern.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
141
            int invBit = bit^1;
142
            patternInv.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
143
        }
144
        patterns.push_back(pattern);
145
        patterns.push_back(patternInv);
146
    }
147
 
148
}
149
 
103 jakw 150
cv::Mat AlgorithmGrayCodeHorzVert::getEncodingPattern(unsigned int depth){
95 jakw 151
    return patterns[depth];
152
}
153
 
154
 
107 jakw 155
typedef struct intersection{
156
    unsigned int row;
157
    unsigned int col;
158
    unsigned int labelLeft;
159
    unsigned int labelRight;
160
    unsigned int labelAbove;
161
    unsigned int labelBelow;
162
    unsigned long id;
163
    intersection() : row(0), col(0), labelLeft(0), labelRight(0), labelAbove(0), labelBelow(0), id(0){}
164
    intersection(unsigned int _row, unsigned int _col, unsigned int _labelLeft, unsigned int _labelRight, unsigned int _labelAbove, unsigned int _labelBelow, unsigned long long _id) :
165
        row(_row), col(_col), labelLeft(_labelLeft), labelRight(_labelRight), labelAbove(_labelAbove), labelBelow(_labelBelow), id(_id){}
166
} intersection;
95 jakw 167
 
168
 
107 jakw 169
static bool sortingLarger(intersection i,intersection j){ return (i.id<j.id);}
170
static bool sortingEqual(intersection i,intersection j){ return (i.id==j.id);}
171
 
172
static void getIntersectionLabels(const cv::Mat& codeHorz, const cv::Mat& codeVert, int NbitsHorz, int NbitsVert, std::vector<intersection>& intersections){
173
 
96 jakw 174
    int nRows = codeHorz.rows;
175
    int nCols = codeHorz.cols;
95 jakw 176
 
96 jakw 177
    int labelHorz;
178
    int labelVert;
179
    int labelHorzRight;
180
    int labelVertBelow;
95 jakw 181
 
96 jakw 182
    // collect intersections
183
    for(int row=0; row<nRows+1; row++){
184
        for(int col=0; col<nCols+1; col++){
95 jakw 185
 
96 jakw 186
            labelHorz = codeHorz.at<int>(row, col);
187
            labelHorzRight = codeHorz.at<int>(row, col+1);
188
 
189
            labelVert = codeVert.at<int>(row, col);
190
            labelVertBelow = codeVert.at<int>(row+1, col);
191
 
192
            // labels need to be non-background, and differ in exactly one bit
193
            if(labelHorz != -1 && labelHorzRight != -1 &&
194
               countBits(labelHorz^labelHorzRight) == 1 &&
195
               labelVert != -1 && labelVertBelow != -1 &&
196
               countBits(labelVert^labelVertBelow) == 1){
197
 
198
                // OVERFLOW??
107 jakw 199
                unsigned long id = ((ulong)labelHorz << NbitsHorz+2*NbitsVert) + ((ulong)labelHorzRight << 2*NbitsVert) +
98 jakw 200
                                          ((ulong)labelVert << NbitsVert) + (ulong)labelVertBelow;
96 jakw 201
                // store left label column
107 jakw 202
                intersections.push_back(intersection(row, col, labelHorz, labelHorzRight, labelVert, labelVertBelow, id));
96 jakw 203
            }
95 jakw 204
        }
205
    }
206
    // sort
96 jakw 207
    std::sort(intersections.begin(), intersections.end(), sortingLarger);
95 jakw 208
 
209
    // remove duplicates
107 jakw 210
    std::vector<intersection>::iterator it;
96 jakw 211
    it = std::unique(intersections.begin(), intersections.end(), sortingEqual);
212
    intersections.resize(std::distance(intersections.begin(),it));
95 jakw 213
}
214
 
98 jakw 215
static cv::Vec3b getColorSubpix(const cv::Mat& img, cv::Point2f pt){
95 jakw 216
    assert(!img.empty());
217
    assert(img.channels() == 3);
218
 
219
    int x = (int)pt.x;
220
    int y = (int)pt.y;
221
 
222
    int x0 = cv::borderInterpolate(x,   img.cols, cv::BORDER_REFLECT_101);
223
    int x1 = cv::borderInterpolate(x+1, img.cols, cv::BORDER_REFLECT_101);
224
    int y0 = cv::borderInterpolate(y,   img.rows, cv::BORDER_REFLECT_101);
225
    int y1 = cv::borderInterpolate(y+1, img.rows, cv::BORDER_REFLECT_101);
226
 
227
    float a = pt.x - (float)x;
228
    float c = pt.y - (float)y;
229
 
230
    uchar b = (uchar)cvRound((img.at<cv::Vec3b>(y0, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y0, x1)[0] * a) * (1.f - c)
231
                           + (img.at<cv::Vec3b>(y1, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[0] * a) * c);
232
    uchar g = (uchar)cvRound((img.at<cv::Vec3b>(y0, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y0, x1)[1] * a) * (1.f - c)
233
                           + (img.at<cv::Vec3b>(y1, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[1] * a) * c);
234
    uchar r = (uchar)cvRound((img.at<cv::Vec3b>(y0, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y0, x1)[2] * a) * (1.f - c)
235
                           + (img.at<cv::Vec3b>(y1, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[2] * a) * c);
236
 
237
    return cv::Vec3b(b, g, r);
238
}
239
 
103 jakw 240
void AlgorithmGrayCodeHorzVert::get3DPoints(SMCalibrationParameters calibration, const std::vector<cv::Mat>& frames0, const std::vector<cv::Mat>& frames1, std::vector<cv::Point3f>& Q, std::vector<cv::Vec3b>& color){
95 jakw 241
 
242
    assert(frames0.size() == N);
243
    assert(frames1.size() == N);
244
 
245
    int frameRows = frames0[0].rows;
246
    int frameCols = frames0[0].cols;
247
 
248
    // gray-scale
249
    std::vector<cv::Mat> frames0Gray(N);
250
    std::vector<cv::Mat> frames1Gray(N);
251
    for(int i=0; i<N; i++){
98 jakw 252
        cv::cvtColor(frames0[i], frames0Gray[i], CV_RGB2GRAY);
253
        cv::cvtColor(frames1[i], frames1Gray[i], CV_RGB2GRAY);
95 jakw 254
    }
255
 
256
    // colors
257
    cv::Mat color0 = frames0[0];
258
    cv::Mat color1 = frames1[0];
259
 
260
    // occlusion masks
261
    cv::Mat occlusion0, occlusion1;
262
    cv::subtract(frames0Gray[0], frames0Gray[1], occlusion0);
263
    occlusion0 = occlusion0 > 25;
264
    cv::subtract(frames1Gray[0], frames1Gray[1], occlusion1);
265
    occlusion1 = occlusion1 > 25;
266
 
267
    // erode occlusion masks
268
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3,3));
269
    cv::erode(occlusion0, occlusion0, strel);
270
    cv::erode(occlusion1, occlusion1, strel);
271
 
272
//cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
273
//cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");
274
 
275
    // decode patterns
276
    cv::Mat code0Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
277
    cv::Mat code1Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
278
    cv::Mat code0Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
279
    cv::Mat code1Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
280
 
281
    // horizontal codes into gray code
282
    for(int i=0; i<NbitsHorz; i++){
283
        cv::Mat bit0;
284
        cv::subtract(frames0Gray[i*2+2], frames0Gray[i*2+3], bit0);
285
        bit0 = bit0 > 0;
286
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 287
        cv::add(code0Horz, bit0*twopowi(NbitsHorz-i-1), code0Horz, cv::Mat(), CV_32S);
95 jakw 288
 
289
        cv::Mat bit1;
290
        cv::subtract(frames1Gray[i*2+2], frames1Gray[i*2+3], bit1);
291
        bit1 = bit1 > 0;
292
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 293
        cv::add(code1Horz, bit1*twopowi(NbitsHorz-i-1), code1Horz, cv::Mat(), CV_32S);
95 jakw 294
    }
295
 
296
    // vertical codes into gray code
297
    for(int i=0; i<NbitsVert; i++){
298
        cv::Mat bit0;
299
        cv::subtract(frames0Gray[i*2+NbitsHorz+2], frames0Gray[i*2+NbitsHorz+3], bit0);
300
        bit0 = bit0 > 0;
301
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 302
        cv::add(code0Vert, bit0*twopowi(NbitsVert-i-1), code0Vert, cv::Mat(), CV_32S);
95 jakw 303
 
304
        cv::Mat bit1;
305
        cv::subtract(frames1Gray[i*2+NbitsHorz+2], frames1Gray[i*2+NbitsHorz+3], bit1);
306
        bit1 = bit1 > 0;
307
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 308
        cv::add(code1Vert, bit1*twopowi(NbitsVert-i-1), code1Vert, cv::Mat(), CV_32S);
95 jakw 309
    }
310
 
311
//cvtools::writeMat(code0Horz, "code0Horz.mat", "code0Horz");
312
//cvtools::writeMat(code1Horz, "code1Horz.mat", "code1Horz");
313
//cvtools::writeMat(code0Vert, "code0Vert.mat", "code0Vert");
314
//cvtools::writeMat(code1Vert, "code1Vert.mat", "code1Vert");
315
 
316
    // set occluded pixels to -1
317
    for(int r=0; r<frameRows; r++){
318
        for(int c=0; c<frameCols; c++){
319
            if(occlusion0.at<char>(r,c) == 0){
320
                code0Horz.at<float>(r,c) = -1;
321
                code0Vert.at<float>(r,c) = -1;
322
            }
323
            if(occlusion1.at<char>(r,c) == 0){
324
                code1Horz.at<float>(r,c) = -1;
325
                code1Vert.at<float>(r,c) = -1;
326
            }
327
        }
328
    }
329
 
96 jakw 330
    // matching
107 jakw 331
    std::vector<intersection> intersections0, intersections1;
95 jakw 332
 
107 jakw 333
    // intersection data structure containing [floor(row), floor(column), id]
96 jakw 334
    getIntersectionLabels(code0Horz, code0Vert, NbitsHorz, NbitsVert, intersections0);
335
    getIntersectionLabels(code1Horz, code1Vert, NbitsHorz, NbitsVert, intersections1);
95 jakw 336
 
96 jakw 337
    // match intersections
107 jakw 338
    std::vector<intersection> matches0, matches1;
96 jakw 339
    int i=0, j=0;
95 jakw 340
 
96 jakw 341
    while(i<intersections0.size() && j<intersections1.size()){
107 jakw 342
        if(intersections0[i].id == intersections1[j].id){
96 jakw 343
            matches0.push_back(intersections0[i]);
344
            matches1.push_back(intersections1[j]);
345
            i += 1;
346
            j += 1;
107 jakw 347
        } else if(intersections0[i].id < intersections1[j].id){
96 jakw 348
            i += 1;
107 jakw 349
        } else if(intersections0[i].id > intersections1[j].id){
96 jakw 350
            j += 1;
351
        }
352
    }
95 jakw 353
 
98 jakw 354
    int nMatches = matches0.size();
95 jakw 355
 
98 jakw 356
    if(nMatches < 1){
357
        Q.resize(0);
358
        color.resize(0);
359
 
360
        return;
361
    }
362
 
363
    std::vector<cv::Vec2f> q0(nMatches), q1(nMatches);
364
 
107 jakw 365
//    for(int i=0; i<nMatches; i++){
366
//        q0[i] = cv::Vec2f(matches0[i].col, matches0[i].row);
367
//        q1[i] = cv::Vec2f(matches1[i].col, matches1[i].row);
368
//    }
98 jakw 369
 
107 jakw 370
    // horizontal subpixel refinement finds the intersection of linear interpolants in the positive/negative pattern
96 jakw 371
    // TODO: subpixel refinement in both horizontal and vertical
107 jakw 372
    for(int i=0; i<nMatches; i++){
95 jakw 373
 
107 jakw 374
        int level = NbitsHorz - leastSignificantBitSet(matches0[i].labelLeft^matches0[i].labelRight);
95 jakw 375
 
107 jakw 376
        // refine for camera 0
377
        float row = matches0[i].row;
378
        float c0 = matches0[i].col;
379
        float c1 = c0+1;
95 jakw 380
 
107 jakw 381
        float pos0 = frames0[2*level+2].at<char>(row, c0);
382
        float pos1 = frames0[2*level+2].at<char>(row, c1);
383
        float neg0 = frames0[2*level+3].at<char>(row, c0);
384
        float neg1 = frames0[2*level+3].at<char>(row, c1);
95 jakw 385
 
107 jakw 386
        float col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
387
        q0[i] = cv::Vec2f(col, row);
95 jakw 388
 
107 jakw 389
        // refine for camera 1
390
        row = matches1[i].row;
391
        c0 = matches1[i].col;
392
        c1 = c0+1;
95 jakw 393
 
107 jakw 394
        pos0 = frames1[2*level+2].at<char>(row, c0);
395
        pos1 = frames1[2*level+2].at<char>(row, c1);
396
        neg0 = frames1[2*level+3].at<char>(row, c0);
397
        neg1 = frames1[2*level+3].at<char>(row, c1);
95 jakw 398
 
107 jakw 399
        col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
400
        q1[i] = cv::Vec2f(col, row);
95 jakw 401
 
107 jakw 402
    }
95 jakw 403
 
404
 
405
 
406
 
96 jakw 407
    // retrieve color information (at integer coordinates)
408
    color.resize(nMatches);
409
    for(int i=0; i<nMatches; i++){
95 jakw 410
 
98 jakw 411
//        cv::Vec3b c0 = color0.at<cv::Vec3b>(q0[i][1], q0[i][0]);
412
//        cv::Vec3b c1 = color1.at<cv::Vec3b>(q1[i][1], q1[i][0]);
413
        cv::Vec3b c0 = getColorSubpix(color0, q0[i]);
414
        cv::Vec3b c1 = getColorSubpix(color1, q1[i]);
95 jakw 415
 
96 jakw 416
        color[i] = 0.5*c0 + 0.5*c1;
417
    }
95 jakw 418
 
96 jakw 419
    // triangulate points
420
    cv::Mat P0(3, 4, CV_32F, cv::Scalar(0.0));
421
    cv::Mat(calibration.K0).copyTo(P0.colRange(0, 3));
95 jakw 422
 
96 jakw 423
    cv::Mat P1(3, 4, CV_32F), temp(3,4,CV_32F);
424
    cv::Mat(calibration.R1).copyTo(temp(cv::Range(0,3), cv::Range(0,3)));
425
    cv::Mat(calibration.T1).copyTo(temp(cv::Range(0,3), cv::Range(3,4)));
426
    P1 = cv::Mat(calibration.K1) * temp;
95 jakw 427
 
96 jakw 428
    cv::correctMatches(calibration.F, q0, q1, q0, q1);
95 jakw 429
 
96 jakw 430
    cv::Mat QMatHomogenous, QMat;
431
    cv::triangulatePoints(P0, P1, q0, q1, QMatHomogenous);
95 jakw 432
 
96 jakw 433
    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
434
    cvtools::matToPoints3f(QMat, Q);
95 jakw 435
 
436
}