雙目相機
在雙目相機中基于相似三角形原理用視差計算深度
圖片.png
disparity=x?x′=BF/Z
//十四講中示例
// 根據(jù)雙目模型計算 point 的位置
double x = (u - cx) / fx;
double y = (v - cy) / fy;
double depth = fx * b / (disparity.at<float>(v, u));
point[0] = x * depth;
point[1] = y * depth;
point[2] = depth;
單目相機
在單目相機中,已估計有相機RT 位姿冻河,使用三角測量計算一點的空間位置阵幸。
圖片.png
但是由于誤差的存在 不一定能夠準(zhǔn)確投影
圖片.png
所以一般使用最小二乘法計算
圖片.png
//十四講示例
void triangulation (
const vector< KeyPoint >& keypoint_1,
const vector< KeyPoint >& keypoint_2,
const std::vector< DMatch >& matches,
const Mat& R, const Mat& t,
vector< Point3d >& points )
{
Mat T1 = (Mat_<float> (3,4) <<
1,0,0,0,
0,1,0,0,
0,0,1,0);
Mat T2 = (Mat_<float> (3,4) <<
R.at<double>(0,0), R.at<double>(0,1), R.at<double>(0,2), t.at<double>(0,0),
R.at<double>(1,0), R.at<double>(1,1), R.at<double>(1,2), t.at<double>(1,0),
R.at<double>(2,0), R.at<double>(2,1), R.at<double>(2,2), t.at<double>(2,0)
);
Mat K = ( Mat_<double> ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );
vector<Point2f> pts_1, pts_2;
for ( DMatch m:matches )
{
// 將像素坐標(biāo)轉(zhuǎn)換至相機坐標(biāo)
pts_1.push_back ( pixel2cam( keypoint_1[m.queryIdx].pt, K) );
pts_2.push_back ( pixel2cam( keypoint_2[m.trainIdx].pt, K) );
}
//結(jié)果是齊次坐標(biāo)系的形式
Mat pts_4d;
//使用OpenCV的函數(shù)求解空間位置
cv::triangulatePoints( T1, T2, pts_1, pts_2, pts_4d );
// 轉(zhuǎn)換成非齊次坐標(biāo)
for ( int i=0; i<pts_4d.cols; i++ )
{
Mat x = pts_4d.col(i);
x /= x.at<float>(3,0); // 歸一化
Point3d p (
x.at<float>(0,0),
x.at<float>(1,0),
x.at<float>(2,0)
);
points.push_back( p );
}
}