c ++如何以二进制格式输出ply文件

时间:2015-01-12 16:37:28

标签: c++ ply-file-format

我正在尝试使用以下标题创建二进制PLY文件:

ply
format binary_little_endian 1.0
element vertex 43000
property float x
property float y
property float z
property float nx
property float ny
property float nz
property uchar red
property uchar green
property uchar blue
end_header

我有以下重载函数写为二进制文件(用另一个例子验证):

inline void write_fbin(std::ofstream &out, float val) {
    out.write(reinterpret_cast<char*>(&val), sizeof(float));
}



inline void write_fbin(std::ofstream &out, unsigned char val) {
    out.write(reinterpret_cast<char*>(&val), sizeof(unsigned char));
}

我按如下方式编写顶点信息:

write_fbin(ofstr, static_cast<float>(point.x));
write_fbin(ofstr, static_cast<float>(point.y));
write_fbin(ofstr, static_cast<float>(point.z));
write_fbin(ofstr, static_cast<float>(point.n_x));
write_fbin(ofstr, static_cast<float>(point.n_y));
write_fbin(ofstr, static_cast<float>(point.n_z));
write_fbin(ofstr, static_cast<unsigned char>(point.r));
write_fbin(ofstr, static_cast<unsigned char>(point.g));
write_fbin(ofstr, static_cast<unsigned char>(point.b));

其中point

类型的结构
struct DensePoint {
    float x, y, z;
    float n_x, n_y, n_z;
    unsigned char r, g, b;
};

这不起作用并生成无效的ply文件。但是,如果我使用相同的代码(更改标题)来生成ASCII版本,

ofstr
            << point.x << ' '
            << point.y << ' '
            << point.z << ' '
            << point.n_x << ' '
            << point.n_y << ' '
            << point.n_z << ' '
            << static_cast<int>(point.r) << ' '
            << static_cast<int>(point.g) << ' '
            << static_cast<int>(point.b) <<
            '\n';

这完美无缺。可能有什么不对?

也许我需要在二进制格式的每个顶点的末尾引入一个换行符?

1 个答案:

答案 0 :(得分:2)

当向/从与预期格式不匹配的文件写入/读取二进制数据时,可能在OS级别存在字符转换,其替换某些字节组合与其他字节组合(es 0x0C成为0x0C 0x0A)。

你很可能在文本模式下打开文件(C ++流的默认设置)应该是二进制文件,让操作系统行为保持中立。