spline_volume module¶
- class spline_volume.OCC_volume(sitk_image: Image, img_path: None, filepath: str, filename: str, ASPECT: int, SLICE: int, UNDERSAMPLING: int, SLICING_COEFFICIENT: int, INSIDE_VAL: float, OUTSIDE_VAL: float, LOWER_THRESH: float, UPPER_THRESH: float, S: int, K: int, INTERP_POINTS: int, DP_SIMPLIFICATION_OUTER: int, DP_SIMPLIFICATION_INNER: int, debug_orientation: int, show_plots: bool, thickness_tol: float, phases: int)[source]¶
Bases:
object
- calculate_outer_offset(contour)[source]¶
Calculate the outer offset of a given contour.
This function calculates the outer offset of the given contour by buffering the contour with a negative offset. It handles cases where multiple geometries are created during buffering and retains the largest one.
- Parameters:
contour (ndarray) – The input contour.
- Returns:
The offset contour.
- Return type:
ndarray
- check_inner_offset(outer_polygon, inn_contour)[source]¶
Check and adjust the inner contour based on the outer polygon.
This function checks if the points of the inner contour are within the outer polygon. If not, it adjusts the points to the closest points on the outer polygon.
- Parameters:
outer_polygon (ndarray) – The outer polygon contour.
inn_contour (ndarray) – The inner contour points.
- Returns:
The adjusted inner contour points.
- Return type:
ndarray
- check_orient(x: ndarray, y: ndarray, direction: int = 1) Tuple[ndarray, ndarray] [source]¶
Author: Simone Poncioni, MSB Date: 18.08.2022 Functionality: Orient all array in the same direction (cw or ccw) (Sometimes planes would reorient in opposite direction, making them unsuitable for interplane connectivity)
Args: x = 1D-arr (x coords of points) y = 1D-arr (y coords of points) directions: 1 = cw, 2 = ccw
Returns: x_o = reoriented x 1D-arr y_o = reoriented y 1D-arr
- classify_and_store_contours(mask, slice_idx)[source]¶
Classify and store contours from a given slice of the mask.
This function finds contours in the specified slice of the mask and classifies the first contour as the outer contour and the second contour (if present) as the inner contour.
- Parameters:
mask (ndarray) – The 3D mask array from which contours are to be extracted.
slice_idx (int) – The index of the slice to be processed.
- Returns:
The outer and inner contours.
- Return type:
Tuple[ndarray, ndarray]
- draw_contours(img: ndarray, loc: str = 'outer', approximation: bool = True) ndarray [source]¶
Find the contours of an image.
- Parameters:
img (numpy.ndarray) – The input image as a 2D numpy array.
loc (str) – The location of the contour. Can be “outer” or “inner”. Defaults to “outer”.
approximation (bool) – If True, contour is approximated using the Ramer-Douglas-Peucker (RDP) algorithm. Defaults to True.
- Returns:
The contour image as a 2D numpy array.
- Return type:
numpy.ndarray
- Raises:
ValueError – If the location of the contour is not valid.
- Credits to:
https://stackoverflow.com/questions/25733694/process-image-to-find-external-contour
- Docs:
https://docs.opencv.org/2.4/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html https://learnopencv.com/convex-hull-using-opencv-in-python-and-c/ https://doi.org/10.1016/0167-8655(82)90016-2
- evaluate_bspline(contour)[source]¶
Evaluate a B-spline for the given contour.
This function fits a B-spline to the given contour points and evaluates the spline to generate new interpolated points. The spline is closed by appending the first point to the end of the new points.
- Parameters:
contour (ndarray) – The contour points to be fitted with a B-spline.
- Returns:
The x and y coordinates of the interpolated B-spline points.
- Return type:
Tuple[ndarray, ndarray]
- exec_thresholding(image: Image, THRESHOLD_PARAM: List[float]) Image [source]¶
Apply binary thresholding to the given image.
This function applies binary thresholding to the input image based on the specified threshold parameters.
- Parameters:
image (SimpleITK.Image) – The input image to be thresholded.
THRESHOLD_PARAM (List[float]) – List of threshold parameters [INSIDE_VAL, OUTSIDE_VAL, LOWER_THRESH, UPPER_THRESH].
- Returns:
The thresholded image.
- Return type:
SimpleITK.Image
- get_binary_contour(image: Image) Image [source]¶
Generate binary contours from the given image. https://itk.org/pipermail/community/2017-August/013464.html
This function generates binary contours for each slice of the input image and joins them into a single 3D image.
- Parameters:
image (SimpleITK.Image) – The input image.
- Returns:
The image with binary contours.
- Return type:
SimpleITK.Image
- get_draw_contour(image: Image, loc: str = 'outer') ndarray [source]¶
Extract and draw contours from the given image.
This function extracts and draws contours from the input image for each slice. The contours are then flipped and returned as a numpy array.
- Parameters:
image (SimpleITK.Image) – The input image.
loc (str, optional) – The location of the contour to be drawn. Default is “outer”.
- Returns:
The extracted and drawn contours.
- Return type:
ndarray
- get_line_sets(contour)[source]¶
Generate vertical line sets from contour slices.
This function generates vertical line sets from the given contour slices. It aligns the slices based on the first point and collects corresponding points from each slice to form vertical lines.
- Parameters:
contour (List[ndarray]) – List of contour slices.
- Returns:
List of vertical line sets.
- Return type:
List[List[ndarray]]
- input_sanity_check(ext_contour_s: ndarray, int_contour_s: ndarray)[source]¶
Sanity check for the input data before cortical sanity check
- Parameters:
ext_contour_s (np.ndarray) – array of external contour points
int_contour_s (np.ndarray) – array of internal contour points
- Returns:
array of external contour points with defined shape and structure (no duplicates, closed contour)
int_contour_s (np.ndarray): array of internal contour points with defined shape and structure (no duplicates, closed contour)
- Return type:
ext_contour_s (np.ndarray)
- interpolate_vertical_lines_3d(line_sets)[source]¶
https://stackoverflow.com/questions/32046582/spline-with-constraints-at-border Interpolate vertical lines in 3D using cubic splines.
This function performs cubic spline interpolation on the given vertical line sets with Neumann boundary conditions. It generates new Z values for interpolation and returns the interpolated points.
- Parameters:
line_sets (List[List[ndarray]]) – List of vertical line sets.
- Returns:
Array of interpolated points.
- Return type:
ndarray
- output_sanity_check(initial_contour: ndarray, contour_s: ndarray)[source]¶
Perform a sanity check on the output contours.
This function checks that the external and internal contours have the same structure and shape as before the sanity check. It ensures that the contours do not have duplicate points and have the correct shape.
- Parameters:
initial_contour (ndarray) – The initial contour points.
contour_s (ndarray) – The contour points after the sanity check.
- Returns:
The corrected contour points.
- Return type:
ndarray
- pad_and_plot(image: Image) Tuple[ndarray, ndarray] [source]¶
Pad the given image and optionally plot a slice of it.
This function pads the input image with a specified padding size and optionally plots a specified slice of the padded image.
- Parameters:
image (SimpleITK.Image) – The input image to be padded.
- Returns:
The padded image as a NumPy array.
- Return type:
ndarray
- pad_image(image: Image, iso_pad_size: int) Image [source]¶
Pads the input image with a constant value (background value) to increase its size. Padding is used to prevent having contours on the edges of the image, which would cause the spline fitting to fail. Padding is performed on the transverse plane only (image orientation is assumed to be z, y, x)
- Parameters:
image (SimpleITK.Image) – The input image to be padded.
iso_pad_size (int) – The size of the padding to be added to each dimension.
- Returns:
The padded image.
- Return type:
SimpleITK.Image
- plot_mhd_slice(img)[source]¶
Plot a slice of the SimpleITK.image.
This helper function plots a specified slice of the SimpleITK.image file using Matplotlib. It also provides an interactive slider to navigate through different slices.
- Parameters:
img (SimpleITK.Image) – The image to be plotted.
- Returns:
None
- plot_slice(image, SLICE, title, ASPECT)[source]¶
Plot a specific slice of the given image.
This function plots a specified slice of the input image using Matplotlib. It also provides an interactive slider to navigate through different slices.
- Parameters:
image (SimpleITK.Image) – The input image to be plotted.
SLICE (int) – The index of the slice to be plotted.
title (str) – The title of the plot.
ASPECT (float) – The aspect ratio for the plot.
- Returns:
None
- plot_slices_with_slider(imnp, total_slices, results)[source]¶
Function to plot slices with a slider to navigate through slices.
- Parameters:
imnp (numpy.ndarray) – 3D numpy array representing the image.
total_slices (int) – Total number of slices.
results (list) – List of tuples containing outer and inner contour plots for each slice.
- Returns:
None
- plotly_add_traces(fig, original, spline_interp)[source]¶
Add traces to a Plotly figure for visualization.
This function adds traces to a Plotly figure for visualizing the original and interpolated spline contours.
- Parameters:
fig (plotly.graph_objs.Figure) – The Plotly figure to add traces to.
original (ndarray) – The original contour points.
spline_interp (ndarray) – The interpolated spline contour points.
- Returns:
The updated Plotly figure with added traces.
- Return type:
plotly.graph_objs.Figure
- plotly_makefig(fig)[source]¶
Finalize and display the Plotly figure with sliders.
This function finalizes the Plotly figure by adding sliders for navigating through slices and displays the figure.
- Parameters:
fig (plotly.graph_objs.Figure) – The Plotly figure to be finalized and displayed.
- Returns:
The finalized Plotly figure.
- Return type:
plotly.graph_objs.Figure
- process_slice(mask, slice_idx)[source]¶
Process a single slice to classify and store contours.
This function processes a single slice of the input mask to classify and store the outer and inner contours. It applies Douglas-Peucker-Ramer simplification and B-spline interpolation to the contours.
- Parameters:
mask (ndarray) – The input mask for the slice.
slice_idx (int) – The index of the slice being processed.
- Returns:
Arrays of outer and inner B-spline contours.
- Return type:
Tuple[ndarray, ndarray]
- sort_mahalanobis(data: ndarray) Tuple[ndarray, ndarray] [source]¶
Sort points based on pairwise distances to form a continuous contour.
This function sorts the given data points based on pairwise distances to form a continuous contour, ensuring no self-intersections.
- Parameters:
data (ndarray) – The data points to be sorted.
- Returns:
The sorted x and y coordinates.
- Return type:
Tuple[ndarray, ndarray]
- sort_surface(image_slice: ndarray) Tuple[ndarray, ndarray, ndarray] [source]¶
Sort surface points in a clockwise direction and with Mahalanobis distance to add robustness
- Parameters:
slices (int) – slice number
- Returns:
xy array of sorted points self.x_mahanalobis (numpy.ndarray): x array of sorted points with mahalanobis distance self.y_mahanalobis (numpy.ndarray): y array of sorted points with mahalanobis distance self.xnew (numpy.ndarray): x array of sorted points interpolated with bspline and in the same direction self.ynew (numpy.ndarray): y array of sorted points interpolated with bspline and in the same direction
- Return type:
self.xy_sorted_closed (numpy.ndarray)
- sort_xy(x: ndarray, y: ndarray) Tuple[ndarray, ndarray] [source]¶
Sort x and y coordinates in a counterclockwise order. https://stackoverflow.com/questions/58377015/counterclockwise-sorting-of-x-y-data
This function sorts the given x and y coordinates in a counterclockwise order based on their angles from the centroid.
- Parameters:
x (ndarray) – The x-coordinates.
y (ndarray) – The y-coordinates.
- Returns:
The sorted x and y coordinates.
- Return type:
Tuple[ndarray, ndarray]
- spline_neumann(x, y, k=3, s=0, w=None)[source]¶
Perform cubic spline interpolation with Neumann boundary conditions.
This function performs cubic spline interpolation on the given data points (x, y) with Neumann boundary conditions, ensuring zero slope at the first point. It uses the scipy.optimize.minimize function to optimize the spline coefficients under the specified constraints.
- Parameters:
x (ndarray) – The x-coordinates of the data points.
y (ndarray) – The y-coordinates of the data points.
k (int, optional) – The degree of the spline. Default is 3.
s (float, optional) – Smoothing factor. Default is 0.
w (ndarray, optional) – Weights for spline fitting. Default is None.
- Returns:
The resulting spline with Neumann boundary conditions.
- Return type:
UnivariateSpline
- volume_splines() Tuple[ndarray, ndarray] [source]¶
Generate splines for cortical and trabecular regions.
This function processes the input image to generate volume splines for the cortical and trabecular regions. It includes steps for padding the image, extracting contours, and optionally plotting the results.
- Returns:
Arrays of cortical external and internal contours.
- Return type:
Tuple[ndarray, ndarray]
- volume_splines_optimized(imsitk_pad) Tuple[ndarray, ndarray] [source]¶
Generate optimized volume splines for cortical and trabecular regions.
This function processes the input padded image to generate optimized splines for the cortical and trabecular regions. It includes steps for processing slices, interpolating vertical lines, and performing sanity checks.
- Parameters:
imsitk_pad (SimpleITK.Image) – The padded input image.
- Returns:
Arrays of cortical external and internal contours.
- Return type:
Tuple[ndarray, ndarray]