CorpusCallosum.shape.contour

This module provides the CCContour class for reading, writing, and manipulating 2D corpus callosum contours together with per-vertex thickness values. Typical template outputs (from fastsurfer_cc.py --save_template) emit one set per slice:

  • contour_<idx>.txt: CSV with header New contour, anterior_endpoint_idx=<a>, posterior_endpoint_idx=<p> followed by x,y rows.

  • thickness_values_<idx>.txt: CSV with header thickness and one value per contour vertex.

  • thickness_measurement_points_<idx>.txt: CSV with header vertex_idx listing the vertices where thickness was measured.

class CorpusCallosum.shape.contour.CCContour(points, thickness_values, endpoint_idxs=None, z_position=0.0)[source]

A class for representing and manipulating corpus callosum (CC) contours.

This class provides functionality for manipulating and analyzing corpus callosum contours.

Attributes

points

(np.ndarray) Array of shape (N, 2) containing 2D contour points.

thickness_values

(np.ndarray) Array of shape (N,) for thickness measurements for each contour point.

endpoint_idxs

(tuple[int, int]) Tuple containing start and end indices for the contour.

Methods

copy()

Copy the contour.

create_levelpaths(num_points[, inplace])

Calculate thickness and level paths for the CC contour using Laplace equation.

fill_thickness_values()

Interpolate missing thickness values using weighted averaging.

from_contour_file(input_path, ...[, z_position])

Load contour from a CSV file.

from_mask_and_acpc(cc_mask, ac_2d, pc_2d, ...)

Extracts the contour of the CC using marching squares, smooth and transform to RAS coordinates.

get_contour_edge_lengths()

Get the lengths of the edges of a contour.

load_thickness_values(input_path)

Load thickness values from a CSV file.

plot_contour([output_path])

Plot a single contour with thickness values.

plot_contour_colorfill(plot_values[, title, ...])

Plot a contour with levelset visualization.

save_contour(output_path)

Save the contours to a CSV file.

save_thickness_values(output_path)

Save thickness values to a CSV file.

set_thickness_values(thickness_values[, ...])

Set the thickness values for the contour.

smooth_contour([window_size])

Smooth a contour using a moving average filter.

smooth_thickness_values([iterations])

Smooth the thickness values using a Gaussian filter.

Examples

>>> from CorpusCallosum.shape.contour import CCContour
>>>
>>> contour = CCContour(contour_points, thickness_values,
>>>                     endpoint_idxs=(anterior_idx, posterior_idx),
>>>                     z_position=0.0)
>>> contour.fill_thickness_values()   # interpolate missing values
>>> contour.smooth_contour(window_size=5)
>>> contour.save_contour("contour_0.txt")
>>> contour.save_thickness_values("thickness_values_0.txt")
copy()[source]

Copy the contour.

create_levelpaths(num_points, inplace=False)[source]

Calculate thickness and level paths for the CC contour using Laplace equation.

Parameters:
num_pointsint

Number of points for thickness estimation.

inplacebool, default=True

Whether to update the contour points and thickness values in place.

Returns:
levelpathslist[np.ndarray]

List of level paths across the CC.

thicknessfloat

Mean thickness of the CC.

midline_lenfloat

Length of the CC midline.

midline_equinp.ndarray

Equidistant points along the midline.

contour_with_thicknessnp.ndarray

Contour points with thickness information, shape (N, 3).

endpoint_idxstuple[int, int]

Indices of the anterior and posterior endpoints on the updated contour.

curvaturefloat

Mean curvature of the midline.

fill_thickness_values()[source]

Interpolate missing thickness values using weighted averaging.

Notes

The function: 1. Processes each contour with missing thickness values. 2. For each missing value: - Finds two closest points with known thickness. - Calculates distances along contour. - Computes weighted average based on inverse distance. 3. Updates thickness values in place.

The weights are calculated as inverse distances to ensure closer points have more influence on the interpolated value.

classmethod from_contour_file(input_path, thickness_values_path, z_position=0.0)[source]

Load contour from a CSV file.

Parameters:
input_pathstr, Path

Path to the CSV file containing the contours.

thickness_values_pathstr, Path

Path to the CSV file containing the thickness_values.

z_positionfloat, default=0.0

The distance to the midslice (in fsaverage space).

Raises:
ValueError

If the file format doesn’t match expected structure.

Notes

The function: 1. Reads CSV file with format matching save_contours output. 2. Processes special lines for endpoint indices. 3. Reconstructs contours and endpoint indices for each slice. 4. Converts lists to fixed-size arrays with None padding.

classmethod from_mask_and_acpc(cc_mask, ac_2d, pc_2d, slice_vox2ras, contour_smoothing=5)[source]

Extracts the contour of the CC using marching squares, smooth and transform to RAS coordinates.

Parameters:
cc_masknp.ndarray of shape (H, W) and type bool

Binary mask of the corpus callosum.

ac_2dnp.ndarray of shape (2,) and type float

2D voxel coordinates of the anterior commissure.

pc_2dnp.ndarray of shape (2,) and type float

2D voxel coordinates of the posterior commissure.

slice_vox2rasAffineMatrix4x4

Transformation matrix from slice-voxel space to RAS-coordinates.

contour_smoothingint, default=5

Window size for contour smoothing.

Returns:
contourCCContour

The contour object.

Notes

Expects LIA orientation.

get_contour_edge_lengths()[source]

Get the lengths of the edges of a contour.

Returns:
np.ndarray

Array of edge lengths for the contour.

Notes

Edge lengths are calculated as Euclidean distances between consecutive points in the contour, including the edge closing the loop between the last and first point.

load_thickness_values(input_path)[source]

Load thickness values from a CSV file.

Parameters:
input_pathPath, str

Path to the CSV file containing thickness values.

Raises:
ValueError

If number of thickness values doesn’t match measurement points or if number of slices is inconsistent.

plot_contour(output_path=None)[source]

Plot a single contour with thickness values.

Parameters:
output_pathstr

Path where to save the plot.

Notes

Creates a 2D visualization with: - Points colored by thickness values. - Gray points for missing thickness values. - Connected contour line. - Grid, labels, and legend.

plot_contour_colorfill(plot_values, title=None, save_path=None, colorbar=True, mode='p-value')[source]

Plot a contour with levelset visualization.

Creates a visualization of a contour with interpolated levelsets, useful for analyzing the thickness distribution across the corpus callosum.

Parameters:
plot_valuesnp.ndarray

Array of values to plot on CC from anterior to posterior (left to right in the plot).

titlestr, optional

Title for the plot.

save_pathstr, optional

Path to save the plot. If None, displays interactively.

colorbarbool, default=True

Whether to show the colorbar.

mode{“p-value”, “icc”, “thickness”}, default=”p-value”

Mode of the plot.

Returns:
matplotlib.figure.Figure

The created figure object.

save_contour(output_path)[source]

Save the contours to a CSV file.

Parameters:
output_pathPath, str

Path to save the CSV file.

Notes

The function saves contours in CSV format with: - Header: slice_idx,x,y. - Special lines indicating new contours with endpoint indices. - Each point gets its own row with slice index and coordinates.

save_thickness_values(output_path)[source]

Save thickness values to a CSV file.

Parameters:
output_pathPath, str

Path to save the CSV file.

Notes

The function saves thickness values in CSV format with: - Header: thickness. - Each thickness value gets its own row with slice index. - Skips slices with no thickness values.

set_thickness_values(thickness_values, use_measurement_points=False)[source]

Set the thickness values for the contour. This is useful to update the thickness values for specific plots.

Parameters:
thickness_valuesnp.ndarray

Array of thickness values for the contour.

use_measurement_pointsbool, default=False

Whether to use the measurement points to set the thickness values.

smooth_contour(window_size=5)[source]

Smooth a contour using a moving average filter.

Parameters:
window_sizeint, default=5

Size of the smoothing window.

Notes

Uses smooth_contour from cc_endpoint_heuristic module.

smooth_thickness_values(iterations=1)[source]

Smooth the thickness values using a Gaussian filter.

Parameters:
iterationsint, optional

Number of smoothing iterations, by default 1.

Notes

Applies Gaussian smoothing with sigma=5 to thickness values along the contour.

property area[source]

Calculate the area of the contour using the shoelace formula.

Returns:
float

The area of the contour.

CorpusCallosum.shape.contour.calculate_volume(contours, width=5.0)[source]

Calculate the volume of the corpus callosum.

This method calculates the volume of a slab of the CC centered on the midplane. It multiplies the area of each cross-sectional slice by the width it represents within the slab. It assumes equally spaced contours centered around the midplane (z=0).

Parameters:
widthfloat, default=5.0

The width of the slab centered on the midplane to calculate the volume for (in mm).

Returns:
float

The volume of the CC in cubic millimeters.