Subversion Repositories seema-scanner

Rev

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

#include "AlgorithmGrayCodeHQ.h"
#include <cmath>
#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
AlgorithmGrayCodeHQ::AlgorithmGrayCodeHQ(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, Nbits-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, Nbits-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 AlgorithmGrayCodeHQ::getEncodingPattern(unsigned int depth){
    return patterns[depth];
}


bool sortingLarger(cv::Vec4i i,cv::Vec4i j){ return (i[3]<j[3]);}
bool sortingEqual(cv::Vec4i i,cv::Vec4i j){ return (i[3]==j[3]);}
void getEdgeLabels(const cv::Mat& scanLine, int Nbits, std::vector<cv::Vec4i>& edges){

    int nCols = scanLine.cols;
    const int *data = scanLine.ptr<const int>(0);

    int labelLeft;
    int labelRight = data[0];

    // collect edges
    for(int col=1; col<nCols; col++){

        labelLeft = labelRight;
        labelRight = data[col];

        // labels need to be non-background, and differ in exactly one bit
        if(labelLeft != -1 && labelRight != -1 && countBits(labelLeft^labelRight) == 1){
            int orderingRelation = (labelLeft << Nbits) + labelRight;
            // store left label column
            edges.push_back(cv::Vec4i(col-1, labelLeft, labelRight, orderingRelation));
        }
    }

    // sort
    std::sort(edges.begin(), edges.end(), sortingLarger);

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

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 AlgorithmGrayCodeHQ::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, CV_RGB2GRAY);
        cv::cvtColor(frames1[i], frames1Gray, 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(Nbits-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(Nbits-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(Nbits-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(Nbits-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;
            }
        }
    }



    // TODO: REWRITE TO PERFORM HORIZONTAL + VERTICAL MATCHING

//    // matching
//    std::vector<cv::Vec2f> q0Rect, q1Rect;
//    for(int row=0; row<frameRectRows; row++){

//        // edge data structure containing [floor(column), labelLeft, labelRight, orderingRelation]
//        std::vector<cv::Vec4i> edges0, edges1;

//        // sorted, unique edges
//        getEdgeLabels(code0Rect.row(row), Nbits, edges0);
//        getEdgeLabels(code1Rect.row(row), Nbits, edges1);

//        // match edges
//        std::vector<cv::Vec4i> matchedEdges0, matchedEdges1;
//        int i=0, j=0;
//        while(i<edges0.size() && j<edges1.size()){

//            if(edges0[i][3] == edges1[j][3]){
//                matchedEdges0.push_back(edges0[i]);
//                matchedEdges1.push_back(edges1[j]);
//                i += 1;
//                j += 1;
//            } else if(edges0[i][3] < edges1[j][3]){
//                i += 1;
//            } else if(edges0[i][3] > edges1[j][3]){
//                j += 1;
//            }
//        }

//        // crude 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));

//        }

//    }

//    int nMatches = q0Rect.size();

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

//        return;
//    }

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

//        cv::Vec3b c0 = color0Rect.at<cv::Vec3b>(q0Rect[i][1], q0Rect[i][0]);
//        cv::Vec3b c1 = color1Rect.at<cv::Vec3b>(q1Rect[i][1], q1Rect[i][0]);
////        cv::Vec3b c0 = getColorSubpix(color0Rect, q0Rect[i]);
////        cv::Vec3b c1 = getColorSubpix(color1Rect, q0Rect[i]);

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

//    // triangulate points
//    cv::Mat QMatHomogenous, QMat;
////    cv::Mat C0 = P0.clone();
////    cv::Mat C1 = P1.clone();
////    C0.colRange(0, 3) = C0.colRange(0, 3)*R0;
////    C1.colRange(0, 3) = C1.colRange(0, 3)*R1.t();
//    cv::triangulatePoints(P0, P1, q0Rect, q1Rect, QMatHomogenous);
//    cvtools::convertMatFromHomogeneous(QMatHomogenous, QMat);

//    // undo rectifying rotation
//    cv::Mat R0Inv;
//    cv::Mat(R0.t()).convertTo(R0Inv, CV_32F);
//    QMat = R0Inv*QMat;

//    cvtools::matToPoints3f(QMat, Q);

}