import numpy as np from scipy.ndimage import distance_transform_edt, gaussian_filter, zoom, median_filter import matplotlib.pyplot as plt from skimage.measure import marching_cubes from scipy.ndimage import binary_fill_holes, label from mpl_toolkits.mplot3d.art3d import Poly3DCollection from scipy.spatial import Delaunay import open3d as o3d import pyvista as pv from scipy.interpolate import griddata # import trimesh def compute_sdf(voxel_matrix): inside_dist = distance_transform_edt(voxel_matrix) outside_dist = distance_transform_edt(1 - voxel_matrix) sdf = outside_dist - inside_dist # sdf = gaussian_filter(sdf, sigma=3.0) sdf = sdf / 32.0 sdf = sdf.clip(-0.2, 0.2) return sdf def visualize_sdf(voxel_matrix, sdf, slice_index, prefix='slice'): plt.figure(figsize=(12, 6)) plt.subplot(1, 2, 1) plt.title("Voxel Matrix Slice") plt.imshow(voxel_matrix[slice_index], cmap='gray') plt.subplot(1, 2, 2) plt.title("SDF Slice") plt.imshow(sdf[slice_index], cmap='jet') plt.colorbar() plt.show() plt.savefig(f'{prefix}_{slice_index}.png') plt.close() def extract_surface(sdf): vertices, faces, normals, values = marching_cubes(sdf, level=0) return vertices, faces def visualize_surface(vertices, faces): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') mesh = Poly3DCollection(vertices[faces]) mesh.set_edgecolor('k') ax.add_collection3d(mesh) ax.set_xlim(0, 32) ax.set_ylim(0, 32) ax.set_zlim(0, 32) plt.show() plt.savefig('surface.png') plt.close() def create_3d_mask(vertices, faces, shape): mask = np.zeros(shape, dtype=np.uint8) # Create a Delaunay triangulation for the vertices delaunay = Delaunay(vertices) # Generate grid points x = np.arange(0, shape[0]) y = np.arange(0, shape[1]) z = np.arange(0, shape[2]) grid = np.array(np.meshgrid(x, y, z)).T.reshape(-1, 3) # Find grid points that are inside the convex hull inside = delaunay.find_simplex(grid) >= 0 # Convert the grid points back to 3D index grid_points = grid[inside] # Set the mask values to 1 where points are inside the convex hull mask[grid_points[:, 0], grid_points[:, 1], grid_points[:, 2]] = 1 return mask def fill_holes_along_axis(volume, axis): filled_volume = np.copy(volume) for i in range(volume.shape[axis]): if axis == 0: slice_2d = volume[i, :, :] elif axis == 1: slice_2d = volume[:, i, :] else: slice_2d = volume[:, :, i] filled_slice = binary_fill_holes(slice_2d) # 确保单连通性 labeled_array, num_features = label(filled_slice) if num_features > 1: max_label = max(range(1, num_features + 1), key=lambda x: np.sum(labeled_array == x)) filled_slice = labeled_array == max_label if axis == 0: filled_volume[i, :, :] = filled_slice elif axis == 1: filled_volume[:, i, :] = filled_slice else: filled_volume[:, :, i] = filled_slice return filled_volume def mesh_to_voxel(vertices, faces): shape = [64, 64, 64] faces = np.hstack([[3] + list(face) for face in faces]) mesh = pv.PolyData(vertices, faces) grid = pv.voxelize(mesh, density=1.0) voxel_points = np.array(grid.points) filled_voxel = np.zeros(shape) for voxel in voxel_points: x, y, z = voxel x, y, z = int(np.round(x)), int(np.round(y)), int(np.round(z)) # 将顶点坐标转换为整数索引 if 0 <= x < shape[0] and 0 <= y < shape[1] and 0 <= z < shape[2]: filled_voxel[x, y, z] = 1 # 设置为1表示该位置有网格顶点 return filled_voxel def sdf_to_filled_mesh(sdf, level=0.02): # vertices, faces, _, _ = marching_cubes(sdf, level=level) # filled_voxel = mesh_to_voxel(vertices, faces) # for _ in range(1): # filled_voxel = fill_holes_along_axis(filled_voxel, 0) # filled_voxel = fill_holes_along_axis(filled_voxel, 1) # filled_voxel = fill_holes_along_axis(filled_voxel, 2) # while True: # prev_filled_voxel = filled_voxel.copy() # filled_voxel = fill_holes_along_axis(filled_voxel, 0) # filled_voxel = fill_holes_along_axis(filled_voxel, 1) # filled_voxel = fill_holes_along_axis(filled_voxel, 2) # if np.array_equal(filled_voxel, prev_filled_voxel): # break vertices_filled, faces_filled, normals_filled, values_filled = marching_cubes(sdf, level=level) # 将网格转换为 Open3D 的三角网格对象 mesh = o3d.geometry.TriangleMesh() mesh.vertices = o3d.utility.Vector3dVector(vertices_filled) mesh.triangles = o3d.utility.Vector3iVector(faces_filled) mesh.compute_vertex_normals() # 拉普拉斯平滑 mesh = mesh.filter_smooth_simple(number_of_iterations=20) mesh.compute_vertex_normals() return np.asarray(mesh.vertices), np.asarray(mesh.triangles) def sdf_to_voxel(sdf, level=0.02): sdf_smoothed = gaussian_filter(sdf, sigma=0.5) binary_mask = binary_fill_holes(sdf_smoothed <= level).astype(np.uint8) # structuring_element = ball(radius=1) # binary_mask_opened = binary_opening(binary_mask, footprint=structuring_element) # binary_mask_closed = binary_closing(binary_mask_opened, footprint=structuring_element) # binary_mask_eroded = binary_erosion(binary_mask_closed, structure=structuring_element) # binary_mask_dilated = binary_dilation(binary_mask_eroded, structure=structuring_element) # filled_voxel = gaussian_filter(binary_mask_dilated.astype(np.float32), sigma=1.0) # filled_voxel = filled_voxel > 0.5 filled_voxel = binary_mask return filled_voxel