CoolFace
Apppublic

IFMedTech/NIfTI

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py85 linesDownload Raw Back to root
1import gradio as gr2import nibabel as nib3import numpy as np4import matplotlib.pyplot as plt5import matplotlib6matplotlib.use('Agg')7 8def visualize_nifti(file, volume_idx=0, slice_idx=0):9    if file is None:10        return None11    12    try:13        # Load the NIfTI file14        img = nib.load(file.name)15        data = img.get_fdata()16        shape = data.shape17        18        # Determine if 3D or 4D19        if len(shape) == 3:20            # 3D data21            max_slice = shape[2] - 122            slice_idx = min(slice_idx, max_slice)23            24            # Extract the axial slice25            slice_data = data[:, :, slice_idx]26            27            # Create the plot28            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 fig35            36        elif len(shape) == 4:37            # 4D data38            max_volume = shape[3] - 139            max_slice = shape[2] - 140            volume_idx = min(volume_idx, max_volume)41            slice_idx = min(slice_idx, max_slice)42            43            # Extract the axial slice from the specified volume44            slice_data = data[:, :, slice_idx, volume_idx]45            46            # Create the plot47            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 fig54        else:55            return None56            57    except Exception as e:58        return None59 60# Create Gradio interface with Blocks for dynamic controls61with 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    visualize_btn.click(79        fn=visualize_nifti,80        inputs=[file_input, volume_slider, slice_slider],81        outputs=[output_plot]82    )83 84if __name__ == "__main__":85    demo.launch()