双目视差生成点云图像

代码如下:

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <string>
#include <Eigen/Core>
#include <pangolin/pangolin.h>
#include <unistd.h>
#include <pcl/io/pcd_io.h>

using namespace std;
using namespace Eigen;

// 文件路径,如果不对,请调整
string left_file = "/home/lgl/project/第四讲习题/作业题/双目视差的使用/left.png";
string right_file = "/home/lgl/project/第四讲习题/作业题/双目视差的使用/right.png";
string disparity_file = "/home/lgl/project/第四讲习题/作业题/双目视差的使用/disparity.png";

// 在panglin中画图,已写好,无需调整
void showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);

int main(int argc, char **argv) {

    // 内参
    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;
    // 间距
    double b = 0.573;  // (注意此处的间距为双目相机左右光圈的间距)

    // 读取图像
    cv::Mat left = cv::imread(left_file, 0);
    cv::Mat right = cv::imread(right_file, 0);
    cv::Mat disparity = cv::imread(disparity_file, 0); // disparty 为CV_8U,单位为像素
    if(left.data)
        cout<<"loaded left.png"<<endl;
    cv::imshow("left",left);
    cv::imshow("right",right);
    cv::imshow("disparity",disparity);
    cv::waitKey(0);
    cv::destroyAllWindows();

    // 生成点云
    vector<Vector4d, Eigen::aligned_allocator<Vector4d>> pointcloud;

    // TODO 根据双目模型计算点云
    // 如果你的机器慢,请把后面的v++和u++改成v+=2, u+=2
    for (int v = 0; v < left.rows; v++)
        for (int u = 0; u < left.cols; u++) {

            Vector4d point(0, 0, 0, left.at<uchar>(v, u) / 255.0); // 前三维为xyz,第四维为颜色

            // start your code here (~6 lines)
            // 根据双目模型计算 point 的位置
            unsigned int d=disparity.ptr<unsigned short>(v)[u];
            if(d==0)
            {
                cout<<"d==0"<<endl;
                continue;
            }
            point[2]=(fx*b*1000)/d;
            point[1]=(v-cy)*point[2]/fy;
            point[0]=(u-cx)*point[2]/fx;
            cout<<"point = [ "<<point[0]<<" "<<point[1]<<" "<<point[2]<<" "<<point[3]<<" ]"<<endl;
            pointcloud.push_back(point);
            // end  your code here
        }

    cout<<"点云共有 : "<<pointcloud.size()<<"个点"<<endl;
    // 画出点云
    showPointCloud(pointcloud);
    return 0;
}

void showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud) {

    if (pointcloud.empty()) {
        cerr << "Point cloud is empty!" << endl;
        return;
    }

    pangolin::CreateWindowAndBind("Point Cloud Viewer", 1024, 768);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    pangolin::OpenGlRenderState s_cam(
            pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),
            pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)
    );

    pangolin::View &d_cam = pangolin::CreateDisplay()
            .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)
            .SetHandler(new pangolin::Handler3D(s_cam));

    while (pangolin::ShouldQuit() == false) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        d_cam.Activate(s_cam);
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        glPointSize(2);
        glBegin(GL_POINTS);
        for (auto &p: pointcloud) {
            glColor3f(p[3], p[3], p[3]);
            glVertex3d(p[0], p[1], p[2]);
        }
        glEnd();
        pangolin::FinishFrame();
        usleep(5000);   // sleep 5 ms
    }
    return ;
}
双目相机生成点云的核心原理是基于视差(Disparity)计算深度信息,并结合相机的标定参数将二维图像信息换为三维空间中的点云数据。其基本流程包括相机标定、立体匹配、视差图计算、深度图换以及点云生成几个关键步骤。 ### 相机标定 在双目视觉系统中,相机标定是获取相机内外参数的重要步骤。标定过程通常使用棋盘格等标准标定板,通过提取图像中的角点信息来求解相机的内参(如焦距、主点坐标)和外参(如旋矩阵和平移向量)[^2]。这些参数是后续视差计算和三维重建的基础。 ### 立体匹配与视差图计算 立体匹配是寻找左右图像中对应像素点的过程。通过匹配算法(如SAD、SSD、SIFT、BM、SGBM等)可以计算出每对像素点之间的视差值。视差值越大,表示该点距离相机越近;反之则越远。最终生成视差图反映了图像中每个像素点的视差信息。 ### 深度图视差图可以通过相机的基线距离(两个相机光心之间的距离)、焦距等参数换为深度图。深度值 $ Z $ 可以通过以下公式计算: $$ Z = \frac{f \cdot B}{d} $$ 其中: - $ f $ 是相机的焦距; - $ B $ 是双目相机的基线距离; - $ d $ 是像素点的视差值。 ### 点云生成 在获得深度图后,每个像素点可以映射到三维空间中的坐标点。具体来说,假设已知图像坐标 $ (u, v) $ 和对应的深度值 $ Z $,可以通过相机内参矩阵 $ K $ 进行反投影计算,得到该点在相机坐标系下的三维坐标 $ (X, Y, Z) $。将所有像素点的三维坐标组合起来,即可形成点云数据。 以下是一个使用 OpenCV 实现点云生成的简单示例代码: ```python import cv2 import numpy as np # 假设已知相机内参矩阵 K 和畸变系数 dist_coeffs K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) dist_coeffs = np.array([k1, k2, p1, p2, k3]) # 畸变系数 # 读取深度图(假设 depth_map 是一个二维数组,每个元素代表深度值 Z) depth_map = cv2.imread("depth_map.png", cv2.IMREAD_UNCHANGED).astype(np.float32) # 创建点云 h, w = depth_map.shape points = [] for v in range(h): for u in range(w): Z = depth_map[v, u] if Z == 0: continue # 跳过无效点 # 反投影计算 X, Y X = (u - K[0, 2]) * Z / K[0, 0] Y = (v - K[1, 2]) * Z / K[1, 1] points.append([X, Y, Z]) # 将点云保存为 PLY 文件 points = np.array(points) ply_header = '''ply format ascii 1.0 element vertex {} property float x property float y property float z end_header '''.format(len(points)) np.savetxt('point_cloud.ply', points, fmt='%f %f %f', header=ply_header, comments='') ``` 上述代码展示了如何将深度图换为三维点云并保存为 `.ply` 格式的文件。实际应用中还需要考虑图像去畸变、视差图的优化(如使用 SGBM 算法)、点云去噪等步骤,以提高点云的质量和精度。 ###
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值