2D-3D / anchor_utils.py
Timilehin's picture
Upload anchor_utils.py
d07c190 verified
Raw History Blame Contribute Delete
3.57 kB
#@title mesh utils
import glob
import os
import open3d as o3d
import numpy as np
def read_off(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
assert lines[0].strip() == "OFF"
n_vertices, n_faces, _ = map(int, lines[1].strip().split())
vertices = []
for i in range(2, 2 + n_vertices):
vertex = list(map(float, lines[i].strip().split()))
vertices.append(vertex)
faces = []
for i in range(2 + n_vertices, 2 + n_vertices + n_faces):
face = list(map(int, lines[i].strip().split()))[1:]
faces.append(face)
return vertices, faces
def write_ply(file_path, vertices, faces):
with open(file_path, 'w') as file:
file.write("ply\n")
file.write("format ascii 1.0\n")
file.write(f"element vertex {len(vertices)}\n")
file.write("property float x\n")
file.write("property float y\n")
file.write("property float z\n")
file.write(f"element face {len(faces)}\n")
file.write("property list uchar int vertex_indices\n")
file.write("end_header\n")
for vertex in vertices:
file.write(f"{' '.join(map(str, vertex))}\n")
for face in faces:
file.write(f"{len(face)} {' '.join(map(str, face))}\n")
def scale_vertices(vertices, scale_factor):
return [[coord * scale_factor for coord in vertex] for vertex in vertices]
def convert_off_to_ply(off_file_path, ply_file_path, scale_factor=1.0):
vertices, faces = read_off(off_file_path)
scaled_vertices = scale_vertices(vertices, scale_factor)
write_ply(ply_file_path, scaled_vertices, faces)
def remove_outliers_and_convert_to_point_cloud(ply_file_path, nb_neighbors=40, std_ratio=1.0, voxel_size=0.005):
point_cloud = o3d.io.read_point_cloud(ply_file_path)
voxel_down = point_cloud.voxel_down_sample(voxel_size=voxel_size)
cl, ind = voxel_down.remove_statistical_outlier(nb_neighbors=nb_neighbors, std_ratio=std_ratio)
cleaned_ply_path = ply_file_path.replace('.ply', '_cleaned.ply')
o3d.io.write_point_cloud(cleaned_ply_path, cl)
cleaned_pcd_path = ply_file_path.replace('.ply', '_cleaned.pcd')
o3d.io.write_point_cloud(cleaned_pcd_path, cl)
return cleaned_ply_path, cleaned_pcd_path
def convert_pointcloud_to_mesh(ply_file_path, obj_file_path):
# Read the point cloud from the PLY file
pcd = o3d.io.read_point_cloud(ply_file_path)
# Estimate the normals of the point cloud
pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.05, max_nn=1000))
# Compute the nearest neighbor distances and calculate the average
nn_distances = pcd.compute_nearest_neighbor_distance()
avg_nn_distance = np.mean(nn_distances)
# Adjust the ball pivoting radius to a smaller value for a finer mesh
radius_of_ball = 3.5 * avg_nn_distance
print('radius of ball', radius_of_ball)
# Create a mesh using the Ball Pivoting Algorithm
bpa_mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_ball_pivoting(
pcd,
o3d.utility.DoubleVector([radius_of_ball, radius_of_ball])
)
# Simplify the mesh with a higher target number of triangles for more detail
target_number_of_triangles = 10000 # Increase this value for a finer mesh
simplified_mesh = bpa_mesh.simplify_quadric_decimation(target_number_of_triangles=target_number_of_triangles)
# Save the resulting mesh as an OBJ file
o3d.io.write_triangle_mesh(obj_file_path, simplified_mesh)
print(f'Saved: {obj_file_path}')