File size: 5,592 Bytes
3799002 | 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 | """Geometry helpers: signed distance fields, point sampling, marching cubes."""
import numpy as np
from scipy import ndimage as ndi
def sdf_from_mask(mask, spacing=(1.0, 1.0, 1.0)):
"""Signed distance field in mm. Negative inside the mask, positive outside, 0 on surface.
mask: bool/0-1 array [x,y,z]; spacing: voxel size per axis (mm)."""
mask = mask.astype(bool)
spacing = tuple(float(s) for s in spacing)
if not mask.any():
# no structure -> large positive distance everywhere
return np.full(mask.shape, 10.0, dtype=np.float32)
if mask.all():
return np.full(mask.shape, -10.0, dtype=np.float32)
out = ndi.distance_transform_edt(~mask, sampling=spacing)
inn = ndi.distance_transform_edt(mask, sampling=spacing)
sdf = out - inn
return sdf.astype(np.float32)
def normals_from_sdf(sdf, spacing=(1.0, 1.0, 1.0)):
"""Unit gradient of the SDF (surface normals), [x,y,z,3]."""
gx, gy, gz = np.gradient(sdf, spacing[0], spacing[1], spacing[2])
g = np.stack([gx, gy, gz], axis=-1)
n = np.linalg.norm(g, axis=-1, keepdims=True)
n = np.clip(n, 1e-6, None)
return (g / n).astype(np.float32)
def sample_surface_and_random(mask, spacing, n_points, near_ratio=0.6,
sigma_mm=0.6, rng=None):
"""Return query coordinates in *voxel* units within a ROI.
A fraction near the surface (jittered surface voxels) + the rest uniform random."""
rng = rng or np.random.default_rng()
shape = np.array(mask.shape)
n_near = int(n_points * near_ratio)
n_rand = n_points - n_near
# surface voxels: boundary between mask and background
mask = mask.astype(bool)
if mask.any():
eroded = ndi.binary_erosion(mask)
surf = mask & ~eroded
coords = np.argwhere(surf)
else:
coords = np.zeros((0, 3))
if len(coords) > 0:
idx = rng.integers(0, len(coords), size=n_near)
near = coords[idx].astype(np.float32)
sigma_vox = np.array(sigma_mm) / np.array(spacing)
near = near + rng.normal(0, 1, near.shape) * sigma_vox[None, :]
else:
near = rng.random((n_near, 3)) * (shape - 1)[None, :]
rand = rng.random((n_rand, 3)) * (shape - 1)[None, :]
pts = np.concatenate([near, rand], axis=0).astype(np.float32)
pts = np.clip(pts, 0, (shape - 1)[None, :])
return pts
def trilinear_sample(vol, pts):
"""Sample a scalar/vector volume at fractional voxel coords pts [N,3] -> [N,(C)].
vol: [x,y,z] or [x,y,z,C]. Pure-numpy trilinear interpolation."""
pts = np.asarray(pts, dtype=np.float32)
x, y, z = pts[:, 0], pts[:, 1], pts[:, 2]
sx, sy, sz = vol.shape[:3]
x0 = np.clip(np.floor(x).astype(int), 0, sx - 1); x1 = np.clip(x0 + 1, 0, sx - 1)
y0 = np.clip(np.floor(y).astype(int), 0, sy - 1); y1 = np.clip(y0 + 1, 0, sy - 1)
z0 = np.clip(np.floor(z).astype(int), 0, sz - 1); z1 = np.clip(z0 + 1, 0, sz - 1)
xd = (x - x0)[:, None] if vol.ndim == 4 else (x - x0)
yd = (y - y0)[:, None] if vol.ndim == 4 else (y - y0)
zd = (z - z0)[:, None] if vol.ndim == 4 else (z - z0)
def g(a, b, c):
return vol[a, b, c]
c00 = g(x0, y0, z0) * (1 - xd) + g(x1, y0, z0) * xd
c01 = g(x0, y0, z1) * (1 - xd) + g(x1, y0, z1) * xd
c10 = g(x0, y1, z0) * (1 - xd) + g(x1, y1, z0) * xd
c11 = g(x0, y1, z1) * (1 - xd) + g(x1, y1, z1) * xd
c0 = c00 * (1 - yd) + c10 * yd
c1 = c01 * (1 - yd) + c11 * yd
return c0 * (1 - zd) + c1 * zd
def canal_centerline(mask):
"""3D skeleton (centerline) of a binary canal mask -> bool array [x,y,z]."""
mask = mask.astype(bool)
if not mask.any():
return np.zeros_like(mask)
try:
from skimage.morphology import skeletonize
return skeletonize(mask).astype(bool)
except Exception:
try:
from skimage.morphology import skeletonize_3d
return skeletonize_3d(mask).astype(bool)
except Exception:
return np.zeros_like(mask)
def marching_cubes_to_mesh(sdf_grid, level=0.0, spacing=(1.0, 1.0, 1.0),
origin=(0.0, 0.0, 0.0), pad=False, watertight=False):
"""SDF grid -> trimesh.Trimesh in world (mm) coordinates. Returns None if empty.
pad : pad the grid with a positive border so the zero-level set never
touches the volume boundary -> MC produces a closed surface.
watertight : keep the largest connected component and fill holes.
"""
import trimesh
from skimage import measure
if pad:
bigval = float(abs(sdf_grid).max() + max(spacing))
sdf_grid = np.pad(sdf_grid, 1, mode="constant", constant_values=bigval)
origin = np.array(origin) - np.array(spacing) # shift to keep world coords
if sdf_grid.min() > level or sdf_grid.max() < level:
return None
try:
verts, faces, normals, _ = measure.marching_cubes(
sdf_grid, level=level, spacing=tuple(float(s) for s in spacing))
except Exception:
return None
verts = verts + np.array(origin)[None, :]
mesh = trimesh.Trimesh(vertices=verts, faces=faces, vertex_normals=normals,
process=True)
if watertight:
try:
comps = mesh.split(only_watertight=False)
if len(comps) > 1:
mesh = max(comps, key=lambda m: len(m.faces))
mesh.fill_holes()
mesh.remove_degenerate_faces()
mesh.remove_duplicate_faces()
mesh.fix_normals()
except Exception:
pass
return mesh
|