IFMedTechdemo commited on
Commit
5ec8b95
·
verified ·
1 Parent(s): c123594

Add NIfTI slice visualization with matplotlib

Browse files
Files changed (1) hide show
  1. app.py +73 -26
app.py CHANGED
@@ -1,41 +1,88 @@
1
  import gradio as gr
2
  import nibabel as nib
3
  import numpy as np
 
 
 
4
 
5
- def process_nifti(file):
6
  if file is None:
7
- return "No file uploaded."
8
 
9
  try:
10
  # Load the NIfTI file
11
  img = nib.load(file.name)
 
 
12
 
13
- # Get basic information
14
- shape = img.shape
15
- data_type = img.get_data_dtype()
16
- header = img.header
17
-
18
- # Create a summary
19
- info = f"""File successfully loaded!
20
-
21
- Shape: {shape}
22
- Data type: {data_type}
23
- Dimensions: {len(shape)}D
24
- Voxel dimensions: {header.get_zooms()}
25
- """
26
-
27
- return info
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  except Exception as e:
29
- return f"Error loading file: {str(e)}"
30
 
31
- # Create Gradio interface
32
- demo = gr.Interface(
33
- fn=process_nifti,
34
- inputs=gr.File(label="Upload NIfTI file (.nii or .nii.gz)"),
35
- outputs=gr.Textbox(label="File Information", lines=10),
36
- title="NIfTI File Viewer",
37
- description="Upload a NIfTI (.nii or .nii.gz) file to view basic information about it."
38
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  if __name__ == "__main__":
41
  demo.launch()
 
1
  import gradio as gr
2
  import nibabel as nib
3
  import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib
6
+ matplotlib.use('Agg')
7
 
8
+ def visualize_nifti(file, volume_idx=0, slice_idx=0):
9
  if file is None:
10
+ return None, "No file uploaded."
11
 
12
  try:
13
  # Load the NIfTI file
14
  img = nib.load(file.name)
15
+ data = img.get_fdata()
16
+ shape = data.shape
17
 
18
+ # Determine if 3D or 4D
19
+ if len(shape) == 3:
20
+ # 3D data
21
+ max_slice = shape[2] - 1
22
+ slice_idx = min(slice_idx, max_slice)
23
+
24
+ # Extract the axial slice
25
+ slice_data = data[:, :, slice_idx]
26
+
27
+ # Create the plot
28
+ fig, ax = plt.subplots(figsize=(8, 8))
29
+ ax.imshow(slice_data.T, cmap='gray', origin='lower')
30
+ ax.axis('off')
31
+ plt.title(f'Axial Slice: {slice_idx}/{max_slice}')
32
+ plt.tight_layout()
33
+
34
+ return fig, f'3D Volume - Displaying Slice {slice_idx}/{max_slice}'
35
+
36
+ elif len(shape) == 4:
37
+ # 4D data
38
+ max_volume = shape[3] - 1
39
+ max_slice = shape[2] - 1
40
+ volume_idx = min(volume_idx, max_volume)
41
+ slice_idx = min(slice_idx, max_slice)
42
+
43
+ # Extract the axial slice from the specified volume
44
+ slice_data = data[:, :, slice_idx, volume_idx]
45
+
46
+ # Create the plot
47
+ fig, ax = plt.subplots(figsize=(8, 8))
48
+ ax.imshow(slice_data.T, cmap='gray', origin='lower')
49
+ ax.axis('off')
50
+ plt.title(f'Volume: {volume_idx}/{max_volume}, Slice: {slice_idx}/{max_slice}')
51
+ plt.tight_layout()
52
+
53
+ return fig, f'4D Volume - Displaying Volume {volume_idx}/{max_volume}, Slice {slice_idx}/{max_slice}'
54
+ else:
55
+ return None, f"Unsupported dimensions: {len(shape)}D"
56
+
57
  except Exception as e:
58
+ return None, f"Error loading file: {str(e)}"
59
 
60
+ # Create Gradio interface with Blocks for dynamic controls
61
+ with gr.Blocks() as demo:
62
+ gr.Markdown("# NIfTI File Visualizer")
63
+ gr.Markdown("Upload a NIfTI (.nii or .nii.gz) file to visualize axial slices.")
64
+
65
+ with gr.Row():
66
+ file_input = gr.File(label="Upload NIfTI file (.nii or .nii.gz)")
67
+
68
+ with gr.Row():
69
+ volume_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Volume/Frame (for 4D)")
70
+ slice_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Axial Slice (Z-plane)")
71
+
72
+ with gr.Row():
73
+ visualize_btn = gr.Button("Visualize")
74
+
75
+ with gr.Row():
76
+ output_plot = gr.Plot(label="Slice Visualization")
77
+
78
+ with gr.Row():
79
+ output_text = gr.Textbox(label="Info", lines=2)
80
+
81
+ visualize_btn.click(
82
+ fn=visualize_nifti,
83
+ inputs=[file_input, volume_slider, slice_slider],
84
+ outputs=[output_plot, output_text]
85
+ )
86
 
87
  if __name__ == "__main__":
88
  demo.launch()