Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- centerline_extraction.py +48 -15
- server.py +2 -2
centerline_extraction.py
CHANGED
|
@@ -837,10 +837,10 @@ def process_branch_centerline(branch_info, main_centerline_polydata, surface_pol
|
|
| 837 |
branch_cl, _ = extract_centerline_from_surface(
|
| 838 |
clipped_surface, branch_endpoints, curve_sampling_distance=curve_sampling_distance,
|
| 839 |
)
|
| 840 |
-
return branch_cl
|
| 841 |
except Exception as e:
|
| 842 |
print(f" Warning: branch centerline extraction failed: {e}")
|
| 843 |
-
return None
|
| 844 |
|
| 845 |
|
| 846 |
def process_all_branches(branch_info_list_lps, main_centerline_polydata, surface_polydata,
|
|
@@ -862,17 +862,20 @@ def process_all_branches(branch_info_list_lps, main_centerline_polydata, surface
|
|
| 862 |
|
| 863 |
print(f"\nProcessing {len(branch_info_ras)} branch centerline(s)...")
|
| 864 |
branch_centerlines = []
|
|
|
|
| 865 |
for idx, info in enumerate(branch_info_ras, 1):
|
| 866 |
print(f"\nBranch {idx}/{len(branch_info_ras)}:")
|
| 867 |
-
cl = process_branch_centerline(info, main_centerline_polydata, surface_polydata, curve_sampling_distance)
|
| 868 |
if cl:
|
| 869 |
branch_centerlines.append(cl)
|
|
|
|
|
|
|
| 870 |
print(f" OK ({cl.GetNumberOfPoints()} points)")
|
| 871 |
else:
|
| 872 |
print(f" FAILED")
|
| 873 |
|
| 874 |
print(f"\nExtracted {len(branch_centerlines)}/{len(branch_info_ras)} branch centerlines")
|
| 875 |
-
return branch_centerlines
|
| 876 |
|
| 877 |
|
| 878 |
def merge_main_and_branch_centerlines(main_centerline_polydata, branch_centerlines):
|
|
@@ -888,6 +891,8 @@ def merge_main_and_branch_centerlines(main_centerline_polydata, branch_centerlin
|
|
| 888 |
|
| 889 |
cleaner = vtk.vtkCleanPolyData()
|
| 890 |
cleaner.SetInputData(append_filter.GetOutput())
|
|
|
|
|
|
|
| 891 |
cleaner.Update()
|
| 892 |
|
| 893 |
print(f"Merged: {cleaner.GetOutput().GetNumberOfCells()} cells, {cleaner.GetOutput().GetNumberOfPoints()} points")
|
|
@@ -935,7 +940,7 @@ def compute_centerlines_network(image, origin, direction, label_value=1,
|
|
| 935 |
aorta_iliac_endpoints, branch_endpoints_lps = detect_aorta_and_iliacs(network)
|
| 936 |
if not aorta_iliac_endpoints:
|
| 937 |
print("Failed to detect aorta-iliac endpoints from network.")
|
| 938 |
-
return None
|
| 939 |
|
| 940 |
# Convert detected endpoints from LPS to RAS (centerline extraction works in RAS)
|
| 941 |
endpoints = lps_to_ras(aorta_iliac_endpoints)
|
|
@@ -953,13 +958,14 @@ def compute_centerlines_network(image, origin, direction, label_value=1,
|
|
| 953 |
f"{centerline_polydata.GetNumberOfPoints()} points")
|
| 954 |
except Exception as e:
|
| 955 |
print(f"Main centerline extraction failed: {type(e).__name__}: {e}")
|
| 956 |
-
return None
|
| 957 |
|
| 958 |
# Step 5: Extract branch centerlines (one per detected branch)
|
| 959 |
branch_centerlines = []
|
|
|
|
| 960 |
if centerline_polydata and branch_endpoints_lps:
|
| 961 |
try:
|
| 962 |
-
branch_centerlines = process_all_branches(
|
| 963 |
branch_endpoints_lps, centerline_polydata, surface_polydata,
|
| 964 |
curve_sampling_distance=curve_sampling_distance,
|
| 965 |
)
|
|
@@ -976,12 +982,15 @@ def compute_centerlines_network(image, origin, direction, label_value=1,
|
|
| 976 |
else:
|
| 977 |
merged = centerline_polydata
|
| 978 |
|
|
|
|
|
|
|
|
|
|
| 979 |
# Convert final result from RAS back to LPS (to match expected coordinate system)
|
| 980 |
try:
|
| 981 |
-
return ras_polydata_to_lps(merged)
|
| 982 |
except Exception as e:
|
| 983 |
print(f"Warning: RAS->LPS conversion failed, returning RAS: {e}")
|
| 984 |
-
return merged
|
| 985 |
|
| 986 |
|
| 987 |
# Converts VTK polydata into a python list that contains line segments information (unique segment id, points in that segment, radius of each point, label)
|
|
@@ -1039,7 +1048,7 @@ def parse_segments(centerlines):
|
|
| 1039 |
|
| 1040 |
|
| 1041 |
# Computes bifurcation points which represent start of any branching arteries
|
| 1042 |
-
def find_bifurcation_points(centerlines):
|
| 1043 |
# Extracts centerline data
|
| 1044 |
pts = centerlines.GetPoints()
|
| 1045 |
lines = centerlines.GetLines()
|
|
@@ -1055,6 +1064,7 @@ def find_bifurcation_points(centerlines):
|
|
| 1055 |
|
| 1056 |
bifurcations = []
|
| 1057 |
max_radius = 0.0
|
|
|
|
| 1058 |
|
| 1059 |
# Degree 1 = endpoint, 2 = mid-segment, 3+ = bifurcation
|
| 1060 |
for point_id, deg in degree.items():
|
|
@@ -1062,6 +1072,7 @@ def find_bifurcation_points(centerlines):
|
|
| 1062 |
pt = pts.GetPoint(point_id)
|
| 1063 |
radius = radius_array.GetValue(point_id)
|
| 1064 |
max_radius = max(max_radius, radius)
|
|
|
|
| 1065 |
bifurcations.append({
|
| 1066 |
'id': point_id,
|
| 1067 |
'x': float(pt[0]),
|
|
@@ -1070,6 +1081,28 @@ def find_bifurcation_points(centerlines):
|
|
| 1070 |
'radius': float(radius),
|
| 1071 |
})
|
| 1072 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1073 |
# Sort bottom to top (iliac bifurcations first then abdomen then thoracic)
|
| 1074 |
bifurcations.sort(key=lambda b: b['z'])
|
| 1075 |
return bifurcations, max_radius
|
|
@@ -1328,12 +1361,12 @@ def build_response(centerlines_vtk, segments, abdomen_bifuractions, reference_po
|
|
| 1328 |
|
| 1329 |
|
| 1330 |
# Main Pipeline for extracting centerline data, labeling bifurcations and arteries, computing ostium and reference point positions
|
| 1331 |
-
def extract_centerline_data(centerlines):
|
| 1332 |
# Parse VTK polydata into Python segment dictionaries
|
| 1333 |
segments, point_to_segments = parse_segments(centerlines)
|
| 1334 |
|
| 1335 |
-
# Identify junction points (bifurcations)
|
| 1336 |
-
all_bifurcations, max_radius = find_bifurcation_points(centerlines)
|
| 1337 |
|
| 1338 |
# Label the 4 abdominal arteries and compute their direction vectors
|
| 1339 |
abdomen_bifs, abdomen_bifuraction_ids, abdomen_candidates = identify_abdominal_arteries(
|
|
@@ -1371,10 +1404,10 @@ if __name__ == '__main__':
|
|
| 1371 |
image, origin, direction = load_nrrd_as_vtk_image(filepath)
|
| 1372 |
|
| 1373 |
# Slicer-style surface processing -> Voronoi centerline extraction
|
| 1374 |
-
centerlines = compute_centerlines_network(image, origin, direction)
|
| 1375 |
|
| 1376 |
# Extract labelled segments and artery bifurcation data
|
| 1377 |
-
data = extract_centerline_data(centerlines)
|
| 1378 |
|
| 1379 |
# Write success JSON to stdout
|
| 1380 |
json.dump({'status': 'success', 'data': data}, sys.stdout)
|
|
|
|
| 837 |
branch_cl, _ = extract_centerline_from_surface(
|
| 838 |
clipped_surface, branch_endpoints, curve_sampling_distance=curve_sampling_distance,
|
| 839 |
)
|
| 840 |
+
return branch_cl, contact_point
|
| 841 |
except Exception as e:
|
| 842 |
print(f" Warning: branch centerline extraction failed: {e}")
|
| 843 |
+
return None, contact_point
|
| 844 |
|
| 845 |
|
| 846 |
def process_all_branches(branch_info_list_lps, main_centerline_polydata, surface_polydata,
|
|
|
|
| 862 |
|
| 863 |
print(f"\nProcessing {len(branch_info_ras)} branch centerline(s)...")
|
| 864 |
branch_centerlines = []
|
| 865 |
+
branch_contacts_ras = []
|
| 866 |
for idx, info in enumerate(branch_info_ras, 1):
|
| 867 |
print(f"\nBranch {idx}/{len(branch_info_ras)}:")
|
| 868 |
+
cl, contact = process_branch_centerline(info, main_centerline_polydata, surface_polydata, curve_sampling_distance)
|
| 869 |
if cl:
|
| 870 |
branch_centerlines.append(cl)
|
| 871 |
+
if contact:
|
| 872 |
+
branch_contacts_ras.append(contact)
|
| 873 |
print(f" OK ({cl.GetNumberOfPoints()} points)")
|
| 874 |
else:
|
| 875 |
print(f" FAILED")
|
| 876 |
|
| 877 |
print(f"\nExtracted {len(branch_centerlines)}/{len(branch_info_ras)} branch centerlines")
|
| 878 |
+
return branch_centerlines, branch_contacts_ras
|
| 879 |
|
| 880 |
|
| 881 |
def merge_main_and_branch_centerlines(main_centerline_polydata, branch_centerlines):
|
|
|
|
| 891 |
|
| 892 |
cleaner = vtk.vtkCleanPolyData()
|
| 893 |
cleaner.SetInputData(append_filter.GetOutput())
|
| 894 |
+
cleaner.SetToleranceIsAbsolute(True)
|
| 895 |
+
cleaner.SetAbsoluteTolerance(1.0) # 1mm tolerance to merge junction points from separately-extracted branch centerlines
|
| 896 |
cleaner.Update()
|
| 897 |
|
| 898 |
print(f"Merged: {cleaner.GetOutput().GetNumberOfCells()} cells, {cleaner.GetOutput().GetNumberOfPoints()} points")
|
|
|
|
| 940 |
aorta_iliac_endpoints, branch_endpoints_lps = detect_aorta_and_iliacs(network)
|
| 941 |
if not aorta_iliac_endpoints:
|
| 942 |
print("Failed to detect aorta-iliac endpoints from network.")
|
| 943 |
+
return None, []
|
| 944 |
|
| 945 |
# Convert detected endpoints from LPS to RAS (centerline extraction works in RAS)
|
| 946 |
endpoints = lps_to_ras(aorta_iliac_endpoints)
|
|
|
|
| 958 |
f"{centerline_polydata.GetNumberOfPoints()} points")
|
| 959 |
except Exception as e:
|
| 960 |
print(f"Main centerline extraction failed: {type(e).__name__}: {e}")
|
| 961 |
+
return None, []
|
| 962 |
|
| 963 |
# Step 5: Extract branch centerlines (one per detected branch)
|
| 964 |
branch_centerlines = []
|
| 965 |
+
branch_contacts_ras = []
|
| 966 |
if centerline_polydata and branch_endpoints_lps:
|
| 967 |
try:
|
| 968 |
+
branch_centerlines, branch_contacts_ras = process_all_branches(
|
| 969 |
branch_endpoints_lps, centerline_polydata, surface_polydata,
|
| 970 |
curve_sampling_distance=curve_sampling_distance,
|
| 971 |
)
|
|
|
|
| 982 |
else:
|
| 983 |
merged = centerline_polydata
|
| 984 |
|
| 985 |
+
# Convert branch junction coordinates from RAS to LPS (negate x,y)
|
| 986 |
+
branch_junctions_lps = [(-c[0], -c[1], c[2]) for c in branch_contacts_ras]
|
| 987 |
+
|
| 988 |
# Convert final result from RAS back to LPS (to match expected coordinate system)
|
| 989 |
try:
|
| 990 |
+
return ras_polydata_to_lps(merged), branch_junctions_lps
|
| 991 |
except Exception as e:
|
| 992 |
print(f"Warning: RAS->LPS conversion failed, returning RAS: {e}")
|
| 993 |
+
return merged, branch_junctions_lps
|
| 994 |
|
| 995 |
|
| 996 |
# Converts VTK polydata into a python list that contains line segments information (unique segment id, points in that segment, radius of each point, label)
|
|
|
|
| 1048 |
|
| 1049 |
|
| 1050 |
# Computes bifurcation points which represent start of any branching arteries
|
| 1051 |
+
def find_bifurcation_points(centerlines, known_junctions=None):
|
| 1052 |
# Extracts centerline data
|
| 1053 |
pts = centerlines.GetPoints()
|
| 1054 |
lines = centerlines.GetLines()
|
|
|
|
| 1064 |
|
| 1065 |
bifurcations = []
|
| 1066 |
max_radius = 0.0
|
| 1067 |
+
found_ids = set()
|
| 1068 |
|
| 1069 |
# Degree 1 = endpoint, 2 = mid-segment, 3+ = bifurcation
|
| 1070 |
for point_id, deg in degree.items():
|
|
|
|
| 1072 |
pt = pts.GetPoint(point_id)
|
| 1073 |
radius = radius_array.GetValue(point_id)
|
| 1074 |
max_radius = max(max_radius, radius)
|
| 1075 |
+
found_ids.add(point_id)
|
| 1076 |
bifurcations.append({
|
| 1077 |
'id': point_id,
|
| 1078 |
'x': float(pt[0]),
|
|
|
|
| 1081 |
'radius': float(radius),
|
| 1082 |
})
|
| 1083 |
|
| 1084 |
+
# Supplement with known junction coordinates from the pipeline (branch contact points)
|
| 1085 |
+
# This ensures bifurcations are detected even if vtkCleanPolyData didn't fully merge junction point IDs
|
| 1086 |
+
if known_junctions:
|
| 1087 |
+
locator = vtk.vtkPointLocator()
|
| 1088 |
+
locator.SetDataSet(centerlines)
|
| 1089 |
+
locator.BuildLocator()
|
| 1090 |
+
for junction_xyz in known_junctions:
|
| 1091 |
+
closest_id = locator.FindClosestPoint(junction_xyz)
|
| 1092 |
+
if closest_id < 0 or closest_id in found_ids:
|
| 1093 |
+
continue
|
| 1094 |
+
pt = pts.GetPoint(closest_id)
|
| 1095 |
+
radius = radius_array.GetValue(closest_id) if radius_array else 0.0
|
| 1096 |
+
max_radius = max(max_radius, radius)
|
| 1097 |
+
found_ids.add(closest_id)
|
| 1098 |
+
bifurcations.append({
|
| 1099 |
+
'id': closest_id,
|
| 1100 |
+
'x': float(pt[0]),
|
| 1101 |
+
'y': float(pt[1]),
|
| 1102 |
+
'z': float(pt[2]),
|
| 1103 |
+
'radius': float(radius),
|
| 1104 |
+
})
|
| 1105 |
+
|
| 1106 |
# Sort bottom to top (iliac bifurcations first then abdomen then thoracic)
|
| 1107 |
bifurcations.sort(key=lambda b: b['z'])
|
| 1108 |
return bifurcations, max_radius
|
|
|
|
| 1361 |
|
| 1362 |
|
| 1363 |
# Main Pipeline for extracting centerline data, labeling bifurcations and arteries, computing ostium and reference point positions
|
| 1364 |
+
def extract_centerline_data(centerlines, branch_junctions=None):
|
| 1365 |
# Parse VTK polydata into Python segment dictionaries
|
| 1366 |
segments, point_to_segments = parse_segments(centerlines)
|
| 1367 |
|
| 1368 |
+
# Identify junction points (bifurcations), supplemented with known branch contact points
|
| 1369 |
+
all_bifurcations, max_radius = find_bifurcation_points(centerlines, known_junctions=branch_junctions)
|
| 1370 |
|
| 1371 |
# Label the 4 abdominal arteries and compute their direction vectors
|
| 1372 |
abdomen_bifs, abdomen_bifuraction_ids, abdomen_candidates = identify_abdominal_arteries(
|
|
|
|
| 1404 |
image, origin, direction = load_nrrd_as_vtk_image(filepath)
|
| 1405 |
|
| 1406 |
# Slicer-style surface processing -> Voronoi centerline extraction
|
| 1407 |
+
centerlines, branch_junctions = compute_centerlines_network(image, origin, direction)
|
| 1408 |
|
| 1409 |
# Extract labelled segments and artery bifurcation data
|
| 1410 |
+
data = extract_centerline_data(centerlines, branch_junctions=branch_junctions)
|
| 1411 |
|
| 1412 |
# Write success JSON to stdout
|
| 1413 |
json.dump({'status': 'success', 'data': data}, sys.stdout)
|
server.py
CHANGED
|
@@ -56,10 +56,10 @@ def extract():
|
|
| 56 |
image, origin, direction = load_nrrd_as_vtk_image(tmp.name)
|
| 57 |
|
| 58 |
# Slicer-style surface processing -> Voronoi centerline extraction
|
| 59 |
-
centerlines = compute_centerlines_network(image, origin, direction)
|
| 60 |
|
| 61 |
# Extract labelled segments and artery bifurcation data
|
| 62 |
-
data = extract_centerline_data(centerlines)
|
| 63 |
|
| 64 |
# Include the NRRD image's physical extent so the frontend can normalize the centerline
|
| 65 |
dims = image.GetDimensions()
|
|
|
|
| 56 |
image, origin, direction = load_nrrd_as_vtk_image(tmp.name)
|
| 57 |
|
| 58 |
# Slicer-style surface processing -> Voronoi centerline extraction
|
| 59 |
+
centerlines, branch_junctions = compute_centerlines_network(image, origin, direction)
|
| 60 |
|
| 61 |
# Extract labelled segments and artery bifurcation data
|
| 62 |
+
data = extract_centerline_data(centerlines, branch_junctions=branch_junctions)
|
| 63 |
|
| 64 |
# Include the NRRD image's physical extent so the frontend can normalize the centerline
|
| 65 |
dims = image.GetDimensions()
|