import nibabel as nib import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact, IntSlider, Layout defload_and_visualize_nifti(filename: str): # Load the NIfTI file nifti_img = nib.load(filename) data = nifti_img.get_fdata() # Remove the singleton dimension if it exists data = np.squeeze(data) # Check data dimensions if data.ndim == 3: # Function to display a slice of the 3D data defdisplay_slice(slice_index): plt.figure(figsize=(8, 8)) plt.imshow(data[:, :, slice_index], cmap='gray') plt.title(f'Slice {slice_index}') plt.axis('off') plt.show() # Create an interactive widget interact(display_slice, slice_index=IntSlider( min=0, max=data.shape[2]-1, step=1, value=data.shape[2]//2, layout=Layout(width='80%') )) elif data.ndim == 2: # If the data is already 2D, just display it plt.figure(figsize=(8, 8)) plt.imshow(data, cmap='gray') plt.title('2D Image') plt.axis('off') plt.show() else: print("Unsupported data dimension") # Example usage load_and_visualize_nifti(img_path)