CorpusCallosum.shape.mesh¶
- class CorpusCallosum.shape.mesh.CCMesh(vertices, faces, vertex_values=None)[source]¶
A class for representing and manipulating corpus callosum (CC) meshes.
This class extends lapy.TriaMesh to provide specialized functionality for working with corpus callosum meshes, including contour management, thickness measurements, and visualization capabilities.
The mesh can be constructed from a series of 2D contours representing slices of the corpus callosum, with optional thickness measurements at various points along these contours.
Attributes
v
(np.ndarray) Vertex coordinates of the mesh.
t
(np.ndarray) Triangle indices of the mesh.
mesh_vertex_colors
(np.ndarray) Vertex values for each vertex (CC thickness values)
Methods
area()Compute the total surface area of triangle mesh.
avg_edge_length()Compute the average edge length of the mesh.
boundary_loops()Compute boundary loops of the mesh.
centroid()Compute centroid of triangle mesh as a weighted average of triangle centers.
connected_components()Compute connected components of the mesh.
construct_adj_dir_tidx()Construct directed adjacency matrix (edge graph) of triangle mesh.
critical_points(vfunc)Compute critical points (extrema and saddles) of a function on mesh vertices.
curvature([smoothit])Compute various curvature values at vertices.
curvature_tria([smoothit])Compute min and max curvature and directions on triangle faces.
edges([with_boundary])Compute vertices and adjacent triangle ids for each edge.
euler()Compute the Euler Characteristic.
extract_level_paths(vfunc, level[, eps])Extract level set paths as Polygon objects with triangle/edge metadata.
from_contours(contours[, lr_center, closed, ...])Create a surface mesh by triangulating between consecutive contours.
get_vertices([original_dim])Get mesh vertices.
has_free_vertices()Check if the vertex list has more vertices than what is used in triangles.
is_2d()Check if the mesh was created with 2D vertices.
is_boundary()Check which vertices are on the boundary.
is_closed()Check if triangle mesh is closed (no boundary edges).
is_manifold()Check if triangle mesh is manifold (no edges with >2 triangles).
is_oriented()Check if triangle mesh is oriented.
keep_largest_connected_component_([clean])Keep only the largest connected component of the mesh.
level_length(vfunc, level)Compute the length of level sets.
level_path(vfunc, level[, get_tria_idx, ...])Extract a single level set path as an array of 3D points.
map_tfunc_to_vfunc(tfunc[, weighted])Map triangle function to vertices by attributing 1/3 to each vertex.
map_vfunc_to_tfunc(vfunc)Map vertex function to triangles by averaging vertex values.
normal_offset_(d)Move vertices along their normals by distance d.
normalize_()Normalize TriaMesh to unit surface area and centroid at the origin.
orient_()Re-orient triangles of manifold mesh to be consistent.
plot_mesh([output_path, colormap, ...])Plot the mesh using Plotly for better performance and interactivity.
read_fssurf(filename)Load triangle mesh from FreeSurfer surface geometry file.
read_gifti(filename)Load triangle mesh from a GIFTI surface file.
read_off(filename)Load triangle mesh from OFF txt file.
read_vtk(filename)Load triangle mesh from VTK txt file.
refine_([it])Refine the triangle mesh by placing new vertex on each edge midpoint.
rm_free_vertices_()Remove unused (free) vertices.
smooth_([iterations])Smooth the mesh while preserving the z-coordinates.
smooth_laplace([vfunc, n, lambda_, mat])Smooth the mesh or a vertex function using Laplace smoothing.
smooth_taubin([vfunc, n, lambda_, mu])Smooth the mesh or a vertex function using Taubin smoothing.
smooth_vfunc(vfunc[, n])Smooth the mesh or a vertex function iteratively.
snap_cc_picture(output_path[, ref_header])Snap a picture of the corpus callosum mesh.
to_vox_coordinates(mesh_ras2vox)Convert mesh coordinates to FreeSurfer coordinate system.
tria_areas()Compute the area of triangles using Heron's formula.
tria_normals()Compute triangle normals.
tria_qualities()Compute triangle quality for each triangle in mesh.
vertex_areas()Compute the area associated to each vertex (1/3 of one-ring trias).
vertex_degrees()Compute the vertex degrees (number of edges at each vertex).
vertex_normals()Compute vertex normals.
volume()Compute the volume of closed triangle mesh, summing tetrahedra at origin.
write_fssurf(filename[, image])Save as Freesurfer Surface Geometry file (wrap Nibabel).
write_gifti(filename)Save mesh as a GIFTI surface file.
write_morph_data(filename)Write the thickness values as a FreeSurfer overlay file.
write_vtk(filename)Save mesh as VTK file.
- classmethod from_contours(contours, lr_center=0, closed=False, smooth=0)[source]¶
Create a surface mesh by triangulating between consecutive contours.
Notes
The function: 1. Filters out None contours. 2. Calculates z-coordinates for each slice. 3. Creates triangles between adjacent contours. 4. Optionally: - Creates caps at both ends. - Applies smoothing. - Colors caps based on thickness values.
- plot_mesh(output_path=None, colormap='red_to_yellow', thickness_overlay=True, show_grid=False, color_range=None, legend='', threshold=None)[source]¶
Plot the mesh using Plotly for better performance and interactivity.
Creates an interactive 3D visualization of the mesh with optional features like thickness overlay, contour display, and grid visualization.
- Parameters:
- output_path
Path,str,optional Path to save the plot. If None, displays the plot interactively.
- colormap
str,optional Which colormap to use, by default “red_to_yellow”. Options: - “red_to_blue”: Red -> Orange -> Grey -> Light Blue -> Blue - “red_to_yellow”: Red -> Yellow -> Light Blue -> Blue - “yellow_to_red”: Yellow -> Light Blue -> Blue -> Red - “blue_to_red”: Blue -> Light Blue -> Grey -> Orange -> Red
- thickness_overlay
bool,optional Whether to overlay thickness values on the mesh, by default True.
- show_contours
bool,optional Whether to show the contours, by default False.
- show_grid
bool,optional Whether to show the grid, by default False.
- color_range
tuple[float,float],optional Fixed range (min, max) for the colorbar, by default None.
- show_mesh_edges
bool,optional Whether to show the mesh edges, by default False.
- legend
str,optional Legend text for the colorbar, by default “”.
- threshold
tuple[float,float],optional Values between these thresholds will be shown in grey, by default None.
- output_path
Notes
The plot can be saved to an HTML file or displayed in a web browser.
- smooth_(iterations=1)[source]¶
Smooth the mesh while preserving the z-coordinates.
- Parameters:
- iterations
int,optional Number of smoothing iterations, by default 1.
- iterations
Notes
The function: 1. Stores original z-coordinates. 2. Applies Laplacian smoothing to x and y coordinates. 3. Restores original z-coordinates to maintain slice structure.
- snap_cc_picture(output_path, ref_header=None)[source]¶
Snap a picture of the corpus callosum mesh.
- Parameters:
- Raises:
ImportErrorIf whippersnappy is not installed or if the version is too old.
ValueErrorIf the mesh has no faces and cannot create a snapshot.
- to_vox_coordinates(mesh_ras2vox)[source]¶
Convert mesh coordinates to FreeSurfer coordinate system.
- Parameters:
- mesh_ras2vox
AffineMatrix4x4 Transformation matrix from midplane mesh space (RAS centered on midplane) to voxel coordinates.
- mesh_ras2vox
- Returns:
CCMeshA CCMesh object with vertices reoriented to FreeSurfer coordinates.
Notes
Mesh coordinates are in ASR (Anterior-Superior-Right) orientation, with the coordinate system origin on the midslice. The function first transforms from midslice ASR to LIA vox coordinates.
- write_fssurf(filename, image=None)[source]¶
Save as Freesurfer Surface Geometry file (wrap Nibabel).
- Parameters:
- filename
str Filename to save to.
- image
str,object,None Path to image, nibabel image object, or image header. If specified, volume_info will be extracted from the image header, and by default, vertices are assumed to be in voxel coordinates and will be converted to surface RAS (tkr) before saving. The expected order of coordinates is (x, y, z) matching the image voxel indices in nibabel.
- coords_are_voxels
boolorNone, default=None Specifies whether vertices are in voxel coordinates. If None (default), the behavior is inferred: when image is provided, vertices are assumed to be in voxel space and converted to surface RAS; when image is not provided, vertices are assumed to already be in surface RAS. Set explicitly to True to force conversion (requires image), or False to skip conversion even when image is provided (only extracts volume_info).
- filename
- Raises:
ValueErrorIf coords_are_voxels is explicitly True but image is None. If image header cannot be processed.
IOErrorIf file cannot be written.
Notes
The surface RAS (tkr) transform is obtained from a header that implements
get_vox2ras_tkr()(e.g.,MGHHeader). For other header types (NIfTI1/2, Analyze/SPM, etc.), we attempt conversion viaMGHHeader.from_header.Also creates parent directory if needed before writing the file.
- CorpusCallosum.shape.mesh.make_triangles_between_contours(contour1, contour2)[source]¶
Create a triangular mesh between two contours using a robust method.
- Parameters:
- contour1
np.ndarray First contour points of shape (N, 2).
- contour2
np.ndarray Second contour points of shape (M, 2).
- contour1
- Returns:
np.ndarrayArray of triangle indices of shape (K, 3) where K is the number of triangles.
Notes
The function: 1. Finds closest point on contour2 to first point of contour1 2. Creates triangles by connecting corresponding points 3. Handles contours with different numbers of points 4. Creates two triangles to form a quad between each pair of points