Subversion Repositories seema-scanner

Rev

Rev 98 | Rev 107 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include "AlgorithmGrayCodeHorzVert.h"
#include <cmath>
#include <assert.h>
#include "cvtools.h"

#ifndef log2f
#define log2f(x) (log(x)/log(2.0))
#endif

//using namespace std;

/*
 * The purpose of this function is to convert an unsigned
 * binary number to reflected binary Gray code.
 *
 * The operator >> is shift right. The operator ^ is exclusive or.
 * Source: http://en.wikipedia.org/wiki/Gray_code
 */
static unsigned int binaryToGray(unsigned int num) {
    return (num >> 1) ^ num;
}

/*
 * From Wikipedia: http://en.wikipedia.org/wiki/Gray_code
 * The purpose of this function is to convert a reflected binary
 * Gray code number to a binary number.
 */
static unsigned int grayToBinary(unsigned int num){
    unsigned int mask;
    for(mask = num >> 1; mask != 0; mask = mask >> 1)
        num = num ^ mask;
    return num;
}

/*
 * Return the Nth bit of an unsigned integer number
 */
static bool getBit(int decimal, int N){

    return decimal & 1 << (N-1);
}

/*
 * Return the number of bits set in an integer
 */
static int countBits(int n) {
  unsigned int c; // c accumulates the total bits set in v
  for (c = 0; n>0; c++)
    n &= n - 1; // clear the least significant bit set
  return c;
}

/*
 * Return the position of the least significant bit that is set
 */
static int leastSignificantBitSet(int x){
  if(x == 0)
      return 0;

  int val = 1;
  while(x>>=1)
      val++;

  return val;
}

//static int get_bit(int decimal, int N){

//    // Shifting the 1 for N-1 bits
//    int constant = 1 << (N-1);

//    // If the bit is set, return 1
//    if( decimal & constant )
//        return 1;
//    else
//        return 0;
//}

static inline unsigned int powi(int num, unsigned int exponent){

    if(exponent == 0)
        return 1;

    float res = num;
    for(unsigned int i=0; i<exponent-1; i++)
        res *= num;

    return res;
}

static inline unsigned int twopowi(unsigned int exponent){

    return 1 << exponent;
}

// Algorithm
AlgorithmGrayCodeHorzVert::AlgorithmGrayCodeHorzVert(unsigned int _screenCols, unsigned int _screenRows) : Algorithm(_screenCols, _screenRows){

    NbitsHorz = ceilf(log2f((float)screenCols));
    NbitsVert =  ceilf(log2f((float)screenRows));
    N = 2 + (NbitsHorz+NbitsVert)*2;

    // all on pattern
    cv::Mat allOn(1, screenCols, CV_8UC3, cv::Scalar::all(255));
    patterns.push_back(allOn);

    // all off pattern
    cv::Mat allOff(1, screenCols, CV_8UC3, cv::Scalar::all(0));
    patterns.push_back(allOff);


    // horizontally encoding patterns
    for(unsigned int p=0; p<NbitsHorz; p++){
        cv::Mat pattern(1, screenCols, CV_8UC3);
        cv::Mat patternInv(1, screenCols, CV_8UC3);

        for(unsigned int j=0; j<screenCols; j++){

            unsigned int jGray = binaryToGray(j);
            // Amplitude of channels
            int bit = (int)getBit(jGray, NbitsHorz-p);
            pattern.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
            int invBit = bit^1;
            patternInv.at<cv::Vec3b>(0,j) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
        }
        patterns.push_back(pattern);
        patterns.push_back(patternInv);
    }

    // vertical encoding patterns
    for(unsigned int p=0; p<NbitsVert; p++){
        cv::Mat pattern(screenRows, 1, CV_8UC3);
        cv::Mat patternInv(screenRows, 1, CV_8UC3);

        for(unsigned int j=0; j<screenRows; j++){

            unsigned int jGray = binaryToGray(j);
            // Amplitude of channels
            int bit = (int)getBit(jGray, NbitsVert-p);
            pattern.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*bit,255.0*bit,255.0*bit);
            int invBit = bit^1;
            patternInv.at<cv::Vec3b>(j,0) = cv::Vec3b(255.0*invBit,255.0*invBit,255.0*invBit);
        }
        patterns.push_back(pattern);
        patterns.push_back(patternInv);
    }

}

cv::Mat AlgorithmGrayCodeHorzVert::getEncodingPattern(unsigned int depth){
    return patterns[depth];
}


static bool sortingLarger(cv::Vec3d i,cv::Vec3d j){ return (i[2]<j[2]);}
static bool sortingEqual(cv::Vec3d i,cv::Vec3d j){ return (i[2]==j[2]);}

static void getIntersectionLabels(const cv::Mat& codeHorz, const cv::Mat& codeVert, int NbitsHorz, int NbitsVert, std::vector< cv::Vec3d >& intersections){

    int nRows = codeHorz.rows;
    int nCols = codeHorz.cols;

    int labelHorz;
    int labelVert;
    int labelHorzRight;
    int labelVertBelow;

    // collect intersections
    for(int row=0; row<nRows+1; row++){
        for(int col=0; col<nCols+1; col++){

            labelHorz = codeHorz.at<int>(row, col);
            labelHorzRight = codeHorz.at<int>(row, col+1);

            labelVert = codeVert.at<int>(row, col);
            labelVertBelow = codeVert.at<int>(row+1, col);

            // labels need to be non-background, and differ in exactly one bit
            if(labelHorz != -1 && labelHorzRight != -1 &&
               countBits(labelHorz^labelHorzRight) == 1 &&
               labelVert != -1 && labelVertBelow != -1 &&
               countBits(labelVert^labelVertBelow) == 1){

                // OVERFLOW??
                double orderingRelation = ((ulong)labelHorz << NbitsHorz+2*NbitsVert) + ((ulong)labelHorzRight << 2*NbitsVert) +
                                          ((ulong)labelVert << NbitsVert) + (ulong)labelVertBelow;
                // store left label column
                intersections.push_back(cv::Vec3d(row, col, orderingRelation));
            }
        }
    }
    // sort
    std::sort(intersections.begin(), intersections.end(), sortingLarger);

    // remove duplicates
    std::vector< cv::Vec3d >::iterator it;
    it = std::unique(intersections.begin(), intersections.end(), sortingEqual);
    intersections.resize(std::distance(intersections.begin(),it));
}

static cv::Vec3b getColorSubpix(const cv::Mat& img, cv::Point2f pt){
    assert(!img.empty());
    assert(img.channels() == 3);

    int x = (int)pt.x;
    int y = (int)pt.y;

    int x0 = cv::borderInterpolate(x,   img.cols, cv::BORDER_REFLECT_101);
    int x1 = cv::borderInterpolate(x+1, img.cols, cv::BORDER_REFLECT_101);
    int y0 = cv::borderInterpolate(y,   img.rows, cv::BORDER_REFLECT_101);
    int y1 = cv::borderInterpolate(y+1, img.rows, cv::BORDER_REFLECT_101);

    float a = pt.x - (float)x;
    float c = pt.y - (float)y;

    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)
                           + (img.at<cv::Vec3b>(y1, x0)[0] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[0] * a) * c);
    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)
                           + (img.at<cv::Vec3b>(y1, x0)[1] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[1] * a) * c);
    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)
                           + (img.at<cv::Vec3b>(y1, x0)[2] * (1.f - a) + img.at<cv::Vec3b>(y1, x1)[2] * a) * c);

    return cv::Vec3b(b, g, r);
}

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){

    assert(frames0.size() == N);
    assert(frames1.size() == N);

    int frameRows = frames0[0].rows;
    int frameCols = frames0[0].cols;

    // gray-scale
    std::vector<cv::Mat> frames0Gray(N);
    std::vector<cv::Mat> frames1Gray(N);
    for(int i=0; i<N; i++){
        cv::cvtColor(frames0[i], frames0Gray[i], CV_RGB2GRAY);
        cv::cvtColor(frames1[i], frames1Gray[i], CV_RGB2GRAY);
    }

    // colors
    cv::Mat color0 = frames0[0];
    cv::Mat color1 = frames1[0];

    // occlusion masks
    cv::Mat occlusion0, occlusion1;
    cv::subtract(frames0Gray[0], frames0Gray[1], occlusion0);
    occlusion0 = occlusion0 > 25;
    cv::subtract(frames1Gray[0], frames1Gray[1], occlusion1);
    occlusion1 = occlusion1 > 25;

    // erode occlusion masks
    cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(3,3));
    cv::erode(occlusion0, occlusion0, strel);
    cv::erode(occlusion1, occlusion1, strel);

//cvtools::writeMat(occlusion0, "occlusion0.mat", "occlusion0");
//cvtools::writeMat(occlusion1, "occlusion1.mat", "occlusion1");

    // decode patterns
    cv::Mat code0Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
    cv::Mat code1Horz(frameRows, frameCols, CV_32S, cv::Scalar(0));
    cv::Mat code0Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));
    cv::Mat code1Vert(frameRows, frameCols, CV_32S, cv::Scalar(0));

    // horizontal codes into gray code
    for(int i=0; i<NbitsHorz; i++){
        cv::Mat bit0;
        cv::subtract(frames0Gray[i*2+2], frames0Gray[i*2+3], bit0);
        bit0 = bit0 > 0;
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
        cv::add(code0Horz, bit0*twopowi(NbitsHorz-i-1), code0Horz, cv::Mat(), CV_32S);

        cv::Mat bit1;
        cv::subtract(frames1Gray[i*2+2], frames1Gray[i*2+3], bit1);
        bit1 = bit1 > 0;
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
        cv::add(code1Horz, bit1*twopowi(NbitsHorz-i-1), code1Horz, cv::Mat(), CV_32S);
    }

    // vertical codes into gray code
    for(int i=0; i<NbitsVert; i++){
        cv::Mat bit0;
        cv::subtract(frames0Gray[i*2+NbitsHorz+2], frames0Gray[i*2+NbitsHorz+3], bit0);
        bit0 = bit0 > 0;
        bit0.convertTo(bit0, CV_32S, 1.0/255.0);
        cv::add(code0Vert, bit0*twopowi(NbitsVert-i-1), code0Vert, cv::Mat(), CV_32S);

        cv::Mat bit1;
        cv::subtract(frames1Gray[i*2+NbitsHorz+2], frames1Gray[i*2+NbitsHorz+3], bit1);
        bit1 = bit1 > 0;
        bit1.convertTo(bit1, CV_32S, 1.0/255.0);
        cv::add(code1Vert, bit1*twopowi(NbitsVert-i-1), code1Vert, cv::Mat(), CV_32S);
    }

//cvtools::writeMat(code0Horz, "code0Horz.mat", "code0Horz");
//cvtools::writeMat(code1Horz, "code1Horz.mat", "code1Horz");
//cvtools::writeMat(code0Vert, "code0Vert.mat", "code0Vert");
//cvtools::writeMat(code1Vert, "code1Vert.mat", "code1Vert");

    // set occluded pixels to -1
    for(int r=0; r<frameRows; r++){
        for(int c=0; c<frameCols; c++){
            if(occlusion0.at<char>(r,c) == 0){
                code0Horz.at<float>(r,c) = -1;
                code0Vert.at<float>(r,c) = -1;
            }
            if(occlusion1.at<char>(r,c) == 0){
                code1Horz.at<float>(r,c) = -1;
                code1Vert.at<float>(r,c) = -1;
            }
        }
    }

    // matching
    std::vector< cv::Vec3d > intersections0, intersections1;

    // intersection data structure containing [floor(row), floor(column), orderingRelation]
    getIntersectionLabels(code0Horz, code0Vert, NbitsHorz, NbitsVert, intersections0);
    getIntersectionLabels(code1Horz, code1Vert, NbitsHorz, NbitsVert, intersections1);

    // match intersections
    std::vector< cv::Vec3d > matches0, matches1;
    int i=0, j=0;

    while(i<intersections0.size() && j<intersections1.size()){
        if(intersections0[i][2] == intersections1[j][2]){
            matches0.push_back(intersections0[i]);
            matches1.push_back(intersections1[j]);
            i += 1;
            j += 1;
        } else if(intersections0[i][2] < intersections1[j][2]){
            i += 1;
        } else if(intersections0[i][2] > intersections1[j][2]){
            j += 1;
        }
    }

    int nMatches = matches0.size();

    if(nMatches < 1){
        Q.resize(0);
        color.resize(0);

        return;
    }

    std::vector<cv::Vec2f> q0(nMatches), q1(nMatches);

    for(int i=0; i<nMatches; i++){
        q0[i] = cv::Vec2f(matches0[i][1], matches0[i][0]);
        q1[i] = cv::Vec2f(matches1[i][1], matches1[i][0]);
    }

    // TODO: subpixel refinement in both horizontal and vertical
//    // subpixel refinement finds the intersection of linear interpolants in the positive/negative pattern
//    for(int i=0; i<matchedEdges0.size(); i++){

//        int level = Nbits - leastSignificantBitSet(matchedEdges0[i][1]^matchedEdges0[i][2]);

//        // refine for camera 0
//        float c0 = matchedEdges0[i][0];
//        float c1 = c0+1;

//        float pos0 = frames0Rect[2*level+2].at<char>(row, c0);
//        float pos1 = frames0Rect[2*level+2].at<char>(row, c1);
//        float neg0 = frames0Rect[2*level+3].at<char>(row, c0);
//        float neg1 = frames0Rect[2*level+3].at<char>(row, c1);

//        float col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
//        q0Rect.push_back(cv::Point2f(col, row));

//        // refine for camera 1
//        c0 = matchedEdges1[i][0];
//        c1 = c0+1;

//        pos0 = frames1Rect[2*level+2].at<char>(row, c0);
//        pos1 = frames1Rect[2*level+2].at<char>(row, c1);
//        neg0 = frames1Rect[2*level+3].at<char>(row, c0);
//        neg1 = frames1Rect[2*level+3].at<char>(row, c1);

//        col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
//        q1Rect.push_back(cv::Point2f(col, row));

//    }




    // retrieve color information (at integer coordinates)
    color.resize(nMatches);
    for(int i=0; i<nMatches; i++){

//        cv::Vec3b c0 = color0.at<cv::Vec3b>(q0[i][1], q0[i][0]);
//        cv::Vec3b c1 = color1.at<cv::Vec3b>(q1[i][1], q1[i][0]);
        cv::Vec3b c0 = getColorSubpix(color0, q0[i]);
        cv::Vec3b c1 = getColorSubpix(color1, q1[i]);

        color[i] = 0.5*c0 + 0.5*c1;
    }

    // triangulate points
    cv::Mat P0(3, 4, CV_32F, cv::Scalar(0.0));
    cv::Mat(calibration.K0).copyTo(P0.colRange(0, 3));

    cv::Mat P1(3, 4, CV_32F), temp(3,4,CV_32F);
    cv::Mat(calibration.R1).copyTo(temp(cv::Range(0,3), cv::Range(0,3)));
    cv::Mat(calibration.T1).copyTo(temp(cv::Range(0,3), cv::Range(3,4)));
    P1 = cv::Mat(calibration.K1) * temp;

    cv::correctMatches(calibration.F, q0, q1, q0, q1);

    cv::Mat QMatHomogenous, QMat;
    cv::triangulatePoints(P0, P1, q0, q1, QMatHomogenous);

    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);
    cvtools::matToPoints3f(QMat, Q);

}