Since I joined Columbia, I have been using Google Colab with my university account. The notebooks run on Google’s servers, you get access to GPUs for free, and things are very fast. The one thing I missed was an interactive viewer for my image stacks. Viewers like napari need a display, and a Colab notebook runs on a remote machine, so they don’t work there. So I wrote a small one myself. It is very simple, but it kind of works, and it has been useful for me.
The idea is to load a TIFF stack, show one slice at a time with matplotlib, and use a slider from ipywidgets to move through the slices.
import tifffile
import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython.display import display
from skimage import data
# Example stack from scikit-image: nuclei channel, 60 slices of 256 x 256
stack = data.cells3d()[:, 1, :, :]
# Or load your own TIFF stack instead
# stack = tifffile.imread('your-stack.tif')
print(f"TIFF stack shape: {stack.shape}")
def interactive_image_viewer(image_stack):
"""
Displays an interactive viewer for a 3D image stack using a slider.
Args:
image_stack (numpy.ndarray): The 3D image stack to visualize.
"""
if image_stack.ndim != 3:
print("Error: Input image_stack must be 3-dimensional.")
return
def show_slice(slice_idx):
plt.figure(figsize=(8, 8))
plt.imshow(image_stack[slice_idx], cmap='gray')
plt.title(f'Slice {slice_idx + 1}/{image_stack.shape[0]}')
plt.axis('off')
plt.show()
# Create a slider widget
slice_slider = widgets.IntSlider(
value=0,
min=0,
max=image_stack.shape[0] - 1,
step=1,
description='Slice:',
continuous_update=True
)
# Display the interactive widget
display(widgets.interactive(show_slice, slice_idx=slice_slider))
interactive_image_viewer(stack)
To try it out, just run the cell. It downloads cells3d, a confocal stack of cells that comes with scikit-image, and shows the nuclei channel. To use your own data, upload your TIFF file to the notebook, uncomment the tifffile line, and change the file name. Either way, you get a slider under the image, and moving it redraws the slice.
The function expects a 3D stack in the order (Z, Y, X). If your stack has more dimensions, for example several channels, pick one first, like stack[:, 0, :, :] for the first channel of a (Z, C, Y, X) stack. And with large images, redrawing can lag a bit while you drag; setting continuous_update=False makes it update only when you let go of the slider.
It is nothing fancy compared to a proper viewer, but for quickly checking a segmentation or scrolling through a stack without leaving the notebook, it does the job.
References:
- Google Colab and its FAQ, including the free access to GPUs
- ipywidgets: Using Interact, for the slider
- matplotlib imshow, for showing each slice
- tifffile, for reading TIFF stacks
- scikit-image cells3d, the example stack
- napari, the full viewer I use outside Colab