TDHarshithReddy commited on
Commit
f1664f8
·
1 Parent(s): ba6cfa8

Implement 3D mesh visualization with trimesh and marching_cubes

Browse files
Files changed (2) hide show
  1. app.py +51 -10
  2. requirements.txt +1 -0
app.py CHANGED
@@ -26,6 +26,8 @@ from monai.transforms import (
26
  )
27
  from monai.inferers import sliding_window_inference
28
  from labels import LABEL_NAMES, get_color_map, get_label_name, get_organ_categories
 
 
29
 
30
  # Constants
31
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -116,6 +118,9 @@ def run_inference(image_path: str, progress=gr.Progress()):
116
  postprocess = get_postprocessing_transforms()
117
 
118
  # Load and preprocess
 
 
 
119
  image = preprocess(image_path)
120
  image = image.unsqueeze(0).to(DEVICE) # Add batch dimension
121
 
@@ -133,17 +138,41 @@ def run_inference(image_path: str, progress=gr.Progress()):
133
 
134
  progress(0.8, desc="Post-processing...")
135
 
136
- # Post-process
137
- outputs = postprocess(outputs)
138
- segmentation = outputs.squeeze().cpu().numpy().astype(np.uint8)
139
-
140
- # Load original image for visualization
141
- original_nib = nib.load(image_path)
142
- original_data = original_nib.get_fdata()
143
 
144
  progress(1.0, desc="Complete!")
145
 
146
- return original_data, segmentation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
 
149
  def create_slice_visualization(ct_data, seg_data, axis, slice_idx, alpha=0.5, show_overlay=True):
@@ -231,15 +260,19 @@ def process_upload(file_path, progress=gr.Progress()):
231
  fig = create_slice_visualization(ct_data, seg_data, "Axial", mid_axial)
232
  structures = get_detected_structures(seg_data)
233
 
 
 
 
234
  return (
235
  fig,
236
  structures,
 
237
  gr.update(maximum=ct_data.shape[2] - 1, value=mid_axial),
238
  gr.update(maximum=ct_data.shape[1] - 1, value=mid_coronal),
239
  gr.update(maximum=ct_data.shape[0] - 1, value=mid_sagittal),
240
  )
241
  except Exception as e:
242
- return None, f"Error processing file: {str(e)}", gr.update(), gr.update(), gr.update()
243
 
244
 
245
  def update_visualization(axis, slice_idx, alpha, show_overlay):
@@ -342,6 +375,14 @@ with gr.Blocks(
342
  lines=10,
343
  max_lines=20
344
  )
 
 
 
 
 
 
 
 
345
 
346
  # Model info section
347
  with gr.Accordion("ℹ️ Model Information", open=False):
@@ -372,7 +413,7 @@ with gr.Blocks(
372
  process_btn.click(
373
  fn=process_upload,
374
  inputs=[file_input],
375
- outputs=[output_image, structures_output, axial_slider, coronal_slider, sagittal_slider]
376
  )
377
 
378
  # Update visualization when controls change
 
26
  )
27
  from monai.inferers import sliding_window_inference
28
  from labels import LABEL_NAMES, get_color_map, get_label_name, get_organ_categories
29
+ import trimesh
30
+ from skimage import measure
31
 
32
  # Constants
33
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
118
  postprocess = get_postprocessing_transforms()
119
 
120
  # Load and preprocess
121
+ image_nib = nib.load(image_path)
122
+ original_data = image_nib.get_fdata() # Keep original data for visualization
123
+
124
  image = preprocess(image_path)
125
  image = image.unsqueeze(0).to(DEVICE) # Add batch dimension
126
 
 
138
 
139
  progress(0.8, desc="Post-processing...")
140
 
141
+ # Post-processing
142
+ seg_data = postprocess(outputs).squeeze().cpu().numpy().astype(np.uint8)
 
 
 
 
 
143
 
144
  progress(1.0, desc="Complete!")
145
 
146
+ return original_data, seg_data
147
+
148
+
149
+ def generate_3d_mesh(seg_data, step_size=2):
150
+ """Generate a 3D mesh from segmentation data using Marching Cubes"""
151
+ if seg_data is None or np.max(seg_data) == 0:
152
+ return None
153
+
154
+ try:
155
+ # Create a boolean mask of all structures (excluding background 0)
156
+ # Using a step_size > 1 reduces resolution but speeds up generation significantly
157
+ # This is crucial for CPU performance on Hugging Face Spaces
158
+ mask = seg_data > 0
159
+
160
+ # Marching cubes to get vertices and faces
161
+ # level=0.5 because boolean mask is 0 or 1
162
+ verts, faces, normals, values = measure.marching_cubes(mask, level=0.5, step_size=step_size)
163
+
164
+ # Create trimesh object
165
+ mesh = trimesh.Trimesh(vertices=verts, faces=faces, vertex_normals=normals)
166
+
167
+ # Export to a temporary GLB file (efficient binary format)
168
+ temp_file = tempfile.NamedTemporaryFile(suffix=".glb", delete=False)
169
+ mesh.export(temp_file.name)
170
+ temp_file.close()
171
+
172
+ return temp_file.name
173
+ except Exception as e:
174
+ print(f"Error generating 3D mesh: {e}")
175
+ return None
176
 
177
 
178
  def create_slice_visualization(ct_data, seg_data, axis, slice_idx, alpha=0.5, show_overlay=True):
 
260
  fig = create_slice_visualization(ct_data, seg_data, "Axial", mid_axial)
261
  structures = get_detected_structures(seg_data)
262
 
263
+ # Generate 3D mesh (this might take a few seconds)
264
+ mesh_path = generate_3d_mesh(seg_data)
265
+
266
  return (
267
  fig,
268
  structures,
269
+ mesh_path,
270
  gr.update(maximum=ct_data.shape[2] - 1, value=mid_axial),
271
  gr.update(maximum=ct_data.shape[1] - 1, value=mid_coronal),
272
  gr.update(maximum=ct_data.shape[0] - 1, value=mid_sagittal),
273
  )
274
  except Exception as e:
275
+ return None, f"Error processing file: {str(e)}", None, gr.update(), gr.update(), gr.update()
276
 
277
 
278
  def update_visualization(axis, slice_idx, alpha, show_overlay):
 
375
  lines=10,
376
  max_lines=20
377
  )
378
+
379
+ # 3D Model Output
380
+ gr.Markdown("### 🧊 3D View")
381
+ model_3d_output = gr.Model3D(
382
+ label="3D Segmentation Mesh",
383
+ clear_color=[0.0, 0.0, 0.0, 0.0],
384
+ camera_position=(90, 90, 3)
385
+ )
386
 
387
  # Model info section
388
  with gr.Accordion("ℹ️ Model Information", open=False):
 
413
  process_btn.click(
414
  fn=process_upload,
415
  inputs=[file_input],
416
+ outputs=[output_image, structures_output, model_3d_output, axial_slider, coronal_slider, sagittal_slider]
417
  )
418
 
419
  # Update visualization when controls change
requirements.txt CHANGED
@@ -7,3 +7,4 @@ nibabel>=5.0.0
7
  numpy
8
  matplotlib
9
  scikit-image
 
 
7
  numpy
8
  matplotlib
9
  scikit-image
10
+ trimesh