File size: 5,829 Bytes
269adbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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