Skip to content

文件读写(File IO)

本教程演示 Open3D 如何读取和写入基本数据结构。

下面的代码读取并写入一个点云。

print("Testing IO for point cloud ...")
sample_pcd_data = o3d.data.PCDPointCloud()
pcd = o3d.io.read_point_cloud(sample_pcd_data.path)
print(pcd)
o3d.io.write_point_cloud("copy_of_fragment.pcd", pcd)

输出:

Testing IO for point cloud ...
PointCloud with 113662 points.
True

默认情况下,Open3D 会根据文件扩展名来推断文件类型。支持以下点云文件格式:

格式说明
xyz每行包含 [x, y, z],其中 x, y, z 为三维坐标
xyzn每行包含 [x, y, z, nx, ny, nz],其中 nx, ny, nz 为法向量
xyzrgb每行包含 [x, y, z, r, g, b],其中 r, g, b 为范围在 [0, 1] 的浮点数
pts第一行为表示点数的整数,其后各行遵循以下格式之一:[x, y, z, i, r, g, b]、[x, y, z, r, g, b]、[x, y, z, i] 或 [x, y, z],其中 x, y, z, i 为 double 类型,r, g, b 为 uint8 类型
ply参见 Polygon File Format,ply 文件可同时包含点云和网格数据
pcd参见 Point Cloud Data

也可以显式指定文件类型,此时文件扩展名将被忽略。

下面的代码读取并写入一个网格。

print("Testing IO for meshes ...")
knot_data = o3d.data.KnotMesh()
mesh = o3d.io.read_triangle_mesh(knot_data.path)
print(mesh)
o3d.io.write_triangle_mesh("copy_of_knot.ply", mesh)

输出:

Testing IO for meshes ...
TriangleMesh with 1440 points and 2880 triangles.
True

与点云数据结构相比,网格(mesh)额外拥有定义三维表面的三角形。默认情况下,Open3D 会根据文件扩展名来推断文件类型。支持以下网格文件格式:

格式说明
ply参见 Polygon File Format,ply 文件可同时包含点云和网格数据
stl参见 StereoLithography
obj参见 Object Files
off参见 Object File Format
gltf/glb参见 GL Transmission Format

下面的代码读取并写入一张图像。

print("Testing IO for images ...")
image_data = o3d.data.JuneauImage()
img = o3d.io.read_image(image_data.path)
print(img)
o3d.io.write_image("copy_of_Juneau.jpg", img)

输出:

Testing IO for images ...
Image of size 800x489, with 3 channels.
Use numpy.asarray to access buffer data.
True

通过 print(img) 可以直接显示图像的尺寸。支持 jpg 和 png 两种图像文件格式。