昌吉 建设局 网站,张店学校网站建设方案,做ppt素材的网站,wordpress短视频模版本文是基于 OpenCV4.80 进行的#xff0c;关于环境的配置可能之后会单独说#xff0c;先提一嘴 vcpkg 真好用 1 大致流程
从多张图片逐步生成稀疏点云#xff0c;这个过程通常包括以下步骤#xff1a; 初始重建#xff1a; 初始两张图片的选择十分重要#xff0c;这是整… 本文是基于 OpenCV4.80 进行的关于环境的配置可能之后会单独说先提一嘴 vcpkg 真好用 1 大致流程
从多张图片逐步生成稀疏点云这个过程通常包括以下步骤 初始重建 初始两张图片的选择十分重要这是整个流程的基础后续的增图都是在这两张图片的基础上进行的 对于输入图像首先需要提取特征点例如SIFT、SURF或ORB特征点。然后通过匹配不同图像中的特征点建立它们之间的对应关系通过两张图像之间的本质矩阵 E 估计相机的外参矩阵旋转矩阵 R 和平移向量 T 然后使用三角测量法计算出一些初始的三维点 具体操作可以查看我前面的博客 增量式重建 从这开始逐步增加图像逐渐扩展三维点云 添加新的图像将新的图像加载到重建流程中特征提取和匹配对新的图像提取特征点并与先前图像匹配以获得新的匹配关系位姿估计估计新图像相对于先前图像的相机位姿通常使用 PnPPerspective-n-Point—— 在已知相机内参数 K 的前提下用该角度下的三维点object_points与它们对应的图像点image_points坐标估算出此时拍摄位置的信息三维点三角测量使用新的匹配对和估计的位姿RT来三角测量生成新的三维点。点云合并将新生成的三维点与先前的点云进行合并构建一个更大的稀疏点云 全局点云优化在稀疏点云已经生成后可以使用全局点云优化技术例如Bundle Adjustment来提高点云的准确性
2 准备代码
之前文章中我们讲所有代码都挤到了main函数中十分不美观现在我们进行一下代码的优化 由于才学C比较菜请见谅 2.1 Include.h
这里包含了所有用到的头文件和宏方便之后使用
由于之后要用 Bundle Adjustment所以引入了 ceres具体环境配置之后可能会说真的比较麻烦强烈推荐 vcpkg 其中大量的 #define 和 #pragma warning(disable: 4996) 都是关于 ceres 的报错的
#ifndef INCLUDES_H
#define INCLUDES_H#define GLOG_NO_ABBREVIATED_SEVERITIES
#define _CRT_NONSTDC_NO_DEPRECATE
#define NOMINMAX
#define _CRT_NONSTDC_NO_WARNINGS
#pragma warning(disable: 4996)#include opencv2/opencv.hpp
#include iostream
#include vector
#include fstream
#include ceres/ceres.h
#include ceres/rotation.husing namespace cv;
using namespace std;
#endif // !INCLUDES_H#pragma once2.2 Constructor
Constructor 类其中包含了三维重建的几个关键步骤的函数
findCamera初始构建使用的求取 E 矩阵和RT其中包括了RANSACmaskoutPoints通过内点标记mask来对点进行筛选pointsReconstruct通过 RT 匹配点来进行三角化生成三维点云
Constructor.h
#ifndef CONSTRUCTOR_H
#define CONSTRUCTOR_H#include Includes.h
#include Images.hclass Constructor
{
public:// 输入K图1的匹配点图2的匹配点输出RT点经过筛选static void findCamera(Mat K, vectorPoint2f point1, vectorPoint2f point2, Mat output_R, Mat output_T, vectoruchar mask);// 输入图匹配点内点标记mask返回mask后的vectorPoint2f匹配点static void maskoutPoints(vectorPoint2f input_points, vectoruchar input_mask);// 输入图一的RT匹配点图二的RT匹配点返回vectorPoint3f三维点static vectorPoint3d pointsReconstruct(const Mat K, Mat R1, Mat T1, Mat R2, Mat T2, vectorPoint2f points1, vectorPoint2f points2);
};#endif // !CONSTRUCTOR_H#pragma onceConstructor.cpp
#include Constructor.hvoid Constructor::findCamera(Mat K, vectorPoint2f point1, vectorPoint2f point2, Mat output_R, Mat output_T, vectoruchar mask)
{vectoruchar inliers;Mat F;F findFundamentalMat(point1, point2, inliers, FM_RANSAC, 1, 0.5);Mat E K.t() * F * K;//Mat E findEssentialMat(point1, point2, K, RANSAC, 0.6, 1.0, inliners);mask inliers;// 根据内点筛选出新的匹配点Constructor::maskoutPoints(point1, inliers);Constructor::maskoutPoints(point2, inliers);// 分解E矩阵获取RT矩阵int pass_count recoverPose(E, point1, point2, K, output_R, output_T);
}void Constructor::maskoutPoints(vectorPoint2f input_points, vectoruchar input_mask)
{vectorPoint2f temp_points(input_points);input_points.clear();for (int i 0; i temp_points.size(); i){if (input_mask[i]){input_points.push_back(temp_points[i]);}}
}vectorPoint3d Constructor::pointsReconstruct(const Mat K, Mat R1, Mat T1, Mat R2, Mat T2, vectorPoint2f points1, vectorPoint2f points2)
{// 构造投影矩阵Mat proj1(3, 4, CV_32FC1);Mat proj2(3, 4, CV_32FC1);// 将旋转矩阵和平移向量合并为投影矩阵R1.convertTo(proj1(Range(0, 3), Range(0, 3)), CV_32FC1);T1.convertTo(proj1.col(3), CV_32FC1);R2.convertTo(proj2(Range(0, 3), Range(0, 3)), CV_32FC1);T2.convertTo(proj2.col(3), CV_32FC1);// 将内参矩阵与投影矩阵相乘得到最终的投影矩阵Mat fK;K.convertTo(fK, CV_32FC1);proj1 fK * proj1;proj2 fK * proj2;// 三角化得到齐次坐标Mat point4D_homogeneous(4, points1.size(), CV_64F);triangulatePoints(proj1, proj2, points1, points2, point4D_homogeneous);// 将齐次坐标转换为三维坐标vectorPoint3d point3D;point3D.clear();point3D.reserve(point4D_homogeneous.cols);for (int i 0; i point4D_homogeneous.cols; i){Matfloat col point4D_homogeneous.col(i);col / col(3);point3D.push_back(Point3d(col(0), col(1), col(2)));}// 将三维坐标存储在Point3d向量中并返回return point3D;
}2.3 Image
为了增图我们需要存储图像中每个特征点在空间中的对应点—— correspond_struct_idx
Image 类其中有成员变量
Mat image—— 存储图像vectorKeyPoint keyPoints—— 存储特征点Mat descriptor—— 存储特征描述符vectorint correspond_struct_idx—— 匹配点所对应的空间点在点云中的索引vectorPoint2f matchedPoints—— 存储匹配点vectorVec3b colors—— 存储匹配点的颜色信息Mat R, T—— 存储相机的旋转矩阵和平移向量
同时还有几个关于图像处理的重要函数
Images构造函数读取图像时就进行了特征点的提取matchFeatures匹配特征点findColor提取颜色信息getObjPointsAndImgPoints找出当前匹配中已经在点云中的点获取 object_points以及 image_points —— 为 PnP 做准备
Image.h
#ifndef IMAGES_H
#define IMAGES_H#include Includes.hclass Images
{
public:Mat image; // 存储图像vectorKeyPoint keyPoints; // 存储特征点Mat descriptor; // 存储特征描述符vectorint correspond_struct_idx; // 匹配点所对应的空间点在点云中的索引vectorPoint2f matchedPoints; // 存储匹配点vectorVec3b colors; // 存储匹配点的颜色信息Mat R, T; // 存储相机的旋转矩阵和平移向量vectorPoint3f object_points; // 前一张图中匹配点对应的三维点vectorPoint2f image_points; // 在现图像中对应的像素点// 构造函数从指定路径读取图像并提取SIFT特征点和描述符Images(string const image_paths);// 特征匹配函数将当前图像与另一个图像进行特征匹配void matchFeatures(Images otherImage, vectorDMatch outputMatches);// 从匹配点中提取颜色信息void findColor();// 遍历当前匹配找出当前匹配中已经在点云中的点获取object_points以及image_pointsvoid getObjPointsAndImgPoints(vectorDMatch matches, vectorPoint3d all_reconstructed_points, Images preImage);
};#endif // !IMAGES_H
#pragma onceImage.cpp
#include Images.hImages::Images(string const image_path)
{// 读取图像this-image imread(image_path);if (this-image.empty()) {cout Could not read image: image_path endl;}// 提取SIFT特征点和描述符PtrSIFT sift SIFT::create(0, 17, 0.0000000001, 16);sift-detectAndCompute(this-image, noArray(), this-keyPoints, this-descriptor);for (int i 0; i keyPoints.size(); i){correspond_struct_idx.push_back(-1);}
}void Images::findColor()
{// 遍历所有匹配点for (Point2f Points : this-matchedPoints){ // 获取像素点的颜色Vec3b color this-image.atVec3b(Points.y, Points.x);// 将颜色存储在颜色向量中this-colors.push_back(color);}
}void Images::matchFeatures(Images otherImage, vectorDMatch outputMatches)
{// 清空匹配点otherImage.matchedPoints.clear();this-matchedPoints.clear();vectorvectorDMatch matches;FlannBasedMatcher matcher;// 使用FlannBasedMatcher进行特征匹配matcher.knnMatch(this-descriptor, otherImage.descriptor, matches, 2);// 计算最小距离float min_dist FLT_MAX;for (int r 0; r matches.size(); r){// 如果最近邻距离大于次近邻距离的2.5倍则跳过该匹配点if (matches[r][0].distance 2.5 * matches[r][1].distance){// 计算最小距离float dist matches[r][0].distance;if (dist min_dist){min_dist dist;}}}// 筛选出好的匹配点for (int i 0; i matches.size(); i){if (matches[i][0].distance 0.76 * matches[i][1].distance matches[i][0].distance 8 * max(min_dist, 10.0f)){outputMatches.push_back(matches[i][0]);}}// 将匹配点存储在matchedPoints向量中for (int i 0; i outputMatches.size(); i){this-matchedPoints.push_back(this-keyPoints[outputMatches[i].queryIdx].pt);otherImage.matchedPoints.push_back(otherImage.keyPoints[outputMatches[i].trainIdx].pt);}
}// 从匹配点中获取三维空间点和图像点
void Images::getObjPointsAndImgPoints(vectorDMatch matches, vectorPoint3d all_reconstructed_points, Images preImage)
{// 清空object_points和image_pointsthis-object_points.clear();this-image_points.clear();// 遍历所有匹配点for (int i 0; i matches.size(); i){// 获取匹配点在前一张图像中对应的三维空间点的索引int matched_world_point_indices preImage.correspond_struct_idx[matches[i].queryIdx];// 如果匹配点在前一张图像中对应的三维空间点存在if (matched_world_point_indices 0){// 将其前一张图像中的三维点添加到object_points中this-object_points.push_back(all_reconstructed_points[matched_world_point_indices]);// 将匹配点该新图像的二维点添加到image_points中this-image_points.push_back(this-keyPoints[matches[i].trainIdx].pt);}}
}
3 具体实现
在先前的两张图片的初始三维点云的构建的基础上我们来实现多张图的增量构建
3.1 初始构建
在前面几篇博客中已经详细讲述过了匹配用计算 E 矩阵的方式求得相机外参 RT进行三角化构建点云
特别为了后面的增图重建我们需要记录初始两张图各个点和点云的关系
void initConstruction(vectorImages initImages, vectorPoint3d all_reconstructed_points, vectorVec3b all_points_colors)
{initImages.push_back(*(new Images(INIT_IMG_PATH1)));initImages.push_back(*(new Images(INIT_IMG_PATH2)));vectorDMatch matches;initImages[0].matchFeatures(initImages[1], matches);vectoruchar mask;Constructor::findCamera(K, initImages[0].matchedPoints, initImages[1].matchedPoints, initImages[1].R, initImages[1].T, mask);initImages[0].R Mat::eye(3, 3, CV_64FC1);initImages[0].T Mat::zeros(3, 1, CV_64FC1);all_reconstructed_points Constructor::pointsReconstruct(K, initImages[0].R, initImages[0].T, initImages[1].R, initImages[1].T, initImages[0].matchedPoints, initImages[1].matchedPoints);initImages[1].findColor();for (int i 0; i initImages[1].colors.size(); i){all_points_colors.push_back(initImages[1].colors[i]);}// 根据mask来记录初始两张图各个点和点云的关系int idx 0;for (int i 0; i matches.size(); i){if (mask[i]){initImages[0].correspond_struct_idx[matches[i].queryIdx] idx;initImages[1].correspond_struct_idx[matches[i].trainIdx] idx;idx;}}
}3.2 增量构建 创建subImageBag然后将initImages[1]添加到容器中即表示initImages中的第二张图像数组索引为1将与后续进行比较否则下一张图添加进来跟谁进行匹配呢 循环遍历sub_image_paths容器中的图像文件路径 在循环中为每个图像文件路径创建一个新的Images并将其添加到subImageBag容器中。这样容器subImageBag中就包含了多张图像其中第一张图像是初始图像对的第二张其余图像是逐步添加的 调用addImageConstruction函数将subImageBag作为参数传递以及用于存储稀疏点云的all_reconstructed_points和点云颜色的all_points_colors 循环遍历subImageBag容器中的每个图像从索引1开始因为第一个图像是初始图像用于了初始构建跳过 对于每对相邻的图像执行以下操作 使用matchFeatures方法找到两个相邻图像之间的特征点匹配关系并将匹配结果存储在matches容器中 使用getObjPointsAndImgPoints方法获取匹配的特征点对应的三维点和图像点 —— 为 PnP 做准备 通过RANSAC筛选使用findCamera方法筛选匹配点并生成一个mask用于标记有效的匹配点只是为了筛选罢了 使用solvePnPRansac方法估计新图像的相机位姿获得RT 转换旋转向量为旋转矩阵solvePnPRansac得到的是 r 向量 使用pointsReconstruct方法重建新图像与前图像之间的三维点并将结果存储在new_restructure_points中 使用findColor方法获取新图像中点的颜色信息 记录初始两张图各个点和点云的关系 遍历matches根据mask中的标记将新生成的点与初始两张图像的各个点和点云的关系进行记录维护点与点云之间的对应关系 最后将新生成的三维点new_restructure_points以及它们的颜色信息添加到all_reconstructed_points和all_points_colors中不断扩展点云
void addImageConstruction(vectorImages subImageBag, vectorPoint3d all_reconstructed_points, vectorVec3b all_points_colors)
{for (int i 1; i subImageBag.size(); i){cout i endl;vectorDMatch matches;subImageBag[i - 1].matchFeatures(subImageBag[i], matches);subImageBag[i].getObjPointsAndImgPoints(matches, all_reconstructed_points, subImageBag[i - 1]);// 只是为了进行RANSAC筛选匹配点和获取maskvectoruchar mask;Mat discardR, discardT;Constructor::findCamera(K, subImageBag[i - 1].matchedPoints, subImageBag[i].matchedPoints, discardR, discardT, mask);solvePnPRansac(subImageBag[i].object_points, subImageBag[i].image_points, K, noArray(), subImageBag[i].R, subImageBag[i].T);Rodrigues(subImageBag[i].R, subImageBag[i].R);vectorPoint3d new_restructure_points;new_restructure_points Constructor::pointsReconstruct(K, subImageBag[i - 1].R, subImageBag[i - 1].T, subImageBag[i].R, subImageBag[i].T, subImageBag[i - 1].matchedPoints, subImageBag[i].matchedPoints);subImageBag[i].findColor();// 记录初始两张图各个点和点云的关系int idx 0;for (int k 0; k matches.size(); k){if (mask[k]){subImageBag[i - 1].correspond_struct_idx[matches[k].queryIdx] all_reconstructed_points.size() idx;subImageBag[i].correspond_struct_idx[matches[k].trainIdx] all_reconstructed_points.size() idx;idx;}}for (int k 0; k new_restructure_points.size(); k){all_reconstructed_points.push_back(new_restructure_points[k]);all_points_colors.push_back(subImageBag[i].colors[k]);}}
}3.3 完整main.cpp
// 定义图像文件路径和保存结果的路径
//#define INIT_IMG_PATH1 test_img\\images\\100_7103.jpg
//#define INIT_IMG_PATH2 test_img\\images\\100_7104.jpg
#define INIT_IMG_PATH1 test_img\\First stage\\B25.jpg
#define INIT_IMG_PATH2 test_img\\First stage\\B24.jpg
#define PLY_SAVE_PATH test_img\\results\\output.ply#include Includes.h
#include Images.h
#include Constructor.h//const Mat K (Mat_double(3, 3) 2905.88, 0, 1416, 0, 2905.88, 1064, 0, 0, 1);
const Mat K (Mat_double(3, 3) 719.5459, 0, 0, 0, 719.5459, 0, 0, 0, 1);//const vectorstring sub_image_paths { /*test_img\\images\\100_7100.jpg, test_img\\images\\100_7101.jpg, test_img\\images\\100_7102.jpg,*/ /*test_img\\images\\100_7103.jpg, test_img\\images\\100_7104.jpg,*/ test_img\\images\\100_7105.jpg, test_img\\images\\100_7106.jpg, test_img\\images\\100_7107.jpg, test_img\\images\\100_7108.jpg, test_img\\images\\100_7109.jpg/*, test_img\\images\\100_7110.jpg*/ };const vectorstring sub_image_paths { test_img\\First stage\\B23.jpg, test_img\\First stage\\B22.jpg, test_img\\First stage\\B21.jpg };
void initConstruction(vectorImages initImages, vectorPoint3d all_reconstructed_points, vectorVec3b all_points_colors)
{initImages.push_back(*(new Images(INIT_IMG_PATH1)));initImages.push_back(*(new Images(INIT_IMG_PATH2)));vectorDMatch matches;initImages[0].matchFeatures(initImages[1], matches);vectoruchar mask;Constructor::findCamera(K, initImages[0].matchedPoints, initImages[1].matchedPoints, initImages[1].R, initImages[1].T, mask);initImages[0].R Mat::eye(3, 3, CV_64FC1);initImages[0].T Mat::zeros(3, 1, CV_64FC1);all_reconstructed_points Constructor::pointsReconstruct(K, initImages[0].R, initImages[0].T, initImages[1].R, initImages[1].T, initImages[0].matchedPoints, initImages[1].matchedPoints);initImages[1].findColor();for (int i 0; i initImages[1].colors.size(); i){all_points_colors.push_back(initImages[1].colors[i]);}// 根据mask来记录初始两张图各个点和点云的关系int idx 0;for (int i 0; i matches.size(); i){if (mask[i]){initImages[0].correspond_struct_idx[matches[i].queryIdx] idx;initImages[1].correspond_struct_idx[matches[i].trainIdx] idx;idx;}}
}void addImageConstruction(vectorImages subImageBag, vectorPoint3d all_reconstructed_points, vectorVec3b all_points_colors)
{for (int i 1; i subImageBag.size(); i){cout i endl;vectorDMatch matches;subImageBag[i - 1].matchFeatures(subImageBag[i], matches);subImageBag[i].getObjPointsAndImgPoints(matches, all_reconstructed_points, subImageBag[i - 1]);// 只是为了进行RANSAC筛选匹配点和获取maskvectoruchar mask;Mat discardR, discardT;Constructor::findCamera(K, subImageBag[i - 1].matchedPoints, subImageBag[i].matchedPoints, discardR, discardT, mask);solvePnPRansac(subImageBag[i].object_points, subImageBag[i].image_points, K, noArray(), subImageBag[i].R, subImageBag[i].T);Rodrigues(subImageBag[i].R, subImageBag[i].R);vectorPoint3d new_restructure_points;new_restructure_points Constructor::pointsReconstruct(K, subImageBag[i - 1].R, subImageBag[i - 1].T, subImageBag[i].R, subImageBag[i].T, subImageBag[i - 1].matchedPoints, subImageBag[i].matchedPoints);subImageBag[i].findColor();// 记录初始两张图各个点和点云的关系int idx 0;for (int k 0; k matches.size(); k){if (mask[k]){subImageBag[i - 1].correspond_struct_idx[matches[k].queryIdx] all_reconstructed_points.size() idx;subImageBag[i].correspond_struct_idx[matches[k].trainIdx] all_reconstructed_points.size() idx;idx;}}for (int k 0; k new_restructure_points.size(); k){all_reconstructed_points.push_back(new_restructure_points[k]);all_points_colors.push_back(subImageBag[i].colors[k]);}}}int main()
{try{vectorImages initImages;vectorPoint3d all_reconstructed_points;vectorVec3b all_points_colors;initConstruction(initImages, all_reconstructed_points, all_points_colors);vectorImages subImageBag;subImageBag.push_back(initImages[1]);for (auto image_path : sub_image_paths){subImageBag.push_back(Images(image_path));}addImageConstruction(subImageBag, all_reconstructed_points, all_points_colors); // 手动输出点云ply文件std::ofstream plyFile(PLY_SAVE_PATH);// ply的头部信息plyFile ply\n;plyFile format ascii 1.0\n;plyFile element vertex all_reconstructed_points.size() \n;plyFile property float x\n;plyFile property float y\n;plyFile property float z\n;plyFile property uchar blue\n;plyFile property uchar green\n;plyFile property uchar red\n;plyFile end_header\n;// 写入点云数据for (int i 0; i all_reconstructed_points.size(); i){cv::Vec3b color all_points_colors[i];cv::Point3f point all_reconstructed_points[i];plyFile point.x point.y point.z static_castint(color[0]) static_castint(color[1]) static_castint(color[2]) std::endl;}plyFile.close();return 0;}catch (Exception e){cout e.msg endl;}}4 总结注意 源码 即上面给出的 Include.hConstructor.hConstructor.cppImage.hImage.cppmain.cpp 增量加图前两张初始图的构建 增量加图构造后 注意
目前只是完成了基本流程有很多地方都需要优化比如
SIFT 的参数设置RANSAC 的参数设置初始图片的选择很重要matchFeatures 中的 ratio test 的设置还可以增加其他优化措施来剔除离谱点最重要的 BA 还没有加入······· 目前出来的效果不好革命尚未成功同志还需努力 参考资料 基于OpenCV和C的多视图三维重建 OpenCV实现SfM三多目三维重建