def fix_mesh(mesh, resolution): bbox_min, bbox_max = mesh.bbox diag_len = norm(bbox_max - bbox_min) target_len = diag_len * resolution rospy.loginfo("\tTarget resolution: {} mm".format(target_len)) count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices rospy.loginfo("\t#vertices: {}".format(num_vertices)) count += 1 if count > 2: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def fix_meshes(mesh, detail="normal"): meshCopy = mesh # copy/pasta of pymesh script fix_mesh from qnzhou, see pymesh on GitHub bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 1e-2 count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) if is_mesh_broken(mesh, meshCopy) is True: if detail == "high": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) fix_meshes(mesh, detail="normal") if detail == "normal": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) fix_meshes(mesh, detail="low") if detail == "low": print( f'The function fix_meshes broke mesh, no lower settings can be applied, no fix was done' ) return meshCopy else: return mesh
def supports(self, c): other = pymesh.form_mesh( c.component_mesh.vertices - numpy.array([0, 0, (c.z - self.z)]), c.component_mesh.faces) pymesh.remove_duplicated_vertices(other) pymesh.remove_duplicated_faces(other) intersection = pymesh.boolean(self.component_mesh, other, 'intersection') pymesh.remove_duplicated_vertices(intersection) pymesh.remove_duplicated_faces(intersection) intersection.add_attribute("face_area") intersection_area = sum(intersection.get_attribute("face_area")) return intersection_area >= 0.2 * self.area()
def main(): args = parse_args(); mesh = pymesh.load_mesh(args.in_mesh); if (args.with_rounding): mesh = pymesh.form_mesh( np.round(mesh.vertices, args.precision), mesh.faces); intersecting_faces = pymesh.detect_self_intersection(mesh); counter = 0; while len(intersecting_faces) > 0 and counter < args.max_iterations: if (args.with_rounding): involved_vertices = np.unique(mesh.faces[intersecting_faces].ravel()); mesh.vertices_ref[involved_vertices, :] =\ np.round(mesh.vertices[involved_vertices, :], args.precision//2); mesh = pymesh.resolve_self_intersection(mesh, "igl"); mesh, __ = pymesh.remove_duplicated_faces(mesh, fins_only=True); if (args.with_rounding): mesh = pymesh.form_mesh( np.round(mesh.vertices, args.precision), mesh.faces); intersecting_faces = pymesh.detect_self_intersection(mesh); counter += 1; if len(intersecting_faces) > 0: logging.warn("Resolving failed: max iteration reached!"); pymesh.save_mesh(args.out_mesh, mesh);
def clean_mesh(mesh, connected=True, fill_internals=False): print('\t - Cleaning mesh (this may take a moment)') vert_list = [] mesh, info = pymesh.remove_isolated_vertices(mesh) mesh, info = pymesh.remove_duplicated_vertices(mesh) mesh, info = pymesh.remove_degenerated_triangles(mesh) mesh, info = pymesh.remove_duplicated_faces(mesh) if connected or fill_internals: mesh_list = pymesh.separate_mesh(mesh, 'auto') max_verts = 0 print(' - Total number of meshes (ideally 1): %d' % len(mesh_list)) for mesh_obj in mesh_list: nverts = mesh_obj.num_vertices if nverts > max_verts: max_verts = nverts mesh = mesh_obj if fill_internals: for mesh_obj in mesh_list: if mesh_obj.num_vertices != max_verts: vert_list.append(mesh_obj.vertices) return mesh, vert_list return mesh, vert_list
def hipp_cut(hipp_filename): hipp_img = nib.load(hipp_filename) hipp_matrix = hipp_img.get_fdata() hipp_matrix_s = scipy.ndimage.filters.gaussian_filter(hipp_matrix, sigma=1) #mesh it verts, faces, normals, values = skimage.measure.marching_cubes_lewiner(hipp_matrix_s, level=0.5) hipp_mesh = pymesh.form_mesh(verts, faces) hipp_mesh, info = pymesh.remove_duplicated_faces(hipp_mesh) assembler = pymesh.Assembler(hipp_mesh) L = assembler.assemble('laplacian').toarray() eigen = sciLA.eigh(L) for i in range(50): #print(eigen[0][i]) #Plot_3D.plot_eigh(hipp_mesh, eigen[1][:, i]) if (eigen[0][i] > 0.0000000001): eigen_cut = segment(eigen[1][:, i]) mean_first = np.mean(verts[np.where(eigen_cut==0), :], axis=1) mean_last = np.mean(verts[np.where(eigen_cut==(NUM_CUT-1)), :], axis=1) diff = -mean_first[0, 1] + mean_last[0, 1] + mean_first[0, 2] - mean_last[0, 2] eigen_cut_output = copy.copy(eigen_cut) if diff < 0: for i in range(NUM_CUT): eigen_cut_output[np.where(eigen_cut==i)] = NUM_CUT-i-1 #Plot_3D.plot_eigh(hipp_mesh, eigen_cut) break return eigen_cut_output, hipp_mesh
def main(): args = parse_args() mesh = pymesh.load_mesh(args.in_mesh) if (args.with_rounding): mesh = pymesh.form_mesh(np.round(mesh.vertices, args.precision), mesh.faces) intersecting_faces = pymesh.detect_self_intersection(mesh) counter = 0 while len(intersecting_faces) > 0 and counter < args.max_iterations: if (args.with_rounding): involved_vertices = np.unique( mesh.faces[intersecting_faces].ravel()) mesh.vertices_ref[involved_vertices, :] =\ np.round(mesh.vertices[involved_vertices, :], args.precision//2) mesh = pymesh.resolve_self_intersection(mesh, "igl") mesh, __ = pymesh.remove_duplicated_faces(mesh, fins_only=True) if (args.with_rounding): mesh = pymesh.form_mesh(np.round(mesh.vertices, args.precision), mesh.faces) intersecting_faces = pymesh.detect_self_intersection(mesh) counter += 1 if len(intersecting_faces) > 0: logging.warn("Resolving failed: max iteration reached!") pymesh.save_mesh(args.out_mesh, mesh)
def fix_mesh(mesh): mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) log_mesh(mesh, "Remove degenerate faces") mesh, __ = pymesh.collapse_short_edges(mesh, MIN_RES, preserve_feature=True) log_mesh(mesh, "Collapse short edges") mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) log_mesh(mesh, "Remove self intersections") mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) log_mesh(mesh, "New hull, remove duplicates") mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.5, 5) log_mesh(mesh, "Remote obtuse faces") mesh, __ = pymesh.remove_isolated_vertices(mesh) log_mesh(mesh, "Remove isolated vertices") return mesh
def finalMesh(z): poolWarning = None # Check if pools will overflow mesh if z > zMax: z = zMax poolWarning = 'The pool have a greater volume than the mesh can contain. Pool set to fill entire mesh.' # Create Bbox bMesh = createBbox(z) # Make intersection newMesh, bottomFaces, boolWarning = intersectAndBottomFaces(bMesh, z) # Create volume mesh volMesh = getVolMesh(newMesh, bottomFaces, z) volMesh.add_attribute('voxel_volume') volVol = volMesh.get_attribute('voxel_volume') volVol = sum(list(map(abs, volVol))) # Clean up mesh volMesh, info = pm.remove_isolated_vertices(volMesh) #print('num vertex removed', info["num_vertex_removed"]) volMesh, info = pm.remove_duplicated_faces(volMesh) return volMesh, volVol, poolWarning, poolWarning
def clean_up_mesh(mesh, tol): new_mesh, _ = pymesh.remove_isolated_vertices(mesh) new_mesh, _ = pymesh.remove_duplicated_vertices(new_mesh) new_mesh, _ = pymesh.remove_duplicated_faces(new_mesh) new_mesh, _ = pymesh.remove_degenerated_triangles(new_mesh) new_mesh, _ = pymesh.collapse_short_edges(new_mesh, rel_threshold=0.2) return new_mesh
def fix_mesh(mesh, detail=5e-3): # "normal": 5e-3 # "high": 2.5e-3 # "low": 2e-2 # "vlow": 2.5e-2 bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) if detail is None: detail = 5e-3 target_len = diag_len * detail print("Target resolution: {} mm".format(target_len)) count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-4) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh, __ = pymesh.remove_duplicated_vertices(mesh, tol=1e-4) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_degenerated_triangles(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices print("fix #v: {}".format(num_vertices)) count += 1 if count > 10: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def fix_mesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox diag_len = norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 1e-2 elif detail == "high": target_len = diag_len * 5e-3 elif detail == "low": target_len = diag_len * 0.03 print("Target resolution: {} mm".format(target_len)) count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices print("#v: {}".format(num_vertices)) count += 1 if count > 10: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def fix_mesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox; diag_len = norm(bbox_max - bbox_min); if detail == "normal": target_len = diag_len * 1e-2; #target_len = diag_len * 5e-3; elif detail == "enormal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 3e-3 #target_len = diag_len * 2.5e-3; elif detail == "low": target_len = diag_len * 1e-2; elif detail == "ehigh": target_len = diag_len * 1e-3; print("Target resolution: {} mm".format(target_len)); count = 0; mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100); mesh, __ = pymesh.split_long_edges(mesh, target_len); num_vertices = mesh.num_vertices; while True: #mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6); if detail == "low": mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=False); else: mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100); if mesh.num_vertices == num_vertices: break; num_vertices = mesh.num_vertices; print("#v: {}".format(num_vertices)); count += 1; if count > 10: break; mesh = pymesh.resolve_self_intersection(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh = pymesh.compute_outer_hull(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5); mesh, __ = pymesh.remove_isolated_vertices(mesh); return mesh;
def inc_remesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox diag_len = norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 2.5e-2 print("Target resolution: {} mm".format(target_len)) count = 1 # # mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) # mesh = pymesh.compute_outer_hull(mesh) # mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) num_vertices = mesh.num_vertices low = 4 / 5 * target_len high = 4 / 3 * target_len while True: print() print("[iteration " + str(count) + "]") # mesh, __ = pymesh.split_long_edges(mesh, high) # print("<split_long_edges> : DONE") # mesh, __ = pymesh.collapse_short_edges(mesh, low, preserve_feature=True) # print("<collapse_short_edges> : DONE") check_mesh(mesh) mesh = equalize_valences(mesh) print("<equalize_valences> : DONE") # mesh = tangential_relaxation(mesh) # print("<tangential_relaxation> : DONE") if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices print("#v: {}".format(num_vertices)) count += 1 if count > 10: break # mesh = pymesh.resolve_self_intersection(mesh) # mesh, __ = pymesh.remove_duplicated_faces(mesh) # mesh = pymesh.compute_outer_hull(mesh) # mesh, __ = pymesh.remove_duplicated_faces(mesh) # mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) # mesh, __ = pymesh.remove_isolated_vertices(mesh) check_mesh(mesh) return mesh
def load_mesh(path: Path) -> "threedframe.lib.PyMesh.python.Mesh.Mesh": mesh = pymesh.load_mesh(str(path)) mesh, _ = pymesh.remove_duplicated_faces(mesh) mesh, _ = pymesh.remove_duplicated_vertices(mesh) mesh.add_attribute("face_area") mesh.add_attribute("face_normal") mesh.add_attribute("face_centroid") mesh.add_attribute("vertex_normal") mesh.enable_connectivity() return mesh
def fix_mesh(mesh, target_len): bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) count = 0 print(" remove degenerated triangles") mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) print(" split long edges") mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: print(" pass %d" % count) print(" collapse short edges #1") mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) print(" collapse short edges #2") mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) print(" remove obtuse triangles") mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) print(" %d of %s vertices." % (num_vertices, mesh.num_vertices)) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break print(" resolve self intersection") mesh = pymesh.resolve_self_intersection(mesh) print(" remove duplicated faces") mesh, __ = pymesh.remove_duplicated_faces(mesh) print(" computer outer hull") mesh = pymesh.compute_outer_hull(mesh) print(" remove duplicated faces") mesh, __ = pymesh.remove_duplicated_faces(mesh) print(" remove obtuse triangles") mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) print(" remove isolated vertices") mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def __fix_mesh(self, mesh, improvement_thres=0.8): mesh, __ = pymesh.split_long_edges(mesh, self.mesh_target_len) num_vertices = len(mesh.vertices) for __ in range(10): mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.collapse_short_edges( mesh, self.mesh_target_len, preserve_feature=True ) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100) if len(mesh.vertices) < num_vertices * improvement_thres: break mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_isolated_vertices(mesh) return mesh
def old_fix_mesh(vertices, faces, detail="normal"): bbox_min = np.amin(vertices, axis=0) bbox_max = np.amax(vertices, axis=0) diag_len = norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 1e-2 print("Target resolution: {} mm".format(target_len)) count = 0 vertices, faces = pymesh.split_long_edges(vertices, faces, target_len) num_vertices = len(vertices) while True: vertices, faces = pymesh.collapse_short_edges(vertices, faces, 1e-6) vertices, faces = pymesh.collapse_short_edges(vertices, faces, target_len, preserve_feature=True) vertices, faces = pymesh.remove_obtuse_triangles( vertices, faces, 150.0, 100) if num_vertices == len(vertices): break num_vertices = len(vertices) print("#v: {}".format(num_vertices)) count += 1 if count > 10: break vertices, faces = pymesh.resolve_self_intersection(vertices, faces) vertices, faces = pymesh.remove_duplicated_faces(vertices, faces) vertices, faces, _ = pymesh.compute_outer_hull(vertices, faces, False) vertices, faces = pymesh.remove_duplicated_faces(vertices, faces) vertices, faces = pymesh.remove_obtuse_triangles(vertices, faces, 179.0, 5) vertices, faces, voxels = pymesh.remove_isolated_vertices(vertices, faces) return vertices, faces
def fix_mesh(mesh, detail="normal"): bbox_min, bbox_max = mesh.bbox; diag_len = norm(bbox_max - bbox_min); if detail == "normal": target_len = diag_len * 5e-3; elif detail == "high": target_len = diag_len * 2.5e-3; elif detail == "low": target_len = diag_len * 1e-2; print("Target resolution: {} mm".format(target_len)); count = 0; mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100); mesh, __ = pymesh.split_long_edges(mesh, target_len); num_vertices = mesh.num_vertices; while True: mesh, __ = pymesh.collapse_short_edges(mesh, 1e-6); mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 150.0, 100); if mesh.num_vertices == num_vertices: break; num_vertices = mesh.num_vertices; print("#v: {}".format(num_vertices)); count += 1; if count > 10: break; mesh = pymesh.resolve_self_intersection(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh = pymesh.compute_outer_hull(mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5); mesh, __ = pymesh.remove_isolated_vertices(mesh); return mesh;
def main(): args = parse_args(); mesh = pymesh.load_mesh(args.in_mesh); intersecting_faces = pymesh.detect_self_intersection(mesh); counter = 0; while len(intersecting_faces) > 0 and counter < args.max_iterations: mesh = pymesh.resolve_self_intersection(mesh, "igl"); mesh, __ = pymesh.remove_duplicated_faces(mesh, fins_only=True); intersecting_faces = pymesh.detect_self_intersection(mesh); counter += 1; if len(intersecting_faces) > 0: logging.warn("Resolving failed: max iteration reached!"); pymesh.save_mesh(args.out_mesh, mesh);
def execute(self, context): scene = context.scene pymesh_props = scene.pymesh obj_a = context.active_object mesh_a = import_object(context, obj_a) pymesh_r, info = pymesh.remove_degenerated_triangles(mesh_a) pymesh_r, info = pymesh.remove_obtuse_triangles(pymesh_r) pymesh_r, info = pymesh.remove_duplicated_faces(pymesh_r) pymesh_r, info = pymesh.collapse_short_edges(pymesh_r) pymesh_r, info = pymesh.remove_duplicated_vertices(pymesh_r) pymesh_r, info = pymesh.remove_isolated_vertices(pymesh_r) off_name = "Py.Clean." + obj_a.name mesh_r = export_mesh(context, pymesh_r, off_name) add_to_scene(context, mesh_r) return {'FINISHED'}
if left != None: b = left elif right != None: b = right if front != None: c = front elif back != None: c = back a, info = pymesh.remove_isolated_vertices(a) b, info = pymesh.remove_isolated_vertices(b) c, info = pymesh.remove_isolated_vertices(c) a, info = pymesh.remove_duplicated_faces(a) b, info = pymesh.remove_duplicated_faces(b) c, info = pymesh.remove_duplicated_faces(c) if a == None and b == None and c == None: print('No mesh to convert') exit() elif a != None and b != None and c != None: a = pymesh.boolean(a, c, operation="intersection") # a = pymesh.boolean(b, a, operation="intersection") elif a != None and b != None and c == None: a = pymesh.boolean(a, b, operation="intersection") elif a != None and b == None and c != None:
from mesh_utils import * # from greedy_remesh_remesh import gre_remesh # from variational_remesh import var_remesh from incremental_remesh import inc_remesh mesh = pymesh.load_mesh(str(sys.argv[1])) # mesh, __ = pymesh.remove_degenerated_triangles(mesh, 100) # mesh = pymesh.resolve_self_intersection(mesh) # mesh, __ = pymesh.remove_duplicated_faces(mesh) # mesh = pymesh.compute_outer_hull(mesh) # mesh, __ = pymesh.remove_duplicated_faces(mesh) # mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) # mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh.enable_connectivity() edges = get_edges(mesh) check_mesh(mesh) start = timeit.default_timer() mesh = equalize_valences(mesh) stop = timeit.default_timer() print('Time: ', stop - start) # mesh = tangential_relaxation(mesh) # edges = get_edges(mesh)
def symmetrize(verts, faces, eps=1e-3): """ verts: N,3 (x,y,z) tensor faces: F,3 (0,1,2) tensor Modifies mesh to make it symmetric about y-z plane - Cut mesh into half - Copy left half into right half - merge, remove duplicate vertices """ # Snap vertices close to centre to centre verts_centre_mask = (verts[:,0].abs() < eps) verts[verts_centre_mask, 0] = 0 # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/1.obj', pmesh) # Categorize vertices into left (-1), centre(0), right(1) verts_side = torch.sign(verts[:,0]) # Categorize faces into left (-1), centre(0), right(1) face_verts_side = torch.index_select(verts_side, 0, faces.view(-1)) face_verts_side = face_verts_side.contiguous().view(faces.shape[0], 3) face_left_mask = (face_verts_side[:,0]==-1) & (face_verts_side[:,1]==-1) & (face_verts_side[:,2]==-1) face_right_mask = (face_verts_side[:,0]==1) & (face_verts_side[:,1]==1) & (face_verts_side[:,2]==1) face_intesects_yz = (~face_left_mask) & (~face_right_mask) # Split intersecting faces new_verts = [] new_faces = [] for f in face_intesects_yz.nonzero().squeeze(1): i0, i1, i2 = faces[f] if verts_side[i0]==verts_side[i1]: i0, i1, i2 = i2, i0, i1 elif verts_side[i2]==verts_side[i1]: i0, i1, i2 = i0, i1, i2 elif verts_side[i0]==verts_side[i2]: i0, i1, i2 = i1, i0, i2 elif verts_side[i0]==-1: i0, i1, i2 = i0, i1, i2 elif verts_side[i1]==-1: i0, i1, i2 = i1, i0, i2 elif verts_side[i2]==-1: i0, i1, i2 = i2, i0, i1 else: import ipdb; ipdb.set_trace() # yz axis intersects i0->i1 & i0->i2 assert(verts_side[i0] != verts_side[i1]) assert(verts_side[i0] != verts_side[i2]) v0 = verts[i0] v1 = verts[i1] v2 = verts[i2] v_n1 = (v0 * v1[0] - v1 * v0[0])/(v1[0] - v0[0]) v_n2 = (v0 * v2[0] - v2 * v0[0])/(v2[0] - v0[0]) i_n1 = verts.shape[0] + len(new_verts) i_n2 = verts.shape[0] + len(new_verts) + 1 new_verts.append(v_n1) new_verts.append(v_n2) new_faces.append((i0, i_n1, i_n2)) new_faces.append((i1, i_n1, i_n2)) new_faces.append((i1, i2, i_n2)) new_verts = torch.stack(new_verts, dim=0) new_faces = torch.tensor(new_faces, dtype=faces.dtype, device=faces.device) verts = torch.cat([verts, new_verts], dim=0) faces = torch.index_select(faces, 0, (~face_intesects_yz).nonzero().squeeze(1)) faces = torch.cat([faces, new_faces], dim=0) # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/2.obj', pmesh) # Merge vertices that are very close together vertex_mapping = [] verts_new = [] for v_id in range(verts.shape[0]): if v_id==0: vertex_mapping.append(0) verts_new.append(verts[0]) continue min_d, min_idx = (verts[0:v_id] - verts[v_id]).norm(dim=-1).min(dim=0) if min_d < eps: vertex_mapping.append(vertex_mapping[min_idx]) else: vertex_mapping.append(len(verts_new)) verts_new.append(verts[v_id]) assert(len(vertex_mapping)==verts.shape[0]) vertex_mapping = torch.tensor(vertex_mapping, dtype=faces.dtype, device=faces.device) verts = torch.stack(verts_new, dim=0) faces = vertex_mapping[faces] # Remove degenerate faces faces_degenerate = (faces[:,0]==faces[:,1]) | (faces[:,0]==faces[:,2]) | (faces[:,2]==faces[:,1]) faces = torch.index_select(faces, 0, (~faces_degenerate).nonzero().squeeze(1)) # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/3.obj', pmesh) # Delete faces that lie on right side (verts_side==1) verts_centre_mask = (verts[:,0].abs() < eps) verts[verts_centre_mask, 0] = 0 verts_side = torch.sign(verts[:,0]) face_verts_side = torch.index_select(verts_side, 0, faces.view(-1)) face_verts_side = face_verts_side.contiguous().view(faces.shape[0], 3) face_right_mask = (face_verts_side[:,0]==1) | (face_verts_side[:,1]==1) | (face_verts_side[:,2]==1) faces = torch.index_select(faces, 0, (~face_right_mask).nonzero().squeeze(1)) # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/4.obj', pmesh) # Flip mesh, merge faces_flip = faces + verts.shape[0] faces = torch.cat([faces, faces_flip], dim=0) verts_flip = verts * torch.tensor([-1,1,1], dtype=verts.dtype, device=verts.device) vertex_mapping_flip = torch.arange(verts.shape[0], dtype=faces.dtype, device=faces.device) vertex_mapping_flip[~verts_centre_mask] += verts.shape[0] vertex_mapping = torch.arange(verts.shape[0], dtype=faces.dtype, device=faces.device) vertex_mapping = torch.cat([vertex_mapping, vertex_mapping_flip], dim=0) verts = torch.cat([verts, verts_flip], dim=0) faces = vertex_mapping[faces] # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/5.obj', pmesh) pymesh.save_mesh(f'csm_mesh/debug/5.8.obj', pmesh) numv = pmesh.num_vertices while True: pmesh, __ = pymesh.collapse_short_edges(pmesh, rel_threshold=0.4) verts = torch.as_tensor(pmesh.vertices, dtype=verts.dtype, device=verts.device) faces = torch.as_tensor(pmesh.faces, dtype=faces.dtype, device=faces.device) verts_centre_mask = (verts[:,0].abs() < 1e-3) verts[verts_centre_mask, 0] = 0 pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pmesh, __ = pymesh.remove_isolated_vertices(pmesh) pmesh, __ = pymesh.remove_duplicated_vertices(pmesh, tol=eps) pmesh, __ = pymesh.remove_duplicated_faces(pmesh) pmesh, __ = pymesh.remove_degenerated_triangles(pmesh) pmesh, __ = pymesh.remove_isolated_vertices(pmesh) # pmesh, __ = pymesh.remove_obtuse_triangles(pmesh, 120.0, 100) pmesh, __ = pymesh.collapse_short_edges(pmesh, 1e-2) pmesh, __ = pymesh.remove_duplicated_vertices(pmesh, tol=eps) if pmesh.num_vertices==numv: break numv = pmesh.num_vertices pymesh.save_mesh(f'csm_mesh/debug/5.9.obj', pmesh) verts = torch.as_tensor(pmesh.vertices, dtype=verts.dtype, device=verts.device) faces = torch.as_tensor(pmesh.faces, dtype=faces.dtype, device=faces.device) # Remove unused vertices vertices_used = torch.unique(faces.view(-1)) vertex_mapping = torch.zeros((verts.shape[0], ), dtype=faces.dtype, device=faces.device) vertex_mapping[vertices_used] = torch.arange(vertices_used.shape[0], dtype=faces.dtype, device=faces.device) faces = vertex_mapping[faces] verts = verts[vertices_used] # import pymesh pmesh = pymesh.form_mesh(verts.numpy(), faces.numpy()) pymesh.save_mesh(f'csm_mesh/debug/6.obj', pmesh) return verts, faces
def main(): args = parse_args(); mesh = pymesh.load_mesh(args.input_mesh); mesh, __ = pymesh.remove_duplicated_faces(mesh); pymesh.save_mesh(args.output_mesh, mesh);
def preprocess_mesh(input_mesh, prevent_nonmanifold_edges=True): r"""Removes duplicated vertices, duplicated faces, zero-area faces, and optionally faces the insertion of which would cause an edge of the mesh to become non-manifold. In particular, an iteration is performed over all faces in the mesh, keeping track of the half-edges in each face, and if a face contains a half-edge already found in one of the faces previously processed, it gets removed from the mesh. Args: input_mesh (pymesh.Mesh.Mesh): Mesh to preprocess. prevent_nonmanifold_edges (bool, optional): If True, faces that would cause an edge to become non-manifold are removed from the mesh (cf. above). (default: :obj:`True`) Returns: output_mesh (pymesh.Mesh.Mesh): Mesh after preprocessing. """ halfedges_found = set() new_faces = np.empty([input_mesh.num_faces, 3]) # Remove duplicated vertices. input_mesh = pymesh.remove_duplicated_vertices(input_mesh)[0] # Remove duplicated faces. input_mesh = pymesh.remove_duplicated_faces(input_mesh)[0] num_valid_faces = 0 # Compute face areas so that zero-are faces can be removed. input_mesh.add_attribute("face_area") face_areas = input_mesh.get_face_attribute("face_area") assert (len(face_areas) == len(input_mesh.faces)) for face, face_area in zip(input_mesh.faces, face_areas): # Do not include the face if it does not have three different # vertices. if (face[0] == face[1] or face[0] == face[2] or face[1] == face[2]): continue # Do not include zero-area faces. if (face_area == 0): continue # Optionally prevent non-manifold edges. if (prevent_nonmanifold_edges): new_halfedges_in_face = set() for idx in range(3): halfedge = (face[idx], face[(idx + 1) % 3]) if (halfedge[0] != halfedge[1]): # Exclude self-loops. if (halfedge not in halfedges_found): # Half-edge not found previously. -> The edge is # manifold so far. new_halfedges_in_face.add(halfedge) if (len(new_halfedges_in_face) == 3): # Face does not introduce non-manifold edges. halfedges_found.update(new_halfedges_in_face) new_faces[num_valid_faces] = face num_valid_faces += 1 # Here one can compute the face features already. else: new_faces[num_valid_faces] = face num_valid_faces += 1 new_faces = new_faces[:num_valid_faces] output_mesh = pymesh.form_mesh(input_mesh.vertices, new_faces) # Not including faces might have caused vertices to become isolated. output_mesh = pymesh.remove_isolated_vertices(output_mesh)[0] return output_mesh
def fix_meshes(mesh, detail="normal"): """ A pipeline to optimise and fix mesh based on pymesh Mesh object. 1. A box is created around the mesh. 2. A target length is found based on diagonal of the mesh box. 3. You can choose between 3 level of details, normal details settings seems to be a good compromise between final mesh size and sufficient number of vertices. It highly depends on your final goal. 4. Remove degenerated triangles aka collinear triangles composed of 3 aligned points. The number of iterations is 5 and should remove all degenerated triangles 5. Remove isolated vertices, not connected to any faces or edges 6. Remove self intersection edges and faces which is not realistic 7. Remove duplicated faces 8. The removing of duplicated faces can leave some vertices alone, we will removed them 9. The calculation of outer hull volume is useful to be sure that the mesh is still ok 10. Remove obtuse triangles > 179 who is not realistic and increase computation time 11. We will remove potential duplicated faces again 12. And duplicated vertices again 13. Finally we will look if the mesh is broken or not. If yes we will try lower settings, if the lowest settings broke the mesh we will return the initial mesh. If not, we will return the optimised mesh. :param mesh: Pymesh Mesh object to optimise :param detail: string 'high', 'normal' or 'low' ('normal' as default), or float/int Settings to choose the targeting minimum length of edges :return: Pymesh Mesh object An optimised mesh or not depending on detail settings and mesh quality """ meshCopy = mesh # copy/pasta of pymesh script fix_mesh from qnzhou, see pymesh on GitHub bbox_min, bbox_max = mesh.bbox diag_len = np.linalg.norm(bbox_max - bbox_min) if detail == "normal": target_len = diag_len * 5e-3 elif detail == "high": target_len = diag_len * 2.5e-3 elif detail == "low": target_len = diag_len * 1e-2 elif detail is float or detail is int and detail > 0: target_len = diag_len * detail else: print( 'Details settings is invalid, must be "low", "normal", "high" or positive int or float' ) quit() count = 0 mesh, __ = pymesh.remove_degenerated_triangles(mesh, 5) mesh, __ = pymesh.split_long_edges(mesh, target_len) num_vertices = mesh.num_vertices while True: mesh, __ = pymesh.collapse_short_edges(mesh, target_len, preserve_feature=True) mesh, info = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) if mesh.num_vertices == num_vertices: break num_vertices = mesh.num_vertices count += 1 if count > 10: break mesh, __ = pymesh.remove_duplicated_vertices(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) mesh = pymesh.resolve_self_intersection(mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_duplicated_vertices(mesh) mesh = pymesh.compute_outer_hull(mesh) mesh, __ = pymesh.remove_obtuse_triangles(mesh, 179.0, 5) mesh, __ = pymesh.remove_duplicated_faces(mesh) mesh, __ = pymesh.remove_isolated_vertices(mesh) if is_mesh_broken(mesh, meshCopy) is True: if detail == "high": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) fix_meshes(meshCopy, detail="normal") return mesh if detail == "normal": print( f'The function fix_meshes broke mesh, trying with lower details settings' ) mesh = fix_meshes(meshCopy, detail="low") return mesh if detail == "low": print( f'The function fix_meshes broke mesh, no lower settings can be applied, no fix was done' ) return meshCopy else: return mesh
def main(): args = parse_args() mesh = pymesh.load_mesh(args.input_mesh) mesh, __ = pymesh.remove_duplicated_faces(mesh) pymesh.save_mesh(args.output_mesh, mesh)