Vtk转obj

本文详细介绍了如何利用C++编程将Vtk格式的数据转换为Obj文件,涉及关键步骤和核心代码,适合对三维模型处理感兴趣的开发者参考。
	全是文件操作,没什么困难的,稍微有点坑是obj的face对应的vertex的idx要加1,下面上代码。
	思路是找到POINTS把点坐标都读出来,找到CELLS把面片都读出来,然后根据obj的格式写一下数据。
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>

using namespace std;

struct TriMesh {
	vector<OpenMesh::Vec3d> points;
	vector<OpenMesh::Vec3i> faces;
}MyMesh;

void readVtk(std::string input)
{
	ifstream input_file(input);
	if (!input_file.is_open()) {
		std::cout << "Unable to open file";
		return;
	}
	std::string ss[3];
	std::string line;
	char str[10];
	double xt, yt, zt;
	int a, b, c, d, tc, t;
	while (getline(input_file, line)) {
		istringstream iss(line);
		if (line.find("POINTS") != std::string::npos) {
			iss >> str >> a >> str;
			MyMesh.points.resize(a);
			break;
		}
	}
	double x, y, z, xx, yy, zz;
	for (int i = 0; i < a; ++i) {
		std::getline(input_file, line);
		std::istringstream iss(line);
		iss >> x >> y >> z;

		MyMesh.points[i][0] = x;
		MyMesh.points[i][1] = y;
		MyMesh.points[i][2] = z;
	}
	while (std::getline(input_file, line)) {
		std::istringstream iss(line);
		if (line.find("CELLS") != std::string::npos) {
			iss >> str >> tc >> b;
			MyMesh.faces.resize(tc);
			break;
		}
	}
	for (int i = 0; i < tc; ++i) {
		std::getline(input_file, line);
		std::istringstream iss(line);
		iss >> t >> a >> b >> c >> d;
		MyMesh.faces[i][0] = a + 1;
		MyMesh.faces[i][1] = b + 1;
		MyMesh.faces[i][2] = c + 1;
	}
	input_file.close();
}

void VtkToObj(string outfile)
{
	ofstream stream;
	stream.open(outfile);

	stream << "g object" << "\n";

	for (int i = 0; i < MyMesh.points.size(); ++i) {
		stream << "v " << MyMesh.points[i][0] << " " << MyMesh.points[i][1] << " " << MyMesh.points[i][2] << "\n";
	}

	for (int i = 0; i < MyMesh.faces.size(); ++i) {
		stream << "f " << MyMesh.faces[i][0] << " " << MyMesh.faces[i][1] << " " << MyMesh.faces[i][2] << "\n";
	}

	stream.close();
}

int main(int argc, char** argv)
{
	if (3 != argc) {
		cout << "Program InputFile OutputFile";
		return -1;
	}

	readVtk(argv[1]);

	VtkToObj(argv[2]);

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值