Spaces:
Sleeping
Sleeping
File size: 2,676 Bytes
a8e2b25 5ec8b95 a8e2b25 5ec8b95 a8e2b25 8de9095 a8e2b25 5ec8b95 a8e2b25 5ec8b95 8de9095 5ec8b95 8de9095 5ec8b95 8de9095 5ec8b95 a8e2b25 8de9095 a8e2b25 5ec8b95 8de9095 5ec8b95 a8e2b25 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
import gradio as gr
import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')
def visualize_nifti(file, volume_idx=0, slice_idx=0):
if file is None:
return None
try:
# Load the NIfTI file
img = nib.load(file.name)
data = img.get_fdata()
shape = data.shape
# Determine if 3D or 4D
if len(shape) == 3:
# 3D data
max_slice = shape[2] - 1
slice_idx = min(slice_idx, max_slice)
# Extract the axial slice
slice_data = data[:, :, slice_idx]
# Create the plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.imshow(slice_data.T, cmap='gray', origin='lower')
ax.axis('off')
plt.title(f'Axial Slice: {slice_idx}/{max_slice}')
plt.tight_layout()
return fig
elif len(shape) == 4:
# 4D data
max_volume = shape[3] - 1
max_slice = shape[2] - 1
volume_idx = min(volume_idx, max_volume)
slice_idx = min(slice_idx, max_slice)
# Extract the axial slice from the specified volume
slice_data = data[:, :, slice_idx, volume_idx]
# Create the plot
fig, ax = plt.subplots(figsize=(8, 8))
ax.imshow(slice_data.T, cmap='gray', origin='lower')
ax.axis('off')
plt.title(f'Volume: {volume_idx}/{max_volume}, Slice: {slice_idx}/{max_slice}')
plt.tight_layout()
return fig
else:
return None
except Exception as e:
return None
# Create Gradio interface with Blocks for dynamic controls
with gr.Blocks() as demo:
gr.Markdown("# NIfTI File Visualizer")
gr.Markdown("Upload a NIfTI (.nii or .nii.gz) file to visualize axial slices.")
with gr.Row():
file_input = gr.File(label="Upload NIfTI file (.nii or .nii.gz)")
with gr.Row():
volume_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Volume/Frame (for 4D)")
slice_slider = gr.Slider(minimum=0, maximum=100, step=1, value=0, label="Axial Slice (Z-plane)")
with gr.Row():
visualize_btn = gr.Button("Visualize")
with gr.Row():
output_plot = gr.Plot(label="Slice Visualization")
visualize_btn.click(
fn=visualize_nifti,
inputs=[file_input, volume_slider, slice_slider],
outputs=[output_plot]
)
if __name__ == "__main__":
demo.launch() |