Spaces:
Sleeping
Sleeping
Upload centerline_extraction.py
Browse files- centerline_extraction.py +43 -10
centerline_extraction.py
CHANGED
|
@@ -10,6 +10,7 @@ import SimpleITK as sitk
|
|
| 10 |
import vtk
|
| 11 |
|
| 12 |
ABDOMEN_LABELS = ['Celiac Trunk', 'Superior Mesenteric', 'Renal', 'Renal'] # The 4 abdominal artery labels, assigned top to bottom
|
|
|
|
| 13 |
AORTA_CONTINUATION_RATIO = 0.75 # At bifurcation, 2nd segment (outlet) must be at least this fraction of the thickest (inlet) to be considered aorta continuation
|
| 14 |
ABDOMEN_CLUSTER_MAX_GAP_MM = 50.0 # Maximum gap (mm) within the abdominal cluster
|
| 15 |
THORACIC_GAP_MM = 80.0 # Minimum gap (mm) separating the thoracic artery cluster from the abdominal cluster
|
|
@@ -143,7 +144,7 @@ def compute_centerlines_network(
|
|
| 143 |
# Extract main aorta→iliacs centerline via Voronoi method
|
| 144 |
try:
|
| 145 |
print("Extracting main centerline...")
|
| 146 |
-
centerline_polydata = extract_centerline_from_surface(surface_polydata_ras, aorta_iliac_endpoints_ras, curve_sampling_distance, smooth_iterations=20)
|
| 147 |
print(f"Main centerline: {centerline_polydata.GetNumberOfCells()} cells, {centerline_polydata.GetNumberOfPoints()} points")
|
| 148 |
except Exception as e:
|
| 149 |
print(f"Main centerline extraction failed: {type(e).__name__}: {e}")
|
|
@@ -648,7 +649,7 @@ def decimate_surface_for_voronoi(surface_polydata, target_points, max_reduction=
|
|
| 648 |
return result
|
| 649 |
|
| 650 |
# Voronoi-based centerline extraction from aorta to iliacs to compute accurate centerline paths, transforms closed surface to centerline network
|
| 651 |
-
def extract_centerline_from_surface(surface_polydata, endpoints, curve_sampling_distance, smooth_iterations=40, smooth_relaxation=0.1):
|
| 652 |
if not endpoints or len(endpoints) < 2:
|
| 653 |
raise ValueError("At least two endpoints are needed for centerline extraction")
|
| 654 |
|
|
@@ -688,7 +689,7 @@ def extract_centerline_from_surface(surface_polydata, endpoints, curve_sampling_
|
|
| 688 |
cl_filter.SetCostFunction("1/R")
|
| 689 |
cl_filter.SetFlipNormals(False) # Controls whether the Voronoi diagram is built from the inward normals (flipped) or outward normals
|
| 690 |
cl_filter.SetAppendEndPointsToCenterlines(0) # Path starts/ends at the nearest Voronoi node, which may be a fraction of a millimeter away from exact seed point
|
| 691 |
-
cl_filter.SetSimplifyVoronoi(
|
| 692 |
cl_filter.SetCenterlineResampling(1) # Enable resampling every 1mm, without this the raw Voronoi path is returned which contains thousands of points per segment
|
| 693 |
cl_filter.SetResamplingStepLength(curve_sampling_distance) # Turns on resampler itself
|
| 694 |
cl_filter.Update()
|
|
@@ -769,7 +770,7 @@ def extract_branch_centerline(branch_info, main_centerline_polydata, surface_pol
|
|
| 769 |
|
| 770 |
# Extract the branch centerline
|
| 771 |
try:
|
| 772 |
-
branch_centerline = extract_centerline_from_surface(clipped_surface, branch_endpoints, curve_sampling_distance, smooth_iterations=10)
|
| 773 |
return branch_centerline, contact_point
|
| 774 |
except Exception as e:
|
| 775 |
print(f"\nWarning: branch centerline extraction failed: {e}")
|
|
@@ -843,12 +844,8 @@ def extract_centerline_data(centerlines, branch_junctions=None):
|
|
| 843 |
all_bifurcations = find_bifurcation_points(centerlines, branch_junctions)
|
| 844 |
|
| 845 |
# Adds segment fork points (segment diverges) to all_bifurcations, useful for When VMTK produces only few long cells that share the entire aorta which ruins polydata
|
| 846 |
-
bifurcation_ids = {b['id'] for b in all_bifurcations}
|
| 847 |
fork_pts = find_segment_fork_points(segments, point_to_segments)
|
| 848 |
-
|
| 849 |
-
if fp['id'] not in bifurcation_ids and fp.get('radius', 0) >= 1.0:
|
| 850 |
-
all_bifurcations.append({'id': fp['id'], 'x': fp['x'], 'y': fp['y'], 'z': fp['z'], 'radius': fp['radius']})
|
| 851 |
-
bifurcation_ids.add(fp['id'])
|
| 852 |
|
| 853 |
# Splits diverging segments at all bifurcations into smaller sub segments that can be modified independently
|
| 854 |
segments, point_to_segments = split_segments_at_bifurcations(segments, bifurcation_ids)
|
|
@@ -1003,6 +1000,43 @@ def find_segment_fork_points(segments, point_to_segments):
|
|
| 1003 |
|
| 1004 |
return fork_points
|
| 1005 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1006 |
# Splits segments that pass through bifurcation points into sub-segments so that each sub-segment can be independently labeled as Aorta or Artery
|
| 1007 |
def split_segments_at_bifurcations(segments, bifurcation_ids):
|
| 1008 |
new_segments = []
|
|
@@ -1453,7 +1487,6 @@ def classify_arteries_by_zone(bifurcations_info, segments, has_thoracic):
|
|
| 1453 |
arm_endpoint_x = bif.get('arm_endpoint_x', [])
|
| 1454 |
|
| 1455 |
# Iliac like means any Artery arm drops more in Z than it spreads in X (lateral noise branches like lumbars move far in X but barely drop in Z)
|
| 1456 |
-
#iliac_like = any((bif_z - ez) > abs(ex - bif_x) for ez, ex, lbl in zip(arm_endpoint_z, arm_endpoint_x, arm_labels) if lbl == 'Artery')
|
| 1457 |
iliac_like = any(((bif_z - ez) > ILIAC_Z_DROP_RATIO * abs(ex - bif_x)) for ez, ex, lbl in zip(arm_endpoint_z, arm_endpoint_x, arm_labels) if lbl == 'Artery')
|
| 1458 |
if iliac_like:
|
| 1459 |
cutoff_pos = k
|
|
|
|
| 10 |
import vtk
|
| 11 |
|
| 12 |
ABDOMEN_LABELS = ['Celiac Trunk', 'Superior Mesenteric', 'Renal', 'Renal'] # The 4 abdominal artery labels, assigned top to bottom
|
| 13 |
+
FORK_DEDUPLICATION_RADIUS_MM = 3.0 # If 2 bifurcations have distance smaller than this, then they're duplicates of each other
|
| 14 |
AORTA_CONTINUATION_RATIO = 0.75 # At bifurcation, 2nd segment (outlet) must be at least this fraction of the thickest (inlet) to be considered aorta continuation
|
| 15 |
ABDOMEN_CLUSTER_MAX_GAP_MM = 50.0 # Maximum gap (mm) within the abdominal cluster
|
| 16 |
THORACIC_GAP_MM = 80.0 # Minimum gap (mm) separating the thoracic artery cluster from the abdominal cluster
|
|
|
|
| 144 |
# Extract main aorta→iliacs centerline via Voronoi method
|
| 145 |
try:
|
| 146 |
print("Extracting main centerline...")
|
| 147 |
+
centerline_polydata = extract_centerline_from_surface(surface_polydata_ras, aorta_iliac_endpoints_ras, curve_sampling_distance, voronoi_simplify=False, smooth_iterations=20)
|
| 148 |
print(f"Main centerline: {centerline_polydata.GetNumberOfCells()} cells, {centerline_polydata.GetNumberOfPoints()} points")
|
| 149 |
except Exception as e:
|
| 150 |
print(f"Main centerline extraction failed: {type(e).__name__}: {e}")
|
|
|
|
| 649 |
return result
|
| 650 |
|
| 651 |
# Voronoi-based centerline extraction from aorta to iliacs to compute accurate centerline paths, transforms closed surface to centerline network
|
| 652 |
+
def extract_centerline_from_surface(surface_polydata, endpoints, curve_sampling_distance, voronoi_simplify=False, smooth_iterations=40, smooth_relaxation=0.1):
|
| 653 |
if not endpoints or len(endpoints) < 2:
|
| 654 |
raise ValueError("At least two endpoints are needed for centerline extraction")
|
| 655 |
|
|
|
|
| 689 |
cl_filter.SetCostFunction("1/R")
|
| 690 |
cl_filter.SetFlipNormals(False) # Controls whether the Voronoi diagram is built from the inward normals (flipped) or outward normals
|
| 691 |
cl_filter.SetAppendEndPointsToCenterlines(0) # Path starts/ends at the nearest Voronoi node, which may be a fraction of a millimeter away from exact seed point
|
| 692 |
+
cl_filter.SetSimplifyVoronoi(voronoi_simplify) # Voronoi smoothing disabled (slows up path finding but maintains narrow vessel sections)
|
| 693 |
cl_filter.SetCenterlineResampling(1) # Enable resampling every 1mm, without this the raw Voronoi path is returned which contains thousands of points per segment
|
| 694 |
cl_filter.SetResamplingStepLength(curve_sampling_distance) # Turns on resampler itself
|
| 695 |
cl_filter.Update()
|
|
|
|
| 770 |
|
| 771 |
# Extract the branch centerline
|
| 772 |
try:
|
| 773 |
+
branch_centerline = extract_centerline_from_surface(clipped_surface, branch_endpoints, curve_sampling_distance, voronoi_simplify=True, smooth_iterations=10)
|
| 774 |
return branch_centerline, contact_point
|
| 775 |
except Exception as e:
|
| 776 |
print(f"\nWarning: branch centerline extraction failed: {e}")
|
|
|
|
| 844 |
all_bifurcations = find_bifurcation_points(centerlines, branch_junctions)
|
| 845 |
|
| 846 |
# Adds segment fork points (segment diverges) to all_bifurcations, useful for When VMTK produces only few long cells that share the entire aorta which ruins polydata
|
|
|
|
| 847 |
fork_pts = find_segment_fork_points(segments, point_to_segments)
|
| 848 |
+
all_bifurcations, bifurcation_ids = merge_bifurcations_with_fork_points(all_bifurcations, fork_pts)
|
|
|
|
|
|
|
|
|
|
| 849 |
|
| 850 |
# Splits diverging segments at all bifurcations into smaller sub segments that can be modified independently
|
| 851 |
segments, point_to_segments = split_segments_at_bifurcations(segments, bifurcation_ids)
|
|
|
|
| 1000 |
|
| 1001 |
return fork_points
|
| 1002 |
|
| 1003 |
+
# Merges calculated bifurcations with detected fork points without any duplications
|
| 1004 |
+
def merge_bifurcations_with_fork_points(all_bifurcations, fork_pts):
|
| 1005 |
+
bifurcation_ids = {b['id'] for b in all_bifurcations}
|
| 1006 |
+
|
| 1007 |
+
# Build a spatial locator on the existing degree-based bifurcations so fork points that are physically the same junction are rejected
|
| 1008 |
+
existing_bif_polydata = vtk.vtkPolyData()
|
| 1009 |
+
existing_bif_pts = vtk.vtkPoints()
|
| 1010 |
+
for b in all_bifurcations:
|
| 1011 |
+
existing_bif_pts.InsertNextPoint(b['x'], b['y'], b['z'])
|
| 1012 |
+
existing_bif_polydata.SetPoints(existing_bif_pts)
|
| 1013 |
+
bif_locator = vtk.vtkPointLocator()
|
| 1014 |
+
bif_locator.SetDataSet(existing_bif_polydata)
|
| 1015 |
+
bif_locator.BuildLocator()
|
| 1016 |
+
|
| 1017 |
+
for fp in fork_pts:
|
| 1018 |
+
if fp.get('radius', 0) < 0.5:
|
| 1019 |
+
continue
|
| 1020 |
+
if fp['id'] in bifurcation_ids:
|
| 1021 |
+
continue
|
| 1022 |
+
|
| 1023 |
+
# Reject if any existing bifurcation is within threshold
|
| 1024 |
+
if existing_bif_pts.GetNumberOfPoints() > 0:
|
| 1025 |
+
nearest_id = bif_locator.FindClosestPoint(fp['x'], fp['y'], fp['z'])
|
| 1026 |
+
nearest_pt = existing_bif_pts.GetPoint(nearest_id)
|
| 1027 |
+
dist = math.sqrt((fp['x'] - nearest_pt[0]) ** 2 + (fp['y'] - nearest_pt[1]) ** 2 + (fp['z'] - nearest_pt[2]) ** 2)
|
| 1028 |
+
if dist < FORK_DEDUPLICATION_RADIUS_MM:
|
| 1029 |
+
continue
|
| 1030 |
+
|
| 1031 |
+
all_bifurcations.append({'id': fp['id'], 'x': fp['x'], 'y': fp['y'], 'z': fp['z'], 'radius': fp['radius']})
|
| 1032 |
+
bifurcation_ids.add(fp['id'])
|
| 1033 |
+
|
| 1034 |
+
# Add the new point to the locator so subsequent fork points also deduplicate against it
|
| 1035 |
+
existing_bif_pts.InsertNextPoint(fp['x'], fp['y'], fp['z'])
|
| 1036 |
+
bif_locator.BuildLocator()
|
| 1037 |
+
|
| 1038 |
+
return all_bifurcations, bifurcation_ids
|
| 1039 |
+
|
| 1040 |
# Splits segments that pass through bifurcation points into sub-segments so that each sub-segment can be independently labeled as Aorta or Artery
|
| 1041 |
def split_segments_at_bifurcations(segments, bifurcation_ids):
|
| 1042 |
new_segments = []
|
|
|
|
| 1487 |
arm_endpoint_x = bif.get('arm_endpoint_x', [])
|
| 1488 |
|
| 1489 |
# Iliac like means any Artery arm drops more in Z than it spreads in X (lateral noise branches like lumbars move far in X but barely drop in Z)
|
|
|
|
| 1490 |
iliac_like = any(((bif_z - ez) > ILIAC_Z_DROP_RATIO * abs(ex - bif_x)) for ez, ex, lbl in zip(arm_endpoint_z, arm_endpoint_x, arm_labels) if lbl == 'Artery')
|
| 1491 |
if iliac_like:
|
| 1492 |
cutoff_pos = k
|