Open3d 使用marching cubes生成3D模型

使用python 3.9.12

如果没有open3d

pip install open3d

 需要的头文件:

import numpy as np
import torch
import open3d as o3d
from skimage import measure

 通过open3d  导入数据

points=o3d.io.read_point_cloud(file)

 创建体素网格,大小以最大最小X,Y,Z创建一个立方体,然后进行创建三维数组体素化,存储数据为,点云表面为1,其他元素为0.

def pcd_to_voxel_grid(pcd, voxel_size=1.0):
    points = np.asarray(pcd.points)
    min_bound = np.min(points, axis=0)
    max_bound = np.max(points, axis=0)
    dims = np.ceil((max_bound - min_bound) / voxel_size).astype(np.int)
    voxel_grid = np.zeros(dims, dtype=np.uint8)
    for point in points:
        indices = np.floor((point - min_bound) / voxel_size).astype(np.int)
        voxel_grid[tuple(indices)] = 1
    return voxel_grid,voxel_size,min_bound #返回体素网格,体素间隔大小,以及最小的体素编号

 重建曲面:

vertices, faces, _, _ = measure.marching_cubes(voxel_grid, level,spacing=voxel)

 返回值为点以及三角面片,下面重建模型并保存:

mesh = o3d.geometry.TriangleMesh()
mesh.vertices = o3d.utility.Vector3dVector(vertices+point)
mesh.triangles = o3d.utility.Vector3iVector(faces)
o3d.io.write_triangle_mesh("rabbit.ply", mesh)

主体代码:

input_pcd_filename ="rabbit.pcd"

# Load PCD file
pcd = o3d.io.read_point_cloud(input_pcd_filename)

# Convert point cloud to voxel grid
voxel_grid,voxel_size,point = pcd_to_voxel_grid(pcd, voxel_size=0.1)

# Perform surface reconstruction using marching cubes
vertices, faces = marching_cubes(voxel_grid, level=0.5,space=(voxel_size,voxel_size,voxel_size))

# Create mesh from the reconstructed surface
mesh = o3d.geometry.TriangleMesh()
mesh.vertices = o3d.utility.Vector3dVector(vertices+point)
mesh.triangles = o3d.utility.Vector3iVector(faces)
o3d.io.write_triangle_mesh("abbit.ply", mesh)
# Visualize the result
o3d.visualization.draw_geometries([mesh])

你可能感兴趣的:(三维重建,python,opencv,python,numpy,开发语言,三维重建,MC算法)