Skip to content

Instantly share code, notes, and snippets.

@Norod
Created October 7, 2024 07:34
Show Gist options
  • Save Norod/50a2bd223f9c76506f541cfa7e9d2634 to your computer and use it in GitHub Desktop.
Save Norod/50a2bd223f9c76506f541cfa7e9d2634 to your computer and use it in GitHub Desktop.
Disconnect mesh components in an .obj file based on a a number of "depth range" buckets
import numpy as np
import trimesh
def load_mesh(file_path):
return trimesh.load(file_path)
def compute_depth_ranges(mesh, num_buckets=5):
# Extract vertex depths (assuming z-coordinate represents depth)
depths = mesh.vertices[:, 2]
# Compute depth range and bucket size
depth_min, depth_max = np.min(depths), np.max(depths)
bucket_size = (depth_max - depth_min) / num_buckets
# Assign vertices to buckets
bucket_assignments = np.floor((depths - depth_min) / bucket_size).astype(int)
return bucket_assignments
def disconnect_mesh_components(mesh, bucket_assignments):
# Create a new mesh for each bucket
disconnected_meshes = []
for bucket in range(np.max(bucket_assignments) + 1):
# Get vertices and faces for this bucket
vertex_mask = bucket_assignments == bucket
vertices = mesh.vertices[vertex_mask]
# Remap face indices to new vertex indices
old_to_new = np.cumsum(vertex_mask) - 1
faces = old_to_new[mesh.faces]
# Only keep faces where all vertices are in this bucket
valid_faces = np.all(vertex_mask[mesh.faces], axis=1)
faces = faces[valid_faces]
# Create a new mesh for this bucket
bucket_mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
disconnected_meshes.append(bucket_mesh)
return disconnected_meshes
def main(mesh_file_path, num_buckets=5):
# Load the mesh
mesh = load_mesh(mesh_file_path)
# Compute depth ranges and assign buckets
bucket_assignments = compute_depth_ranges(mesh, num_buckets)
# Disconnect mesh components
disconnected_meshes = disconnect_mesh_components(mesh, bucket_assignments)
# Save or visualize the results
for i, m in enumerate(disconnected_meshes):
m.export(f"disconnected_mesh_{i}.obj")
if __name__ == "__main__":
mesh_file_path = "download_model_1728232394.obj"
main(mesh_file_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment