Spaces:
Sleeping

mosta02 commited on
Commit
622eeec
·
verified ·
1 Parent(s): 38006ac

Upload 2 files

Browse files
Files changed (2) hide show
  1. centerline_extraction.py +79 -908
  2. server.py +66 -63
centerline_extraction.py CHANGED
@@ -3,11 +3,7 @@ import sys
3
  import json
4
  import math
5
  from collections import defaultdict
6
- from vmtk import vtkvmtkComputationalGeometryPython as vtkvmtkComputationalGeometry
7
- from vmtk import vtkvmtkMiscPython as vtkvmtkMisc
8
- from vtk.util import numpy_support
9
- import numpy as np
10
- import SimpleITK as sitk
11
  import vtk
12
 
13
  # The 4 abdominal artery labels, assigned top to bottom
@@ -71,918 +67,91 @@ def calculate_average_direction(points, is_start_at_bifurcation, limit_points):
71
  return normalize_vector((total[0] / valid, total[1] / valid, total[2] / valid))
72
 
73
 
74
- # ═══════════════════════════════════════════════════════════════════════════════
75
- # COORDINATE CONVERSION HELPERS (LPS ↔ RAS)
76
- # Medical imaging stores data in LPS (Left-Posterior-Superior) coordinates.
77
- # 3D Slicer's surface processing works in RAS (Right-Anterior-Superior).
78
- # Conversion simply flips X and Y: scale(-1, -1, 1).
79
- # The transform is its own inverse, so the same op converts LPS→RAS and RAS→LPS.
80
- # ═══════════════════════════════════════════════════════════════════════════════
81
-
82
- def lps_polydata_to_ras(polydata):
83
- """Convert polydata from LPS to RAS by flipping X and Y axes."""
84
- transform = vtk.vtkTransform()
85
- transform.Scale(-1.0, -1.0, 1.0)
86
- tf = vtk.vtkTransformPolyDataFilter()
87
- tf.SetInputData(polydata)
88
- tf.SetTransform(transform)
89
- tf.Update()
90
- return tf.GetOutput()
91
-
92
-
93
- def lps_to_ras(endpoints):
94
- """Convert list of (x, y, z, is_start) tuples from LPS to RAS."""
95
- return [(-x, -y, z, is_start) for x, y, z, is_start in endpoints]
96
-
97
-
98
- def ras_polydata_to_lps(polydata):
99
- """Convert polydata from RAS back to LPS (same flip: scale -1,-1,1)."""
100
- transform = vtk.vtkTransform()
101
- transform.Scale(-1.0, -1.0, 1.0)
102
- tf = vtk.vtkTransformPolyDataFilter()
103
- tf.SetInputData(polydata)
104
- tf.SetTransform(transform)
105
- tf.Update()
106
- return tf.GetOutput()
107
-
108
-
109
- # ═══════════════════════════════════════════════════════════════════════════════
110
- # NRRD IMAGE LOADING (SimpleITK-based)
111
- # Reads the NRRD segmentation using SimpleITK instead of vmtkImageReader.
112
- # SimpleITK correctly preserves the full 3×3 direction cosine matrix, which
113
- # vtkImageData alone cannot store (only origin + spacing). This is critical
114
- # for oblique acquisitions where the scan axes don't align with LPS.
115
- # Also auto-binarizes multi-label segmentations (any non-zero voxel → 1).
116
- # Returns: (vtkImageData, origin_tuple, direction_9tuple)
117
- # ═══════════════════════════════════════════════════════════════════════════════
118
-
119
- def load_nrrd_as_vtk_image(path):
120
- """Read NRRD segmentation via SimpleITK, binarize, and convert to vtkImageData."""
121
- sitk_img = sitk.ReadImage(path)
122
- arr = sitk.GetArrayFromImage(sitk_img)
123
-
124
- # Auto-binarize: if segmentation has multiple labels, collapse to binary (0/1)
125
- unique_vals = np.unique(arr)
126
- if not (unique_vals.size == 2 and set(unique_vals.tolist()) <= {0, 1}):
127
- print(f"Warning: segmentation contains values {unique_vals}, binarizing (>0 -> 1)")
128
- arr = (arr > 0).astype(np.uint8)
129
-
130
- spacing = sitk_img.GetSpacing() # (sx, sy, sz) in mm
131
- origin = sitk_img.GetOrigin() # (ox, oy, oz) in mm
132
- direction = sitk_img.GetDirection() # 9-tuple: row-major 3×3 direction cosine matrix
133
-
134
- # Build vtkImageData matching the SimpleITK geometry
135
- vtk_img = vtk.vtkImageData()
136
- vtk_img.SetDimensions(arr.shape[::-1]) # SimpleITK is (z,y,x), VTK needs (x,y,z)
137
- vtk_img.SetSpacing(spacing)
138
- vtk_img.SetOrigin(origin)
139
-
140
- vtk_arr = numpy_support.numpy_to_vtk(num_array=arr.flatten(order="C"), deep=True)
141
- vtk_arr.SetName("Image")
142
- vtk_img.GetPointData().SetScalars(vtk_arr)
143
-
144
- return vtk_img, origin, direction
145
-
146
-
147
- # ═══════════════════════════════════════════════════════════════════════════════
148
- # SLICER-STYLE CLOSED SURFACE EXTRACTION
149
- # Converts a binary labelmap into a closed 3D surface mesh following the same
150
- # algorithm as 3D Slicer's vtkBinaryLabelmapToClosedSurfaceConversionRule:
151
- # 1. Cast to unsigned short (required by discrete surface filters)
152
- # 2. Pad by 1 voxel if non-background voxels touch the image border
153
- # 3. Work in IJK (identity origin/spacing) for clean surface extraction
154
- # 4. Discrete Flying Edges iso-surface (faster + cleaner than Marching Cubes)
155
- # 5. Optional DecimatePro decimation
156
- # 6. Windowed Sinc smoothing with Slicer's passband/iteration mapping:
157
- # passband = 10^(-4 × smoothing), iterations = 20 + smoothing × 40
158
- # 7. Transform from IJK back to physical coords via 4×4 affine matrix
159
- # 8. Compute consistent normals
160
- # 9. Optionally convert LPS → RAS
161
- # ═══════════════════════════════════════════════════════════════════════════════
162
-
163
- def _is_labelmap_padding_necessary(image_data):
164
- """Check if any non-background voxels touch the image border (would create open edges)."""
165
- extent = image_data.GetExtent()
166
- if extent[0] > extent[1] or extent[2] > extent[3] or extent[4] > extent[5]:
167
- return False
168
- dims = image_data.GetDimensions()
169
- scalars = image_data.GetPointData().GetScalars()
170
- if scalars is None:
171
- return False
172
- arr = numpy_support.vtk_to_numpy(scalars).reshape((dims[2], dims[1], dims[0]))
173
- return (
174
- arr[0, :, :].any() or arr[-1, :, :].any() or
175
- arr[:, 0, :].any() or arr[:, -1, :].any() or
176
- arr[:, :, 0].any() or arr[:, :, -1].any()
177
- )
178
 
 
 
 
 
 
 
179
 
180
- def create_closed_surface_polydata(
181
- image, origin, direction, label_value=1, smoothing=0.5, decimation=0.0,
182
- keep_all_components=True, to_ras=True, conversion_method="flying_edges",
183
- ):
184
- """Slicer-style closed surface extraction from a binary labelmap."""
185
- smoothing = max(0.0, min(1.0, float(smoothing)))
186
- decimation = max(0.0, min(1.0, float(decimation)))
187
- label_value = int(label_value)
188
-
189
- # Step 1: Cast to unsigned short (discrete surface filters require integer types)
190
- cast = vtk.vtkImageCast()
191
- cast.SetInputData(image)
192
- cast.SetOutputScalarTypeToUnsignedShort()
193
- cast.Update()
194
- image_data = cast.GetOutput()
195
-
196
- # Step 2: Pad by 1 voxel if border voxels are non-background (prevents open edges)
197
- if _is_labelmap_padding_necessary(image_data):
198
- padder = vtk.vtkImageConstantPad()
199
- padder.SetInputData(image_data)
200
- extent = list(image_data.GetExtent())
201
- padder.SetOutputWholeExtent(
202
- extent[0] - 1, extent[1] + 1,
203
- extent[2] - 1, extent[3] + 1,
204
- extent[4] - 1, extent[5] + 1,
205
- )
206
- padder.Update()
207
- image_data = padder.GetOutput()
208
-
209
- # Step 3: Work in IJK space (identity geometry) for cleaner isosurface extraction
210
- image_identity = vtk.vtkImageData()
211
- image_identity.ShallowCopy(image_data)
212
- image_identity.SetOrigin(0.0, 0.0, 0.0)
213
- image_identity.SetSpacing(1.0, 1.0, 1.0)
214
-
215
- # Step 4: Surface extraction — Discrete Flying Edges (fallback: Discrete Marching Cubes)
216
- if conversion_method == "surface_nets":
217
- try:
218
- surface_filter = vtk.vtkSurfaceNets3D()
219
- surface_filter.SetInputData(image_identity)
220
- surface_filter.SmoothingOff()
221
- surface_filter.SetValue(0, label_value)
222
- surface_filter.Update()
223
- except AttributeError:
224
- raise RuntimeError("vtkSurfaceNets3D not available in this VTK build")
225
- else:
226
- try:
227
- surface_filter = vtk.vtkDiscreteFlyingEdges3D()
228
- except AttributeError:
229
- surface_filter = vtk.vtkDiscreteMarchingCubes()
230
- surface_filter.SetInputData(image_identity)
231
- surface_filter.ComputeGradientsOff()
232
- surface_filter.ComputeNormalsOff()
233
- surface_filter.SetValue(0, label_value)
234
- surface_filter.Update()
235
- surface = surface_filter.GetOutput()
236
-
237
- # Step 5: Optional decimation (Slicer uses DecimatePro)
238
- if decimation > 0.0:
239
- decimator = vtk.vtkDecimatePro()
240
- decimator.SetInputData(surface)
241
- decimator.SetFeatureAngle(60)
242
- decimator.SplittingOff()
243
- decimator.PreserveTopologyOn()
244
- decimator.SetMaximumError(1)
245
- decimator.SetTargetReduction(decimation)
246
- decimator.Update()
247
- surface = decimator.GetOutput()
248
-
249
- # Step 6: Windowed Sinc smoothing with Slicer's passband/iteration mapping
250
- if smoothing > 0.0 and conversion_method != "surface_nets":
251
- pass_band = pow(10.0, -4.0 * smoothing)
252
- iterations = int(20 + smoothing * 40)
253
- smoother = vtk.vtkWindowedSincPolyDataFilter()
254
- smoother.SetInputData(surface)
255
- smoother.SetNumberOfIterations(iterations)
256
- smoother.SetPassBand(pass_band)
257
- smoother.BoundarySmoothingOff()
258
- smoother.FeatureEdgeSmoothingOff()
259
- smoother.NonManifoldSmoothingOn()
260
- smoother.NormalizeCoordinatesOn()
261
- smoother.Update()
262
- surface = smoother.GetOutput()
263
-
264
- # Step 7: Transform from IJK back to physical space via 4×4 affine matrix
265
- # The affine combines direction cosines, spacing, and origin into one transform
266
- d = direction if direction and len(direction) == 9 else (1, 0, 0, 0, 1, 0, 0, 0, 1)
267
- spacing = image.GetSpacing() if hasattr(image, "GetSpacing") else (1.0, 1.0, 1.0)
268
- ox, oy, oz = origin
269
- mat = vtk.vtkMatrix4x4()
270
- mat.Identity()
271
- mat.SetElement(0, 0, d[0] * spacing[0]); mat.SetElement(0, 1, d[1] * spacing[1]); mat.SetElement(0, 2, d[2] * spacing[2]); mat.SetElement(0, 3, ox)
272
- mat.SetElement(1, 0, d[3] * spacing[0]); mat.SetElement(1, 1, d[4] * spacing[1]); mat.SetElement(1, 2, d[5] * spacing[2]); mat.SetElement(1, 3, oy)
273
- mat.SetElement(2, 0, d[6] * spacing[0]); mat.SetElement(2, 1, d[7] * spacing[1]); mat.SetElement(2, 2, d[8] * spacing[2]); mat.SetElement(2, 3, oz)
274
-
275
- transform = vtk.vtkTransform()
276
- transform.SetMatrix(mat)
277
- tf = vtk.vtkTransformPolyDataFilter()
278
- tf.SetInputData(surface)
279
- tf.SetTransform(transform)
280
- tf.Update()
281
- transformed = tf.GetOutput()
282
-
283
- # Step 8: Compute consistent normals
284
- if smoothing > 0.0 or conversion_method == "flying_edges":
285
- normals_filter = vtk.vtkPolyDataNormals()
286
- normals_filter.SetInputData(transformed)
287
- normals_filter.ConsistencyOn()
288
- normals_filter.SplittingOff()
289
- normals_filter.Update()
290
- transformed = normals_filter.GetOutput()
291
-
292
- # Optional: keep only largest connected component
293
- if not keep_all_components:
294
- conn = vtk.vtkPolyDataConnectivityFilter()
295
- conn.SetInputData(transformed)
296
- conn.SetExtractionModeToLargestRegion()
297
- conn.Update()
298
- transformed = conn.GetOutput()
299
-
300
- # Step 9: Convert LPS → RAS if requested
301
- if to_ras:
302
- transformed = lps_polydata_to_ras(transformed)
303
-
304
- return transformed
305
-
306
-
307
- # ═══════════════════════════════════════════════════════════════════════════════
308
- # SURFACE PREPROCESSING FOR NETWORK EXTRACTION
309
- # Prepares the surface mesh for VMTK's skeleton (network) extraction:
310
- # 1. Decimate to a target point count (vtkQuadricDecimation with attribute
311
- # error metric and volume preservation — better shape than DecimatePro)
312
- # 2. Windowed Sinc smoothing for mesh quality
313
- # 3. Clean: merge duplicate points, remove degenerate cells
314
- # 4. Triangulate: VMTK requires pure triangle meshes
315
- # 5. Optional linear subdivision for extra detail
316
- # 6. Orient normals consistently (required for network extraction quality)
317
- # ═══════════════════════════════════════════════════════════════════════════════
318
-
319
- def preprocess_surface_for_network(surface_polydata, target_number_of_points=5000,
320
- decimation_aggressiveness=4.0, subdivide=False):
321
- """Decimate → smooth → clean → triangulate → (subdivide) → orient normals."""
322
- num_points = surface_polydata.GetNumberOfPoints()
323
- if num_points == 0:
324
- raise ValueError("Input surface is empty")
325
-
326
- # Reduce point count to target via quadric decimation
327
- reduction_factor = (num_points - target_number_of_points) / num_points
328
- decimated = surface_polydata
329
- if reduction_factor > 0.0:
330
- decim = vtk.vtkQuadricDecimation()
331
- decim.SetInputData(surface_polydata)
332
- decim.SetTargetReduction(min(max(reduction_factor, 0.0), 0.99))
333
- decim.AttributeErrorMetricOn()
334
- decim.VolumePreservationOn()
335
- decim.Update()
336
- decimated = decim.GetOutput()
337
-
338
- # Smooth to improve mesh quality for network extraction
339
  smoother = vtk.vtkWindowedSincPolyDataFilter()
340
- smoother.SetInputData(decimated)
341
- smoother.SetNumberOfIterations(10)
342
- smoother.SetPassBand(0.1)
343
- smoother.NonManifoldSmoothingOn()
344
- smoother.NormalizeCoordinatesOn()
 
 
345
  smoother.Update()
346
 
347
- # Clean: merge coincident points, remove degenerate cells
348
- surface_cleaner = vtk.vtkCleanPolyData()
349
- surface_cleaner.SetInputData(smoother.GetOutput())
350
- surface_cleaner.Update()
351
-
352
- # Triangulate: VMTK requires pure triangle meshes
353
- surface_triangulator = vtk.vtkTriangleFilter()
354
- surface_triangulator.SetInputData(surface_cleaner.GetOutput())
355
- surface_triangulator.PassLinesOff()
356
- surface_triangulator.PassVertsOff()
357
- surface_triangulator.Update()
358
-
359
- # Optional linear subdivision for extra detail
360
- subdivided = surface_triangulator.GetOutput()
361
- if subdivide:
362
- subdiv = vtk.vtkLinearSubdivisionFilter()
363
- subdiv.SetInputData(surface_triangulator.GetOutput())
364
- subdiv.SetNumberOfSubdivisions(1)
365
- subdiv.Update()
366
- if subdiv.GetOutput().GetNumberOfPoints() > 0:
367
- subdivided = subdiv.GetOutput()
368
-
369
- # Orient normals consistently (important for network extraction quality)
370
- normals_filter = vtk.vtkPolyDataNormals()
371
- normals_filter.SetInputData(subdivided)
372
- normals_filter.SetAutoOrientNormals(1)
373
- normals_filter.SetFlipNormals(0)
374
- normals_filter.SetConsistency(1)
375
- normals_filter.SplittingOff()
376
- normals_filter.Update()
377
- return normals_filter.GetOutput()
378
-
379
-
380
- def open_surface_at_point(polydata, hole_position=None, hole_point_index=None):
381
- """Delete one cell at the specified point to create a small opening in the mesh.
382
-
383
- VMTK's network extraction requires at least one opening to enter the vessel.
384
- This mimics Slicer's approach of opening the mesh at a known boundary point.
385
- """
386
- if hole_point_index is None:
387
- locator = vtk.vtkPointLocator()
388
- locator.SetDataSet(polydata)
389
- locator.BuildLocator()
390
- hole_point_index = locator.FindClosestPoint(hole_position)
391
- if hole_point_index < 0:
392
- raise ValueError("open_surface_at_point: invalid hole point")
393
-
394
- polydata.BuildLinks()
395
- cell_ids = vtk.vtkIdList()
396
- polydata.GetPointCells(hole_point_index, cell_ids)
397
- if cell_ids.GetNumberOfIds() > 0:
398
- polydata.DeleteCell(cell_ids.GetId(0)) # Only remove the first cell (like Slicer)
399
- polydata.RemoveDeletedCells()
400
-
401
-
402
- # ═══════════════════════════════════════════════════════════════════════════════
403
- # NETWORK SKELETON EXTRACTION (Slicer ExtractCenterline.extractNetwork)
404
- # Generates a centerline skeleton using the same approach as Slicer's
405
- # ExtractCenterline module (extractNetwork method):
406
- # 1. Build closed surface from segmentation (if not already provided)
407
- # 2. Preprocess: decimate, smooth, clean, triangulate
408
- # 3. Open a small hole in the mesh at a boundary point
409
- # 4. Run vtkvmtkPolyDataNetworkExtraction to trace the skeleton
410
- # 5. Optionally compute geometric properties:
411
- # Length, Curvature, Torsion, Tortuosity, Frenet frame vectors
412
- # The output has Radius, Topology, and Marks arrays on each point.
413
- # Endpoints (degree-1) are vessel tips; degree-3+ points are bifurcations.
414
- # ═══════════════════════════════════════════════════════════════════════════════
415
-
416
- def skeletonize(
417
- image=None, origin=None, direction=None, surface_polydata=None,
418
- label_value=1, smoothing=0.5, decimation=0.0, keep_all_components=True,
419
- target_number_of_points=5000, decimation_aggressiveness=4.0, subdivide=False,
420
- start_point=None, compute_geometry=True,
421
- ):
422
- """Generate a centerline network skeleton from a segmentation or surface."""
423
- # Build surface from segmentation if not provided
424
- if surface_polydata is None:
425
- if image is None:
426
- raise ValueError("image is required when surface_polydata is not provided")
427
- if origin is None:
428
- origin = image.GetOrigin() if hasattr(image, "GetOrigin") else (0.0, 0.0, 0.0)
429
- if direction is None:
430
- direction = (1, 0, 0, 0, 1, 0, 0, 0, 1)
431
- surface_polydata = create_closed_surface_polydata(
432
- image, origin, direction,
433
- label_value=label_value, smoothing=smoothing, decimation=decimation,
434
- keep_all_components=keep_all_components, to_ras=True,
435
- )
436
-
437
- # Decimate, smooth, clean, triangulate the surface
438
- prepped_surface = preprocess_surface_for_network(
439
- surface_polydata,
440
- target_number_of_points=target_number_of_points,
441
- decimation_aggressiveness=decimation_aggressiveness,
442
- subdivide=subdivide,
443
  )
444
-
445
- # Choose where to open the surface (default: corner of bounding box)
446
- if start_point is not None:
447
- start_position = start_point
448
- else:
449
- bounds = prepped_surface.GetBounds()
450
- start_position = (bounds[0], bounds[2], bounds[4])
451
-
452
- # Open a small hole so the algorithm can enter the vessel
453
- open_surface_at_point(prepped_surface, start_position)
454
-
455
- # Run VMTK's network extraction (vtkvmtkPolyDataNetworkExtraction)
456
- # Traces the medial axis using maximal inscribed sphere approach
457
- network_extraction = vtkvmtkMisc.vtkvmtkPolyDataNetworkExtraction()
458
- network_extraction.SetInputData(prepped_surface)
459
- network_extraction.SetAdvancementRatio(1.05)
460
- network_extraction.SetRadiusArrayName("Radius")
461
- network_extraction.SetTopologyArrayName("Topology")
462
- network_extraction.SetMarksArrayName("Marks")
463
- network_extraction.Update()
464
-
465
- network_output = network_extraction.GetOutput()
466
- if not compute_geometry:
467
- return network_output
468
-
469
- # Compute geometric properties: Length, Curvature, Torsion, Tortuosity, Frenet frame
470
- centerline_geometry = vtkvmtkComputationalGeometry.vtkvmtkCenterlineGeometry()
471
- centerline_geometry.SetInputData(network_output)
472
- centerline_geometry.SetLengthArrayName("Length")
473
- centerline_geometry.SetCurvatureArrayName("Curvature")
474
- centerline_geometry.SetTorsionArrayName("Torsion")
475
- centerline_geometry.SetTortuosityArrayName("Tortuosity")
476
- centerline_geometry.SetFrenetTangentArrayName("FrenetTangent")
477
- centerline_geometry.SetFrenetNormalArrayName("FrenetNormal")
478
- centerline_geometry.SetFrenetBinormalArrayName("FrenetBinormal")
479
- centerline_geometry.Update()
480
- return centerline_geometry.GetOutput()
481
-
482
-
483
- # ═══════════════════════════════════════════════════════════════════════════════
484
- # ENDPOINT DETECTION (Aorta + Iliacs + Branches)
485
- # Analyzes the network skeleton to automatically detect:
486
- # - Aortic root: endpoint with the largest inscribed sphere radius
487
- # - Iliac endpoints: below the aorta, sorted into left/right by X coordinate
488
- # - Branch endpoints: all remaining endpoints (visceral arteries, etc.)
489
- # Each branch endpoint also traces back along the skeleton to find its
490
- # bifurcation point (first degree-3+ node encountered when walking inward).
491
- # ═══════════════════════════════════════════════════════════════════════════════
492
-
493
- def find_bifurcation_point(network_polydata, endpoint_id):
494
- """Trace back from an endpoint along the skeleton to find its bifurcation point.
495
-
496
- Walks inward from a vessel tip, following the skeleton cells, until it
497
- reaches a point connected to 3+ cells (a junction where vessels split).
498
- """
499
- network_polydata.BuildLinks(0)
500
- points = network_polydata.GetPoints()
501
- current_id = endpoint_id
502
- visited = set([current_id])
503
-
504
- while True:
505
- cell_ids = vtk.vtkIdList()
506
- network_polydata.GetPointCells(current_id, cell_ids)
507
- num_cells = cell_ids.GetNumberOfIds()
508
-
509
- # Degree >= 3 means we reached a bifurcation
510
- if num_cells >= 3:
511
- return points.GetPoint(current_id)
512
-
513
- # Find the next unvisited neighbour along the skeleton
514
- next_id = None
515
- for c in range(num_cells):
516
- cell = network_polydata.GetCell(cell_ids.GetId(c))
517
- for j in range(cell.GetNumberOfPoints()):
518
- pid = cell.GetPointId(j)
519
- if pid != current_id and pid not in visited:
520
- next_id = pid
521
- break
522
- if next_id is not None:
523
- break
524
-
525
- if next_id is None:
526
- return None # Reached dead end without finding bifurcation
527
-
528
- visited.add(next_id)
529
- current_id = next_id
530
-
531
-
532
- def detect_aorta_and_iliacs(network_polydata):
533
- """Auto-detect aortic root, iliac endpoints, and branch endpoints from the skeleton.
534
-
535
- Returns:
536
- aorta_iliac_endpoints: list of (x, y, z, is_start) tuples (aorta is_start=True, iliacs False)
537
- branch_endpoints: list of dicts with 'endpoint' (x,y,z) and 'bifurcation' (x,y,z or None)
538
- """
539
- # Clean and prepare the network polydata
540
- cleaner = vtk.vtkCleanPolyData()
541
- cleaner.SetInputData(network_polydata)
542
- cleaner.Update()
543
- network = cleaner.GetOutput()
544
- network.BuildCells()
545
- network.BuildLinks(0)
546
-
547
- points = network.GetPoints()
548
- if points is None or network.GetNumberOfCells() == 0:
549
- return [], []
550
-
551
- radius_array = network.GetPointData().GetArray("Radius")
552
- if radius_array is None:
553
- radius_array = network.GetPointData().GetArray("MaximumInscribedSphereRadius")
554
-
555
- # Find all endpoints: points connected to exactly 1 cell (vessel tips)
556
- endpoint_ids = vtk.vtkIdList()
557
- tmp_point_cells = vtk.vtkIdList()
558
- for cell_id in range(network.GetNumberOfCells()):
559
- cell = network.GetCell(cell_id)
560
- num_pts = cell.GetNumberOfPoints()
561
- if num_pts < 2:
562
- continue
563
- for pid in (cell.GetPointId(0), cell.GetPointId(num_pts - 1)):
564
- network.GetPointCells(pid, tmp_point_cells)
565
- if tmp_point_cells.GetNumberOfIds() == 1:
566
- endpoint_ids.InsertUniqueId(pid)
567
-
568
- if endpoint_ids.GetNumberOfIds() < 3:
569
- print(f"Warning: only {endpoint_ids.GetNumberOfIds()} endpoints found (need >= 3)")
570
- return [], []
571
-
572
- # Collect endpoint info
573
- endpoints_info = []
574
- for i in range(endpoint_ids.GetNumberOfIds()):
575
- pid = endpoint_ids.GetId(i)
576
- pos = points.GetPoint(pid)
577
- radius = radius_array.GetValue(pid) if radius_array else 0.0
578
- endpoints_info.append({
579
- 'id': pid, 'pos': pos,
580
- 'x': pos[0], 'y': pos[1], 'z': pos[2], 'radius': radius,
581
- })
582
-
583
- # Aortic root = endpoint with the largest inscribed sphere radius
584
- aorta = max(endpoints_info, key=lambda ep: ep['radius'])
585
- aorta_z = aorta['z']
586
-
587
- # Iliac candidates = endpoints below the aorta (lower Z in LPS = more caudal)
588
- iliac_candidates = [ep for ep in endpoints_info if ep['z'] < aorta_z]
589
- if len(iliac_candidates) < 2:
590
- # Fallback: take the two furthest endpoints from aorta
591
- iliac_candidates = sorted(
592
- endpoints_info,
593
- key=lambda ep: vtk.vtkMath.Distance2BetweenPoints(aorta['pos'], ep['pos']),
594
- reverse=True,
595
- )[:2]
596
-
597
- # Sort iliacs by X to separate left/right
598
- iliac_candidates.sort(key=lambda ep: ep['x'])
599
- left_iliacs = [ep for ep in iliac_candidates if ep['x'] < 0]
600
- right_iliacs = [ep for ep in iliac_candidates if ep['x'] >= 0]
601
-
602
- def sort_by_z_and_radius(iliacs):
603
- return sorted(iliacs, key=lambda ep: (ep['z'], -ep['radius']))
604
-
605
- left_sorted = sort_by_z_and_radius(left_iliacs)
606
- right_sorted = sort_by_z_and_radius(right_iliacs)
607
-
608
- left_external = left_sorted[0] if len(left_sorted) > 0 else None
609
- left_internal = left_sorted[1] if len(left_sorted) > 1 else None
610
- right_external = right_sorted[0] if len(right_sorted) > 0 else None
611
- right_internal = right_sorted[1] if len(right_sorted) > 1 else None
612
-
613
- # Build aorta + iliac endpoint list: aorta is the source (is_start=True)
614
- result = [(aorta['x'], aorta['y'], aorta['z'], True)]
615
- iliac_ids = set()
616
- for ep in (right_external, right_internal, left_external, left_internal):
617
- if ep:
618
- result.append((ep['x'], ep['y'], ep['z'], False))
619
- iliac_ids.add(ep['id'])
620
-
621
- # Everything else is a branch endpoint — also trace to its skeleton bifurcation
622
- branch_endpoints = []
623
- for ep in endpoints_info:
624
- if ep['id'] != aorta['id'] and ep['id'] not in iliac_ids:
625
- bif_pt = find_bifurcation_point(network, ep['id'])
626
- branch_endpoints.append({
627
- 'endpoint': (ep['x'], ep['y'], ep['z']),
628
- 'bifurcation': bif_pt,
629
- })
630
-
631
- # Diagnostic output
632
- print(f" Aorta (source): {aorta['x']:.2f}, {aorta['y']:.2f}, {aorta['z']:.2f} (R={aorta['radius']:.2f})")
633
- if right_external: print(f" Right ext iliac: {right_external['x']:.2f}, {right_external['y']:.2f}, {right_external['z']:.2f}")
634
- if left_external: print(f" Left ext iliac: {left_external['x']:.2f}, {left_external['y']:.2f}, {left_external['z']:.2f}")
635
- if branch_endpoints: print(f" {len(branch_endpoints)} additional branch endpoint(s)")
636
-
637
- return result, branch_endpoints
638
-
639
-
640
- # ═══════════════════════════════════════════════════════════════════════════════
641
- # VORONOI-BASED CENTERLINE EXTRACTION (Slicer ExtractCenterlineLogic)
642
- # Uses VMTK's vtkvmtkPolyDataCenterlines to compute accurate centerline paths.
643
- # Unlike the network skeleton (which approximates the medial axis), this method:
644
- # 1. Caps all open mesh ends (vtkvmtkCapPolyData)
645
- # 2. Computes the Voronoi diagram of the interior volume
646
- # 3. Finds minimum-cost paths between source and target seeds
647
- # Cost function = 1/R (inversely proportional to inscribed sphere radius),
648
- # so the path naturally follows the vessel center
649
- # 4. Optionally applies Laplacian smoothing to reduce zigzag artifacts
650
- # ══════════════════════════════════════════════════════════���════════════════════
651
-
652
- def smooth_centerline_polydata(centerline_polydata, iterations=20, relaxation_factor=0.1):
653
- """Apply Laplacian smoothing to a centerline polydata while keeping endpoints fixed."""
654
- smoother = vtk.vtkSmoothPolyDataFilter()
655
- smoother.SetInputData(centerline_polydata)
656
- smoother.SetNumberOfIterations(iterations)
657
- smoother.SetRelaxationFactor(relaxation_factor)
658
- smoother.BoundarySmoothingOff() # Keep boundary endpoints fixed
659
- smoother.FeatureEdgeSmoothingOff()
660
- smoother.Update()
661
-
662
- smoothed = vtk.vtkPolyData()
663
- smoothed.DeepCopy(smoother.GetOutput())
664
- return smoothed
665
-
666
-
667
- def extract_centerline_from_surface(surface_polydata, endpoints, curve_sampling_distance=1.0,
668
- smooth_iterations=40, smooth_relaxation=0.1):
669
- """Voronoi-based centerline extraction (mirrors Slicer's ExtractCenterlineLogic).
670
-
671
- Args:
672
- surface_polydata: vessel surface mesh (in RAS coordinates)
673
- endpoints: list of (x, y, z, is_start) – is_start=True for source seeds
674
- curve_sampling_distance: resampling step length along the centerline
675
- smooth_iterations: Laplacian smoothing passes (0 to disable)
676
- smooth_relaxation: fraction each point moves per smoothing pass
677
-
678
- Returns:
679
- (centerline_polydata, voronoi_polydata) tuple
680
- """
681
- if not endpoints or len(endpoints) < 2:
682
- raise ValueError("At least two endpoints are needed for centerline extraction")
683
-
684
- # Cap open mesh ends (required for Voronoi computation inside the volume)
685
- capper = vtkvmtkComputationalGeometry.vtkvmtkCapPolyData()
686
- capper.SetInputData(surface_polydata)
687
- capper.SetDisplacement(0.0)
688
- capper.SetInPlaneDisplacement(0.0)
689
- capper.Update()
690
- tube_polydata = capper.GetOutput()
691
-
692
- # Classify seeds: is_start=True → source, is_start=False → target
693
- source_ids = vtk.vtkIdList()
694
- target_ids = vtk.vtkIdList()
695
- locator = vtk.vtkPointLocator()
696
- locator.SetDataSet(tube_polydata)
697
- locator.BuildLocator()
698
-
699
- has_explicit_start = any(p[3] for p in endpoints)
700
- for idx, (x, y, z, is_start) in enumerate(endpoints):
701
- is_target = not is_start
702
- if not has_explicit_start and idx == 0:
703
- is_target = False
704
- pid = locator.FindClosestPoint((x, y, z))
705
- if is_target:
706
- target_ids.InsertNextId(pid)
707
- else:
708
- source_ids.InsertNextId(pid)
709
-
710
- # Run VMTK's Voronoi-based centerline filter
711
- cl_filter = vtkvmtkComputationalGeometry.vtkvmtkPolyDataCenterlines()
712
- cl_filter.SetInputData(tube_polydata)
713
- cl_filter.SetSourceSeedIds(source_ids)
714
- cl_filter.SetTargetSeedIds(target_ids)
715
- cl_filter.SetRadiusArrayName("Radius")
716
- cl_filter.SetCostFunction("1/R")
717
- cl_filter.SetFlipNormals(False)
718
- cl_filter.SetAppendEndPointsToCenterlines(0)
719
- cl_filter.SetSimplifyVoronoi(False) # Voronoi smoothing disabled
720
- cl_filter.SetCenterlineResampling(0)
721
- cl_filter.SetResamplingStepLength(curve_sampling_distance)
722
- cl_filter.Update()
723
-
724
- if not cl_filter.GetOutput():
725
- raise ValueError("Centerline extraction produced no output")
726
-
727
- centerline_polydata = vtk.vtkPolyData()
728
- centerline_polydata.DeepCopy(cl_filter.GetOutput())
729
-
730
- voronoi_polydata = None
731
- if cl_filter.GetVoronoiDiagram():
732
- voronoi_polydata = vtk.vtkPolyData()
733
- voronoi_polydata.DeepCopy(cl_filter.GetVoronoiDiagram())
734
-
735
- # Optional Laplacian smoothing to remove zigzag artifacts
736
- if smooth_iterations > 0:
737
- print(f" Smoothing centerline ({smooth_iterations} iters, relax={smooth_relaxation})...")
738
- centerline_polydata = smooth_centerline_polydata(
739
- centerline_polydata, iterations=smooth_iterations, relaxation_factor=smooth_relaxation,
740
- )
741
-
742
- return centerline_polydata, voronoi_polydata
743
-
744
-
745
- # ═══════════════════════════════════════════════════════════════════════════════
746
- # BRANCH CENTERLINE PROCESSING
747
- # After extracting the main aorta→iliacs centerline, each branch artery is
748
- # processed independently:
749
- # 1. The skeleton bifurcation point is projected onto the main centerline
750
- # to find where the branch contacts the aorta
751
- # 2. The surface mesh is clipped to a local sphere around the branch,
752
- # reducing input from ~100k to ~5k pts for much faster extraction
753
- # 3. A separate Voronoi centerline is extracted between the branch tip
754
- # and its contact point on the aorta
755
- # 4. All branch centerlines are merged with the main centerline
756
- # ═══════════════════════════════════════════════════════════════════════════════
757
-
758
- def find_branch_contact_point(branch_endpoint, bifurcation_point, main_centerline_polydata):
759
- """Find where a branch meets the main centerline using the skeleton bifurcation point."""
760
- if bifurcation_point is None:
761
- # Fallback: closest point on main centerline to the branch tip
762
- locator = vtk.vtkPointLocator()
763
- locator.SetDataSet(main_centerline_polydata)
764
- locator.BuildLocator()
765
- closest_id = locator.FindClosestPoint(branch_endpoint)
766
- return main_centerline_polydata.GetPoints().GetPoint(closest_id)
767
-
768
- # Project the skeleton bifurcation onto the main centerline
769
- locator = vtk.vtkPointLocator()
770
- locator.SetDataSet(main_centerline_polydata)
771
- locator.BuildLocator()
772
- closest_id = locator.FindClosestPoint(bifurcation_point)
773
- return main_centerline_polydata.GetPoints().GetPoint(closest_id)
774
-
775
-
776
- def clip_surface_around_points(surface_polydata, point1, point2, radius_multiplier=3.0):
777
- """Clip the surface mesh to a spherical region between two points.
778
-
779
- This dramatically speeds up branch centerline extraction by reducing the
780
- input mesh size from the full vessel tree to just the local branch region.
781
- The clipping sphere center is the midpoint; radius = distance × multiplier (min 20 mm).
782
- """
783
- center = [
784
- (point1[0] + point2[0]) / 2.0,
785
- (point1[1] + point2[1]) / 2.0,
786
- (point1[2] + point2[2]) / 2.0,
787
- ]
788
- distance = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(point1, point2))
789
- radius = max(distance * radius_multiplier, 20.0) # 20 mm minimum
790
-
791
- sphere = vtk.vtkSphere()
792
- sphere.SetCenter(center)
793
- sphere.SetRadius(radius)
794
-
795
  clipper = vtk.vtkClipPolyData()
796
- clipper.SetInputData(surface_polydata)
797
- clipper.SetClipFunction(sphere)
798
- clipper.InsideOutOn() # Keep points inside the sphere
799
  clipper.Update()
800
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801
  cleaner = vtk.vtkCleanPolyData()
802
- cleaner.SetInputData(clipper.GetOutput())
803
  cleaner.Update()
804
- return cleaner.GetOutput()
805
-
806
-
807
- def process_branch_centerline(branch_info, main_centerline_polydata, surface_polydata,
808
- curve_sampling_distance=1.0):
809
- """Extract centerline for a single branch from its tip to the main aorta."""
810
- branch_endpoint = branch_info['endpoint']
811
- bifurcation_point = branch_info['bifurcation']
812
-
813
- # Find the contact point on the main centerline
814
- contact_point = find_branch_contact_point(
815
- branch_endpoint, bifurcation_point, main_centerline_polydata,
816
- )
817
 
818
- # Branch tip = source, contact point = target
819
- branch_endpoints = [
820
- (branch_endpoint[0], branch_endpoint[1], branch_endpoint[2], True),
821
- (contact_point[0], contact_point[1], contact_point[2], False),
822
- ]
823
-
824
- print(f" Branch: ({branch_endpoint[0]:.1f}, {branch_endpoint[1]:.1f}, {branch_endpoint[2]:.1f})")
825
- print(f" -> Contact: ({contact_point[0]:.1f}, {contact_point[1]:.1f}, {contact_point[2]:.1f})")
826
-
827
- # Clip surface to a local region for faster processing
828
- original_pts = surface_polydata.GetNumberOfPoints()
829
- clipped_surface = clip_surface_around_points(
830
- surface_polydata, branch_endpoint, contact_point, radius_multiplier=1.25,
831
- )
832
- clipped_pts = clipped_surface.GetNumberOfPoints()
833
- reduction = 100.0 * (1.0 - clipped_pts / original_pts) if original_pts > 0 else 0
834
- print(f" Clipped: {original_pts} -> {clipped_pts} pts ({reduction:.0f}% reduction)")
835
-
836
- try:
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,
847
- curve_sampling_distance=1.0):
848
- """Process all branch centerlines, converting endpoints from LPS to RAS."""
849
- if not branch_info_list_lps:
850
- return []
851
-
852
- # Convert branch info from LPS to RAS
853
- branch_info_ras = []
854
- for info in branch_info_list_lps:
855
- x, y, z = info['endpoint']
856
- ep_ras = (-x, -y, z)
857
- bif_ras = None
858
- if info['bifurcation'] is not None:
859
- bx, by, bz = info['bifurcation']
860
- bif_ras = (-bx, -by, bz)
861
- branch_info_ras.append({'endpoint': ep_ras, 'bifurcation': bif_ras})
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):
879
- """Merge the main aorta→iliacs centerline with all branch centerlines into one polydata."""
880
- if not branch_centerlines:
881
- return main_centerline_polydata
882
-
883
- append_filter = vtk.vtkAppendPolyData()
884
- append_filter.AddInputData(main_centerline_polydata)
885
- for cl in branch_centerlines:
886
- append_filter.AddInputData(cl)
887
- append_filter.Update()
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")
894
- return cleaner.GetOutput()
895
-
896
-
897
- # ═══════════════════════════════════════════════════════════════════════════════
898
- # MAIN PIPELINE: COMPUTE CENTERLINES NETWORK
899
- # Orchestrates the full Slicer-style centerline extraction:
900
- # 1. Build closed surface from segmentation (Discrete Flying Edges)
901
- # 2. Skeletonize to detect vessel topology and endpoints
902
- # 3. Auto-detect aorta, iliacs, and branch endpoints
903
- # 4. Extract Voronoi-based main centerline (aorta → iliacs)
904
- # 5. Extract branch centerlines (clipped surface per branch)
905
- # 6. Merge all centerlines and convert back to LPS
906
- # ═══════════════════════════════════════════════════════════════════════════════
907
-
908
- def compute_centerlines_network(image, origin, direction, label_value=1,
909
- surface_smoothing=0.5, surface_decimation=0.0,
910
- keep_all_components=True, start_point=None,
911
- curve_sampling_distance=1.0):
912
- """Full pipeline: segmentation → surface → skeleton → centerlines → merge."""
913
-
914
- # Step 1: Build closed surface mesh from segmentation (Slicer-style Flying Edges)
915
- # Generate both LPS surface (for skeletonization) and RAS surface (for centerline extraction)
916
- surface_polydata_lps = create_closed_surface_polydata(
917
- image, origin, direction,
918
- label_value=label_value, smoothing=surface_smoothing, decimation=surface_decimation,
919
- keep_all_components=keep_all_components, to_ras=False,
920
- )
921
- surface_polydata = lps_polydata_to_ras(surface_polydata_lps)
922
-
923
- # Step 2: Skeletonize to get the network (topology + radius at each point)
924
- network = skeletonize(
925
- image=image, origin=origin, direction=direction,
926
- surface_polydata=surface_polydata_lps,
927
- label_value=label_value, smoothing=surface_smoothing, decimation=surface_decimation,
928
- keep_all_components=keep_all_components,
929
- target_number_of_points=5000, decimation_aggressiveness=4.0, subdivide=False,
930
- start_point=start_point, compute_geometry=True,
931
- )
932
-
933
- # Step 3: Auto-detect aorta root + iliac endpoints + branch endpoints
934
- print("\nDetecting aorta and iliac endpoints from network...")
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)
942
- print(f"Using aorta + {len(endpoints) - 1} iliac endpoint(s)")
943
- if branch_endpoints_lps:
944
- print(f"Detected {len(branch_endpoints_lps)} branch endpoint(s)")
945
-
946
- # Step 4: Extract main aorta→iliacs centerline via Voronoi method
947
- try:
948
- print("Extracting main centerline...")
949
- centerline_polydata, voronoi_polydata = extract_centerline_from_surface(
950
- surface_polydata, endpoints, curve_sampling_distance=curve_sampling_distance,
951
- )
952
- print(f"Main centerline: {centerline_polydata.GetNumberOfCells()} cells, "
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
- )
966
- except Exception as e:
967
- print(f"Branch extraction failed: {type(e).__name__}: {e}")
968
-
969
- # Step 6: Merge main + branch centerlines
970
- if branch_centerlines:
971
- try:
972
- merged = merge_main_and_branch_centerlines(centerline_polydata, branch_centerlines)
973
- except Exception as e:
974
- print(f"Merge failed: {e}")
975
- merged = centerline_polydata
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)
988
  def parse_segments(centerlines):
@@ -1365,11 +534,13 @@ if __name__ == '__main__':
1365
  sys.exit(1)
1366
 
1367
  try:
1368
- # Read the NRRD segmentation via SimpleITK (preserves full direction matrix)
1369
- image, origin, direction = load_nrrd_as_vtk_image(filepath)
 
 
1370
 
1371
- # Slicer-style surface processing -> Voronoi centerline extraction
1372
- centerlines = compute_centerlines_network(image, origin, direction)
1373
 
1374
  # Extract labelled segments and artery bifurcation data
1375
  data = extract_centerline_data(centerlines)
 
3
  import json
4
  import math
5
  from collections import defaultdict
6
+ from vmtk import vmtkscripts
 
 
 
 
7
  import vtk
8
 
9
  # The 4 abdominal artery labels, assigned top to bottom
 
67
  return normalize_vector((total[0] / valid, total[1] / valid, total[2] / valid))
68
 
69
 
70
+ # Transforms a 3D segmentation volume into a centerline polydata network
71
+ def compute_centerlines_network(image):
72
+ # Calculate iso_value which is the midpoint of intensity range, used to separate "inside vessel" parts from background
73
+ scalar_range = image.GetScalarRange()
74
+ iso_value = scalar_range[0] + 0.5 * (scalar_range[1] - scalar_range[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ # Converts voxel volume into a polygon surface mesh
77
+ marching_cubes = vtk.vtkMarchingCubes()
78
+ marching_cubes.SetInputData(image)
79
+ marching_cubes.ComputeNormalsOn()
80
+ marching_cubes.SetValue(0, iso_value)
81
+ marching_cubes.Update()
82
 
83
+ # Keeps only the largest connected surface (filters out noise islands)
84
+ connectivity = vtk.vtkPolyDataConnectivityFilter()
85
+ connectivity.SetInputData(marching_cubes.GetOutput())
86
+ connectivity.SetExtractionModeToLargestRegion()
87
+ connectivity.Update()
88
+
89
+ # Taubin smoothing to remove staircase atrifiacts without shrinking the mesh
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  smoother = vtk.vtkWindowedSincPolyDataFilter()
91
+ smoother.SetInputData(connectivity.GetOutput())
92
+ smoother.SetNumberOfIterations(30)
93
+ smoother.BoundarySmoothingOn()
94
+ smoother.FeatureEdgeSmoothingOff() # Don't treat staircase steps as sharp features
95
+ smoother.SetPassBand(0.2) # Low-pass cutoff, higher = more high-frequency (jagged) details kept
96
+ smoother.NonManifoldSmoothingOn() # Prevents crash on non-manifold geometry from marching cubes
97
+ smoother.NormalizeCoordinatesOn() # Avoids float precision issues with very large/small coordinates
98
  smoother.Update()
99
 
100
+ # Clips 1mm inset so vessel tips are open (VMTK needs open endpoints to trace flow)
101
+ bounds = smoother.GetOutput().GetBounds()
102
+ cut = 1.0
103
+ box = vtk.vtkBox()
104
+ box.SetBounds(
105
+ bounds[0] + cut, bounds[1] - cut,
106
+ bounds[2] + cut, bounds[3] - cut,
107
+ bounds[4] + cut, bounds[5] - cut,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  clipper = vtk.vtkClipPolyData()
110
+ clipper.SetInputData(smoother.GetOutput())
111
+ clipper.SetClipFunction(box)
112
+ clipper.InsideOutOn() # Keep what's inside the box (the vessel)
113
  clipper.Update()
114
 
115
+ # Triangulate (VMTK requires pure triangle mesh) + subdivide for accuracy so that voronoi diagram works correctly
116
+ tri_filter = vtk.vtkTriangleFilter()
117
+ tri_filter.SetInputData(clipper.GetOutput())
118
+ tri_filter.Update()
119
+
120
+ subdivider = vmtkscripts.vmtkSurfaceSubdivision()
121
+ subdivider.Surface = tri_filter.GetOutput()
122
+ subdivider.Method = 'butterfly' # Interpolating subdivision -- preserves curvature
123
+ subdivider.NumberOfSubdivisions = 1
124
+ subdivider.Execute()
125
+
126
+ # VMTK network extraction which traces centerline via maximal inscribed sphere paths
127
+ # The Voronoi diagram defines the medial axis; the centerline is the lowest-cost path from inlet to outlet where cost is inversely proportional to sphere radius
128
+ network = vmtkscripts.vmtkNetworkExtraction()
129
+ network.Surface = subdivider.Surface
130
+ network.AdvancementRatio = 1.02
131
+ network.Execute()
132
+
133
+ # Resample to uniform 0.5mm spacing, then smooth sharp turns
134
+ resampler = vmtkscripts.vmtkCenterlineResampling()
135
+ resampler.Centerlines = network.Network
136
+ resampler.Length = 0.5
137
+ resampler.Execute()
138
+
139
+ cl_smoother = vmtkscripts.vmtkCenterlineSmoothing()
140
+ cl_smoother.Centerlines = resampler.Centerlines
141
+ cl_smoother.NumberOfSmoothingIterations = 300
142
+ cl_smoother.SmoothingFactor = 0.1 # Moves each point 10% toward mean of its neighbours
143
+ cl_smoother.Execute()
144
+
145
+ # Merge overlapping points so bifurcation topology is correct
146
  cleaner = vtk.vtkCleanPolyData()
147
+ cleaner.SetInputData(cl_smoother.Centerlines)
148
  cleaner.Update()
149
+ cleaned = cleaner.GetOutput()
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
+ if not cleaned or cleaned.GetNumberOfCells() == 0:
152
+ raise Exception('Centerline Network Extraction returned 0 segments')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
+ return cleaned
155
 
156
  # Converts VTK polydata into a python list that contains line segments information (unique segment id, points in that segment, radius of each point, label)
157
  def parse_segments(centerlines):
 
534
  sys.exit(1)
535
 
536
  try:
537
+ # Read the NRRD segmentation image via VMTK
538
+ reader = vmtkscripts.vmtkImageReader()
539
+ reader.InputFileName = filepath
540
+ reader.Execute()
541
 
542
+ # VTK surface processing -> centerline polydata network
543
+ centerlines = compute_centerlines_network(reader.Image)
544
 
545
  # Extract labelled segments and artery bifurcation data
546
  data = extract_centerline_data(centerlines)
server.py CHANGED
@@ -1,63 +1,66 @@
1
- # Flask API server that wraps the VMTK centerline extraction pipeline
2
- # Single endpoint: POST /extract, accepts file upload (NRRD segmentation), returns JSON with centerline data
3
- import os
4
- import tempfile
5
- from flask import Flask, request, jsonify
6
- from flask_cors import CORS
7
-
8
- # Import the centerline extraction logic from the existing module
9
- from centerline_extraction import compute_centerlines_network, extract_centerline_data, load_nrrd_as_vtk_image
10
-
11
- app = Flask(__name__)
12
- CORS(app) # Allow cross-origin requests from the Next.js frontend
13
-
14
- # Maximum file upload size (200 MB)
15
- app.config["MAX_CONTENT_LENGTH"] = 200 * 1024 * 1024
16
-
17
- # Simple health check so the deployment platform knows the server is alive
18
- @app.route("/health", methods=["GET"])
19
- def health():
20
- return jsonify({"status": "ok"})
21
-
22
- # Runs the full VMTK centerline extraction pipeline on NRRD segmentation and returns the result as JSON
23
- @app.route("/extract", methods=["POST"])
24
- def extract():
25
- if "file" not in request.files:
26
- return jsonify({"status": "error", "error": "No file provided"}), 400
27
-
28
- uploaded = request.files["file"]
29
- file_name = uploaded.filename.lower()
30
- if not file_name.endswith(".nrrd"):
31
- return jsonify({"status": "error", "error": "Invalid File Type. Allowed: .nrrd"}), 400
32
-
33
- # Save to a temp file so VMTK can read it from disk
34
- tmp = tempfile.NamedTemporaryFile(suffix=".nrrd", delete=False)
35
- try:
36
- uploaded.save(tmp.name)
37
- tmp.close()
38
-
39
- # Read the NRRD segmentation via SimpleITK (preserves full direction matrix)
40
- image, origin, direction = load_nrrd_as_vtk_image(tmp.name)
41
-
42
- # Slicer-style surface processing -> Voronoi centerline extraction
43
- centerlines = compute_centerlines_network(image, origin, direction)
44
-
45
- # Extract labelled segments and artery bifurcation data
46
- data = extract_centerline_data(centerlines)
47
-
48
- return jsonify({"status": "success", "data": data})
49
-
50
- except Exception as e:
51
- return jsonify({"status": "error", "error": str(e)}), 500
52
-
53
- finally:
54
- # Always clean up the temp file
55
- try:
56
- os.unlink(tmp.name)
57
- except OSError:
58
- pass
59
-
60
-
61
- if __name__ == "__main__":
62
- port = int(os.environ.get("PORT", 5050))
63
- app.run(host="0.0.0.0", port=port)
 
 
 
 
1
+ # Flask API server that wraps the VMTK centerline extraction pipeline
2
+ # Single endpoint: POST /extract, accepts file upload (NRRD segmentation), returns JSON with centerline data
3
+ import os
4
+ import tempfile
5
+ from flask import Flask, request, jsonify
6
+ from flask_cors import CORS
7
+ from vmtk import vmtkscripts
8
+
9
+ # Import the centerline extraction logic from the existing module
10
+ from centerline_extraction import compute_centerlines_network, extract_centerline_data
11
+
12
+ app = Flask(__name__)
13
+ CORS(app) # Allow cross-origin requests from the Next.js frontend
14
+
15
+ # Maximum file upload size (200 MB)
16
+ app.config["MAX_CONTENT_LENGTH"] = 200 * 1024 * 1024
17
+
18
+ # Simple health check so the deployment platform knows the server is alive
19
+ @app.route("/health", methods=["GET"])
20
+ def health():
21
+ return jsonify({"status": "ok"})
22
+
23
+ # Runs the full VMTK centerline extraction pipeline on NRRD segmentation and returns the result as JSON
24
+ @app.route("/extract", methods=["POST"])
25
+ def extract():
26
+ if "file" not in request.files:
27
+ return jsonify({"status": "error", "error": "No file provided"}), 400
28
+
29
+ uploaded = request.files["file"]
30
+ file_name = uploaded.filename.lower()
31
+ if not file_name.endswith(".nrrd"):
32
+ return jsonify({"status": "error", "error": "Invalid File Type. Allowed: .nrrd"}), 400
33
+
34
+ # Save to a temp file so VMTK can read it from disk
35
+ tmp = tempfile.NamedTemporaryFile(suffix=".nrrd", delete=False)
36
+ try:
37
+ uploaded.save(tmp.name)
38
+ tmp.close()
39
+
40
+ # Read the NRRD segmentation image via VMTK
41
+ reader = vmtkscripts.vmtkImageReader()
42
+ reader.InputFileName = tmp.name
43
+ reader.Execute()
44
+
45
+ # VTK surface processing -> centerline polydata network
46
+ centerlines = compute_centerlines_network(reader.Image)
47
+
48
+ # Extract labelled segments and artery bifurcation data
49
+ data = extract_centerline_data(centerlines)
50
+
51
+ return jsonify({"status": "success", "data": data})
52
+
53
+ except Exception as e:
54
+ return jsonify({"status": "error", "error": str(e)}), 500
55
+
56
+ finally:
57
+ # Always clean up the temp file
58
+ try:
59
+ os.unlink(tmp.name)
60
+ except OSError:
61
+ pass
62
+
63
+
64
+ if __name__ == "__main__":
65
+ port = int(os.environ.get("PORT", 5050))
66
+ app.run(host="0.0.0.0", port=port)