Subversion Repositories seema-scanner

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
99 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
99 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
 
99 jakw 150
cv::Mat AlgorithmGrayCodeHorzVert::getEncodingPattern(unsigned int depth){
95 jakw 151
    return patterns[depth];
152
}
153
 
154
 
98 jakw 155
static bool sortingLarger(cv::Vec3d i,cv::Vec3d j){ return (i[2]<j[2]);}
156
static bool sortingEqual(cv::Vec3d i,cv::Vec3d j){ return (i[2]==j[2]);}
95 jakw 157
 
98 jakw 158
static void getIntersectionLabels(const cv::Mat& codeHorz, const cv::Mat& codeVert, int NbitsHorz, int NbitsVert, std::vector< cv::Vec3d >& intersections){
95 jakw 159
 
96 jakw 160
    int nRows = codeHorz.rows;
161
    int nCols = codeHorz.cols;
95 jakw 162
 
96 jakw 163
    int labelHorz;
164
    int labelVert;
165
    int labelHorzRight;
166
    int labelVertBelow;
95 jakw 167
 
96 jakw 168
    // collect intersections
169
    for(int row=0; row<nRows+1; row++){
170
        for(int col=0; col<nCols+1; col++){
95 jakw 171
 
96 jakw 172
            labelHorz = codeHorz.at<int>(row, col);
173
            labelHorzRight = codeHorz.at<int>(row, col+1);
174
 
175
            labelVert = codeVert.at<int>(row, col);
176
            labelVertBelow = codeVert.at<int>(row+1, col);
177
 
178
            // labels need to be non-background, and differ in exactly one bit
179
            if(labelHorz != -1 && labelHorzRight != -1 &&
180
               countBits(labelHorz^labelHorzRight) == 1 &&
181
               labelVert != -1 && labelVertBelow != -1 &&
182
               countBits(labelVert^labelVertBelow) == 1){
183
 
184
                // OVERFLOW??
98 jakw 185
                double orderingRelation = ((ulong)labelHorz << NbitsHorz+2*NbitsVert) + ((ulong)labelHorzRight << 2*NbitsVert) +
186
                                          ((ulong)labelVert << NbitsVert) + (ulong)labelVertBelow;
96 jakw 187
                // store left label column
98 jakw 188
                intersections.push_back(cv::Vec3d(row, col, orderingRelation));
96 jakw 189
            }
95 jakw 190
        }
191
    }
192
    // sort
96 jakw 193
    std::sort(intersections.begin(), intersections.end(), sortingLarger);
95 jakw 194
 
195
    // remove duplicates
98 jakw 196
    std::vector< cv::Vec3d >::iterator it;
96 jakw 197
    it = std::unique(intersections.begin(), intersections.end(), sortingEqual);
198
    intersections.resize(std::distance(intersections.begin(),it));
95 jakw 199
}
200
 
98 jakw 201
static cv::Vec3b getColorSubpix(const cv::Mat& img, cv::Point2f pt){
95 jakw 202
    assert(!img.empty());
203
    assert(img.channels() == 3);
204
 
205
    int x = (int)pt.x;
206
    int y = (int)pt.y;
207
 
208
    int x0 = cv::borderInterpolate(x,   img.cols, cv::BORDER_REFLECT_101);
209
    int x1 = cv::borderInterpolate(x+1, img.cols, cv::BORDER_REFLECT_101);
210
    int y0 = cv::borderInterpolate(y,   img.rows, cv::BORDER_REFLECT_101);
211
    int y1 = cv::borderInterpolate(y+1, img.rows, cv::BORDER_REFLECT_101);
212
 
213
    float a = pt.x - (float)x;
214
    float c = pt.y - (float)y;
215
 
216
    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)
217
                           + (img.at<cv::Vec3b>(y1, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[0] * a) * c);
218
    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)
219
                           + (img.at<cv::Vec3b>(y1, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[1] * a) * c);
220
    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)
221
                           + (img.at<cv::Vec3b>(y1, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[2] * a) * c);
222
 
223
    return cv::Vec3b(b, g, r);
224
}
225
 
99 jakw 226
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 227
 
228
    assert(frames0.size() == N);
229
    assert(frames1.size() == N);
230
 
231
    int frameRows = frames0[0].rows;
232
    int frameCols = frames0[0].cols;
233
 
234
    // gray-scale
235
    std::vector<cv::Mat> frames0Gray(N);
236
    std::vector<cv::Mat> frames1Gray(N);
237
    for(int i=0; i<N; i++){
98 jakw 238
        cv::cvtColor(frames0[i], frames0Gray[i], CV_RGB2GRAY);
239
        cv::cvtColor(frames1[i], frames1Gray[i], CV_RGB2GRAY);
95 jakw 240
    }
241
 
242
    // colors
243
    cv::Mat color0 = frames0[0];
244
    cv::Mat color1 = frames1[0];
245
 
246
    // occlusion masks
247
    cv::Mat occlusion0, occlusion1;
248
    cv::subtract(frames0Gray[0], frames0Gray[1], occlusion0);
249
    occlusion0 = occlusion0 > 25;
250
    cv::subtract(frames1Gray[0], frames1Gray[1], occlusion1);
251
    occlusion1 = occlusion1 > 25;
252
 
253
    // erode occlusion masks
254
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3,3));
255
    cv::erode(occlusion0, occlusion0, strel);
256
    cv::erode(occlusion1, occlusion1, strel);
257
 
258
//cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
259
//cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");
260
 
261
    // decode patterns
262
    cv::Mat code0Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
263
    cv::Mat code1Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
264
    cv::Mat code0Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
265
    cv::Mat code1Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
266
 
267
    // horizontal codes into gray code
268
    for(int i=0; i<NbitsHorz; i++){
269
        cv::Mat bit0;
270
        cv::subtract(frames0Gray[i*2+2], frames0Gray[i*2+3], bit0);
271
        bit0 = bit0 > 0;
272
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 273
        cv::add(code0Horz, bit0*twopowi(NbitsHorz-i-1), code0Horz, cv::Mat(), CV_32S);
95 jakw 274
 
275
        cv::Mat bit1;
276
        cv::subtract(frames1Gray[i*2+2], frames1Gray[i*2+3], bit1);
277
        bit1 = bit1 > 0;
278
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 279
        cv::add(code1Horz, bit1*twopowi(NbitsHorz-i-1), code1Horz, cv::Mat(), CV_32S);
95 jakw 280
    }
281
 
282
    // vertical codes into gray code
283
    for(int i=0; i<NbitsVert; i++){
284
        cv::Mat bit0;
285
        cv::subtract(frames0Gray[i*2+NbitsHorz+2], frames0Gray[i*2+NbitsHorz+3], bit0);
286
        bit0 = bit0 > 0;
287
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
96 jakw 288
        cv::add(code0Vert, bit0*twopowi(NbitsVert-i-1), code0Vert, cv::Mat(), CV_32S);
95 jakw 289
 
290
        cv::Mat bit1;
291
        cv::subtract(frames1Gray[i*2+NbitsHorz+2], frames1Gray[i*2+NbitsHorz+3], bit1);
292
        bit1 = bit1 > 0;
293
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
96 jakw 294
        cv::add(code1Vert, bit1*twopowi(NbitsVert-i-1), code1Vert, cv::Mat(), CV_32S);
95 jakw 295
    }
296
 
297
//cvtools::writeMat(code0Horz, "code0Horz.mat", "code0Horz");
298
//cvtools::writeMat(code1Horz, "code1Horz.mat", "code1Horz");
299
//cvtools::writeMat(code0Vert, "code0Vert.mat", "code0Vert");
300
//cvtools::writeMat(code1Vert, "code1Vert.mat", "code1Vert");
301
 
302
    // set occluded pixels to -1
303
    for(int r=0; r<frameRows; r++){
304
        for(int c=0; c<frameCols; c++){
305
            if(occlusion0.at<char>(r,c) == 0){
306
                code0Horz.at<float>(r,c) = -1;
307
                code0Vert.at<float>(r,c) = -1;
308
            }
309
            if(occlusion1.at<char>(r,c) == 0){
310
                code1Horz.at<float>(r,c) = -1;
311
                code1Vert.at<float>(r,c) = -1;
312
            }
313
        }
314
    }
315
 
96 jakw 316
    // matching
98 jakw 317
    std::vector< cv::Vec3d > intersections0, intersections1;
95 jakw 318
 
96 jakw 319
    // intersection data structure containing [floor(row), floor(column), orderingRelation]
320
    getIntersectionLabels(code0Horz, code0Vert, NbitsHorz, NbitsVert, intersections0);
321
    getIntersectionLabels(code1Horz, code1Vert, NbitsHorz, NbitsVert, intersections1);
95 jakw 322
 
96 jakw 323
    // match intersections
98 jakw 324
    std::vector< cv::Vec3d > matches0, matches1;
96 jakw 325
    int i=0, j=0;
95 jakw 326
 
96 jakw 327
    while(i<intersections0.size() && j<intersections1.size()){
328
        if(intersections0[i][2] == intersections1[j][2]){
329
            matches0.push_back(intersections0[i]);
330
            matches1.push_back(intersections1[j]);
331
            i += 1;
332
            j += 1;
333
        } else if(intersections0[i][2] < intersections1[j][2]){
334
            i += 1;
335
        } else if(intersections0[i][2] > intersections1[j][2]){
336
            j += 1;
337
        }
338
    }
95 jakw 339
 
98 jakw 340
    int nMatches = matches0.size();
95 jakw 341
 
98 jakw 342
    if(nMatches < 1){
343
        Q.resize(0);
344
        color.resize(0);
345
 
346
        return;
347
    }
348
 
349
    std::vector<cv::Vec2f> q0(nMatches), q1(nMatches);
350
 
351
    for(int i=0; i<nMatches; i++){
352
        q0[i] = cv::Vec2f(matches0[i][1], matches0[i][0]);
353
        q1[i] = cv::Vec2f(matches1[i][1], matches1[i][0]);
354
    }
355
 
96 jakw 356
    // TODO: subpixel refinement in both horizontal and vertical
357
//    // subpixel refinement finds the intersection of linear interpolants in the positive/negative pattern
358
//    for(int i=0; i<matchedEdges0.size(); i++){
95 jakw 359
 
96 jakw 360
//        int level = Nbits - leastSignificantBitSet(matchedEdges0[i][1]^matchedEdges0[i][2]);
95 jakw 361
 
96 jakw 362
//        // refine for camera 0
363
//        float c0 = matchedEdges0[i][0];
364
//        float c1 = c0+1;
95 jakw 365
 
96 jakw 366
//        float pos0 = frames0Rect[2*level+2].at<char>(row, c0);
367
//        float pos1 = frames0Rect[2*level+2].at<char>(row, c1);
368
//        float neg0 = frames0Rect[2*level+3].at<char>(row, c0);
369
//        float neg1 = frames0Rect[2*level+3].at<char>(row, c1);
95 jakw 370
 
96 jakw 371
//        float col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
372
//        q0Rect.push_back(cv::Point2f(col, row));
95 jakw 373
 
96 jakw 374
//        // refine for camera 1
375
//        c0 = matchedEdges1[i][0];
376
//        c1 = c0+1;
95 jakw 377
 
96 jakw 378
//        pos0 = frames1Rect[2*level+2].at<char>(row, c0);
379
//        pos1 = frames1Rect[2*level+2].at<char>(row, c1);
380
//        neg0 = frames1Rect[2*level+3].at<char>(row, c0);
381
//        neg1 = frames1Rect[2*level+3].at<char>(row, c1);
95 jakw 382
 
96 jakw 383
//        col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
384
//        q1Rect.push_back(cv::Point2f(col, row));
95 jakw 385
 
96 jakw 386
//    }
95 jakw 387
 
388
 
389
 
390
 
96 jakw 391
    // retrieve color information (at integer coordinates)
392
    color.resize(nMatches);
393
    for(int i=0; i<nMatches; i++){
95 jakw 394
 
98 jakw 395
//        cv::Vec3b c0 = color0.at<cv::Vec3b>(q0[i][1], q0[i][0]);
396
//        cv::Vec3b c1 = color1.at<cv::Vec3b>(q1[i][1], q1[i][0]);
397
        cv::Vec3b c0 = getColorSubpix(color0, q0[i]);
398
        cv::Vec3b c1 = getColorSubpix(color1, q1[i]);
95 jakw 399
 
96 jakw 400
        color[i] = 0.5*c0 + 0.5*c1;
401
    }
95 jakw 402
 
96 jakw 403
    // triangulate points
404
    cv::Mat P0(3, 4, CV_32F, cv::Scalar(0.0));
405
    cv::Mat(calibration.K0).copyTo(P0.colRange(0, 3));
95 jakw 406
 
96 jakw 407
    cv::Mat P1(3, 4, CV_32F), temp(3,4,CV_32F);
408
    cv::Mat(calibration.R1).copyTo(temp(cv::Range(0,3), cv::Range(0,3)));
409
    cv::Mat(calibration.T1).copyTo(temp(cv::Range(0,3), cv::Range(3,4)));
410
    P1 = cv::Mat(calibration.K1) * temp;
95 jakw 411
 
96 jakw 412
    cv::correctMatches(calibration.F, q0, q1, q0, q1);
95 jakw 413
 
96 jakw 414
    cv::Mat QMatHomogenous, QMat;
415
    cv::triangulatePoints(P0, P1, q0, q1, QMatHomogenous);
95 jakw 416
 
96 jakw 417
    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
418
    cvtools::matToPoints3f(QMat, Q);
95 jakw 419
 
420
}