Rev 236 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
//
// Gray Code Structured Light
//
// This implementation closely follows Henrik Aanaes, "Lecture Notes on Computer Vision" (2014).
//
#include "AlgorithmGrayCode.h"
#include <cmath>
#include "cvtools.h"
#include "algorithmtools.h"
// Algorithm
AlgorithmGrayCode::AlgorithmGrayCode(unsigned int _screenCols, unsigned int _screenRows) : Algorithm(_screenCols, _screenRows){
Nbits = ceilf(log2f((float)screenCols)) - 1;
N = 2 + Nbits*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<Nbits; 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+1);
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);
}
}
cv::Mat AlgorithmGrayCode::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 && (grayToBinary(labelRight) == grayToBinary(labelLeft)+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));
}
void AlgorithmGrayCode::get3DPoints(const SMCalibrationParameters &calibration, const std::vector<cv::Mat>& frames0, const std::vector<cv::Mat>& frames1, std::vector<cv::Point3f>& Q, std::vector<cv::Vec3f>& color){
assert(frames0.size() == N);
assert(frames1.size() == N);
int frameRows = frames0[0].rows;
int frameCols = frames0[0].cols;
// rectifying homographies (rotation+projections)
cv::Size frameSize(frameCols, frameRows);
cv::Mat R, T;
// stereoRectify segfaults unless R is double precision
cv::Mat(calibration.R1).convertTo(R, CV_64F);
cv::Mat(calibration.T1).convertTo(T, CV_64F);
cv::Mat R0, R1, P0, P1, QRect;
cv::stereoRectify(calibration.K0, calibration.k0, calibration.K1, calibration.k1, frameSize, R, T, R0, R1, P0, P1, QRect, 0);
// interpolation maps
cv::Mat map0X, map0Y, map1X, map1Y;
cv::initUndistortRectifyMap(calibration.K0, calibration.k0, R0, P0, frameSize, CV_32F, map0X, map0Y);
cv::initUndistortRectifyMap(calibration.K1, calibration.k1, R1, P1, frameSize, CV_32F, map1X, map1Y);
// gray-scale and remap
std::vector<cv::Mat> frames0Rect(N);
std::vector<cv::Mat> frames1Rect(N);
for(unsigned int i=0; i<N; i++){
cv::Mat temp;
cv::cvtColor(frames0[i], temp, CV_RGB2GRAY);
cv::remap(temp, frames0Rect[i], map0X, map0Y, CV_INTER_LINEAR);
cv::cvtColor(frames1[i], temp, CV_RGB2GRAY);
cv::remap(temp, frames1Rect[i], map1X, map1Y, CV_INTER_LINEAR);
}
#ifdef QT_DEBUG
cvtools::writeMat(frames0Rect[0], "frames0Rect_0.mat", "frames0Rect_0");
cvtools::writeMat(frames0[0], "frames0_0.mat", "frames0_0");
cvtools::writeMat(frames0Rect[22], "frames0Rect_22.mat", "frames0Rect_22");
cvtools::writeMat(frames0Rect[23], "frames0Rect_23.mat", "frames0Rect_23");
cv::imwrite("frames0[0].png", frames0[0]);
cv::imwrite("frames0Rect[0].png", frames0Rect[0]);
cv::imwrite("frames1[0].png", frames1[0]);
cv::imwrite("frames1Rect[0].png", frames1Rect[0]);
#endif
// color remap
cv::Mat color0Rect, color1Rect;
cv::remap(frames0[0], color0Rect, map0X, map0Y, CV_INTER_LINEAR);
cv::remap(frames1[0], color1Rect, map1X, map1Y, CV_INTER_LINEAR);
int frameRectRows = frames0Rect[0].rows;
int frameRectCols = frames0Rect[0].cols;
// occlusion masks
cv::Mat occlusion0Rect, occlusion1Rect;
cv::subtract(frames0Rect[0], frames0Rect[1], occlusion0Rect);
occlusion0Rect = (occlusion0Rect > 0.1) & (occlusion0Rect < 0.99);
cv::subtract(frames1Rect[0], frames1Rect[1], occlusion1Rect);
occlusion1Rect = (occlusion1Rect > 0.1) & (occlusion1Rect < 0.99);
// erode occlusion masks
cv::Mat strel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2,2));
cv::erode(occlusion0Rect, occlusion0Rect, strel);
cv::erode(occlusion1Rect, occlusion1Rect, strel);
// // correct for projector inversion error
// cv::Mat W;
// cv::add(frames0Rect[0], frames0Rect[1], W, cv::noArray(), CV_32F);
// for(int i=2; i<N; i+=2){
// cv::Mat S, E;
// cv::add(frames0Rect[i], frames0Rect[i+1], S, cv::noArray(), CV_32F);
// cv::subtract(W, S, E, cv::noArray(), CV_32F);
// E *= 0.5;
// cv::add(frames0Rect[i], E, frames0Rect[i], cv::noArray(), CV_16UC1);
// cv::add(frames0Rect[i+1], E, frames0Rect[i+1], cv::noArray(), CV_16UC1);
// }
// // correct for texture modulation and ambient
// cv::Mat A0 = frames0Rect[1];
// cv::Mat M0 = frames0Rect[0]-frames0Rect[1];
// cv::divide(256.0, M0, M0, CV_32F);
// cv::Mat A1 = frames1Rect[1];
// cv::Mat M1 = frames1Rect[0]-frames1Rect[1];
// cv::divide(256.0, M1, M1, CV_32F);
// for(int i=2; i<N; i++){
// cv::multiply(frames0Rect[i]-A0, M0, frames0Rect[i], 1.0, CV_8UC1);
// cv::multiply(frames1Rect[i]-A1, M1, frames1Rect[i], 1.0, CV_8UC1);
// }
// decode patterns
cv::Mat code0Rect(frameRectRows, frameRectCols, CV_32S, cv::Scalar(0));
cv::Mat code1Rect(frameRectRows, frameRectCols, CV_32S, cv::Scalar(0));
// into gray code
for(unsigned int i=0; i<Nbits; i++){
cv::Mat temp, bit0, bit1;
cv::compare(frames0Rect[i*2+2], frames0Rect[i*2+3], temp, cv::CMP_GT);
temp.convertTo(bit0, CV_32S, 1.0/255.0);
cv::add(code0Rect, bit0*twopowi(Nbits-i-1), code0Rect, cv::noArray(), CV_32S);
cv::compare(frames1Rect[i*2+2], frames1Rect[i*2+3], temp, cv::CMP_GT);
temp.convertTo(bit1, CV_32S, 1.0/255.0);
cv::add(code1Rect, bit1*twopowi(Nbits-i-1), code1Rect, cv::noArray(), CV_32S);
}
//cvtools::writeMat(code0Rect, "code0Rect.mat", "code0Rect");
//cvtools::writeMat(code1Rect, "code1Rect.mat", "code1Rect");
#ifdef QT_DEBUG
// convert to standard binary
cv::Mat code0Binary(code0Rect.rows, code0Rect.cols, CV_32F);
cv::Mat code1Binary(code1Rect.rows, code1Rect.cols, CV_32F);
for(int r=0; r<frameRectRows; r++){
for(int c=0; c<frameRectCols; c++){
if(code0Rect.at<int>(r,c) != -1)
code0Binary.at<float>(r,c) = grayToBinary(code0Rect.at<int>(r,c));
if(code1Rect.at<int>(r,c) != -1)
code1Binary.at<float>(r,c) = grayToBinary(code1Rect.at<int>(r,c));
}
}
cvtools::writeMat(code0Binary, "code0Binary.mat", "code0Binary");
cvtools::writeMat(code1Binary, "code1Binary.mat", "code1Binary");
#endif
// // threshold on vertical discontinuities (due to imperfect rectification)
// cv::Mat edges0;
// cv::Sobel(code0Binary, edges0, -1, 0, 1, 5);
// occlusion0Rect = occlusion0Rect & (abs(edges0) < 50);
// cv::Mat edges1;
// cv::Sobel(code1Binary, edges1, -1, 0, 1, 5);
// occlusion1Rect = occlusion1Rect & (abs(edges1) < 50);
// set occluded pixels to -1
for(int r=0; r<frameRectRows; r++){
for(int c=0; c<frameRectCols; c++){
if(occlusion0Rect.at<unsigned char>(r,c) == 0)
code0Rect.at<int>(r,c) = -1;
if(occlusion1Rect.at<unsigned char>(r,c) == 0)
code1Rect.at<int>(r,c) = -1;
}
}
#ifdef QT_DEBUG
cvtools::writeMat(code0Rect, "code0Rect.mat", "code0Rect");
cvtools::writeMat(code1Rect, "code1Rect.mat", "code1Rect");
#endif
// matching
std::vector<cv::Vec2f> q0, q1;
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;
unsigned 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(unsigned 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<float>(row, c0);
float pos1 = frames0Rect[2*level+2].at<float>(row, c1);
float neg0 = frames0Rect[2*level+3].at<float>(row, c0);
float neg1 = frames0Rect[2*level+3].at<float>(row, c1);
float col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
q0.push_back(cv::Point2f(col, row));
// refine for camera 1
c0 = matchedEdges1[i][0];
c1 = c0+1;
pos0 = frames1Rect[2*level+2].at<float>(row, c0);
pos1 = frames1Rect[2*level+2].at<float>(row, c1);
neg0 = frames1Rect[2*level+3].at<float>(row, c0);
neg1 = frames1Rect[2*level+3].at<float>(row, c1);
col = c0 + (pos0 - neg0)/(neg1 - neg0 - pos1 + pos0);
q1.push_back(cv::Point2f(col, row));
}
}
int nMatches = q0.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::Vec3f c0 = color0Rect.at<cv::Vec3f>(q0[i][1], q0[i][0]);
cv::Vec3f c1 = color1Rect.at<cv::Vec3f>(q1[i][1], q1[i][0]);
color[i] = 0.5*c0 + 0.5*c1;
}
// Triangulate by means of disparity projection
Q.resize(q0.size());
cv::Matx44f QRectx = cv::Matx44f(QRect);
cv::Matx33f R0invx = cv::Matx33f(cv::Mat(R0.t()));
#pragma omp parallel for
for(unsigned int i=0; i<q0.size(); i++){
float disparity = q0[i][0]-q1[i][0];
cv::Vec4f Qih = QRectx*cv::Vec4f(q0[i][0], q0[i][1], disparity, 1.0);
float winv = float(1.0)/Qih[3];
Q[i] = R0invx * cv::Point3f(Qih[0]*winv, Qih[1]*winv, Qih[2]*winv);
}
}