CSV也是一种文本文件,类似于TXT文本文件。但是由于CSV文件的特殊用途,本身可以由Excel办公软件获得,也有广泛的用途。以下示例演示采用C++方式读取CSV文件的点云数据,然后借助VTK可视化管线,渲染读取的点云数据。
#include <vtkSmartPointer.h>
#include <vtkSimplePointsReader.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <vtkVertexGlyphFilter.h>
using namespace std;
//删除字符串中空格,制表符tab等无效字符
string Trim(string& str)
{
//str.find_first_not_of(" \t\r\n"),在字符串str中从索引0开始,返回首次不匹配"\t\r\n"的位置
str.erase(0,str.find_first_not_of(" \t\r\n"));
str.erase(str.find_last_not_of(" \t\r\n") + 1);
return str;
}
int main( )
{
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
double x,y,z;
ifstream fin("Points.csv"); //打开文件流操作
string line;
while (getline(fin, line)) //整行读取,换行符“\n”区分,遇到文件尾标志eof终止读取
{
//cout <<"原始字符串:"<< line << endl; //整行输出
istringstream sin(line); //将整行字符串line读入到字符串流istringstream中
vector<string> fields; //声明一个字符串向量
string field;
while (getline(sin, field, ',')) //将字符串流sin中的字符读入到field字符串中,以逗号为分隔符
{
fields.push_back(field); //将刚刚读取的字符串添加到向量fields中
}
string sx = Trim(fields[0]);
string sy = Trim(fields[1]);
string sz = Trim(fields[2]);
//字符串转换成double型数字
istringstream streamx,streamy,streamz;
streamx.str(sx),streamy.str(sy),streamz.str(sz);
streamx>>x,streamy>>y,streamz>>z;
points->InsertNextPoint(x, y, z); //新读取的数据赋予点的几何结构
}
fin.close(); //关闭文件
vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
polyData->SetPoints(points);
vtkSmartPointer<vtkVertexGlyphFilter> glyphFilter = vtkSmartPointer<vtkVertexGlyphFilter>::New();
#if VTK_MAJOR_VERSION <= 5
glyphFilter->SetInputConnection(polyData->GetProducerPort());
#else
glyphFilter->SetInputData(polyData);
#endif
glyphFilter->Update();
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(glyphFilter->GetOutputPort());
vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetPointSize(4);
actor->GetProperty()->SetColor(0.0,0.0,0.0);
vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New();
renderer->AddActor(actor);
renderer->SetBackground(1.3, 1.6, 1.3); // Background color green
vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
Excel文件中的点云数据如下图所示:
生成的CSV文件如下图所示:
读取Point.csv文件中的点云数据,并经由VTK可视化管线渲染之后的点云数据如下图所示,