使用PCL读取pcd文件并传给osg显示,将窗口嵌入到qt
cpp文件:
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/StateSetManipulator>
#include <osgUtil/Optimizer>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osg/MatrixTransform>
_osgQtView::_osgQtView(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
osgWidget = new osgQOpenGLWidget(ui.widget); // qt拖入widget控件
osgWidget->setGeometry(ui.widget->geometry()); // 指定osg窗口显示大小
//m_fileName = "D:/code_cpp/cow.osg"; // 显示模型路径
//connect(osgWidget, SIGNAL(initialized()), this, SLOT(initOSG()));
connect(osgWidget, SIGNAL(initialized()), this, SLOT(initPCD()));
}
//读取模型
void _osgQtView::initOSG()
{
osgViewer::Viewer* pViewer = osgWidget->getOsgViewer();
pViewer->setCameraManipulator(new osgGA::TrackballManipulator);
osg::Node* node = osgDB::readNodeFile(m_fileName.toStdString());
pViewer->setSceneData(node);
}
void _osgQtView::initPCD()
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile("D:/code_cpp/rabbit.pcd", *cloud);
osg::ref_ptr<osg::Node> rootNode = createPointCloudNode(cloud);
osgViewer::Viewer* viewer = osgWidget->getOsgViewer();
viewer->setCameraManipulator(new osgGA::TrackballManipulator);
viewer->setSceneData(rootNode);
//viewer->run();
}
osg::ref_ptr<osg::Node> _osgQtView::createPointCloudNode(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud)
{
osg::ref_ptr<osg::Geometry> pointGeom = new osg::Geometry;
// 创建顶点数组
osg::ref_ptr<osg::Vec3Array> coords = new osg::Vec3Array();
// 创建颜色
osg::ref_ptr<osg::Vec4Array> color = new osg::Vec4Array();
int cloudNum = cloud->points.size();
for (size_t i = 0; i < cloudNum; i++) {
coords->push_back(osg::Vec3(cloud->points[i].x, cloud->points[i].y, cloud->points[i].z));
color->push_back(osg::Vec4(255.0, 0, 0, 1.0f));
}
pointGeom->setVertexArray(coords);
pointGeom->setColorArray(color);
pointGeom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
pointGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::POINTS, 0, coords->size()));
osg::ref_ptr<osg::Geode> geode = new osg::Geode;
geode->addDrawable(pointGeom);
osg::ref_ptr<osg::MatrixTransform> pointCloudNode = new osg::MatrixTransform;
pointCloudNode->addChild(geode);
return pointCloudNode;
}
头文件:
#include <QtWidgets/QMainWindow>
#include <QWidget>
#include <osgQOpenGL/osgQOpenGLWidget> //链接器添加 osgQOpenGLd.lib
#include "ui__osgQtView.h"
#include <osg/Node>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
class _osgQtView : public QMainWindow
{
Q_OBJECT
public:
_osgQtView(QWidget *parent = nullptr);
~_osgQtView();
osg::ref_ptr<osg::Node> createPointCloudNode(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud);
protected slots:
void initOSG();
void initPCD();
void on_pushButton_clicked();
private:
Ui::_osgQtViewClass ui;
osgQOpenGLWidget* osgWidget;
QString m_fileName;
};