n-dimensional array viewer in Python with fast, interactive multi-dimensional image visualization
—
Napari utilities provide essential helper functions and classes for colormaps, progress tracking, system information, notifications, and other supporting functionality that enhances the user experience and developer workflow.
Classes and functions for managing colormaps used in data visualization, supporting both continuous and discrete color mapping schemes.
class Colormap:
"""
Colormap class for continuous data visualization.
Supports custom color definitions and interpolation.
"""
def __init__(
self,
colors,
*,
name: str = None,
interpolation: str = 'linear'
):
"""
Create a colormap.
Parameters:
- colors: Color definitions (list of colors or array)
- name: Colormap name
- interpolation: Interpolation method ('linear', 'zero')
"""
def map(self, values):
"""
Apply colormap to data values.
Parameters:
- values: Array of values to map
Returns:
Array of RGBA colors
"""
class DirectLabelColormap:
"""
Colormap for direct label-to-color mapping.
Maps integer labels directly to specific colors.
"""
def __init__(self, color_dict: dict):
"""
Create direct label colormap.
Parameters:
- color_dict: Dictionary mapping labels to colors
"""
class CyclicLabelColormap:
"""
Colormap that cycles through colors for label data.
Automatically assigns colors to labels in sequence.
"""
def __init__(
self,
colors,
*,
seed: float = 0.5,
shuffle: bool = True
):
"""
Create cyclic label colormap.
Parameters:
- colors: List of colors to cycle through
- seed: Random seed for color generation
- shuffle: Whether to shuffle color order
"""Functions and context managers for displaying progress information during long-running operations.
def progress(
iterable=None,
*,
desc: str = None,
total: int = None,
nest_under=None,
**kwargs
):
"""
Create a progress indicator for iterables or manual updates.
Parameters:
- iterable: Iterable to wrap with progress tracking
- desc: Description text for progress bar
- total: Total number of items (if not using iterable)
- nest_under: Parent progress bar for nested progress
- kwargs: Additional progress bar parameters
Returns:
Progress context manager or wrapped iterable
"""
def progrange(
stop,
start: int = 0,
step: int = 1,
*,
desc: str = None,
**kwargs
):
"""
Create a progress-wrapped range iterator.
Parameters:
- stop: End value for range
- start: Start value for range
- step: Step size for range
- desc: Progress description
- kwargs: Additional progress parameters
Returns:
Progress-wrapped range iterator
"""
def cancelable_progress(
iterable=None,
*,
desc: str = None,
total: int = None,
**kwargs
):
"""
Create a cancelable progress indicator.
Allows users to cancel long-running operations.
Parameters:
- iterable: Iterable to wrap
- desc: Progress description
- total: Total items count
- kwargs: Additional parameters
Returns:
Cancelable progress context manager
"""Functions for retrieving and displaying system and environment information useful for debugging and support.
def sys_info():
"""
Get comprehensive system information.
Returns:
str: Formatted system information including:
- Python and napari versions
- Operating system details
- Qt backend information
- Graphics and display details
- Installed packages and dependencies
"""
def citation_text():
"""
Get citation information for napari.
Returns:
str: Formatted citation text for academic use
"""Utilities for working with napari in Jupyter notebooks and other interactive environments.
class NotebookScreenshot:
"""
Class for managing screenshot display in Jupyter notebooks.
Handles image formatting and display optimization.
"""
def __init__(self, viewer, *, canvas_only: bool = True):
"""
Create notebook screenshot handler.
Parameters:
- viewer: Napari viewer instance
- canvas_only: Whether to capture only canvas or full window
"""
def _repr_png_(self):
"""PNG representation for notebook display."""
def _repr_jpeg_(self):
"""JPEG representation for notebook display."""
def nbscreenshot(
viewer,
*,
canvas_only: bool = True,
**kwargs
):
"""
Take a screenshot optimized for notebook display.
Parameters:
- viewer: Napari viewer instance
- canvas_only: Capture canvas only or full window
- kwargs: Additional screenshot parameters
Returns:
NotebookScreenshot: Screenshot object for notebook display
"""Utilities for managing memory usage and performance optimization, particularly for large dataset handling.
def resize_dask_cache(nbytes: str = None):
"""
Resize the dask cache for improved memory management.
Parameters:
- nbytes: Cache size specification (e.g., '2GB', '512MB')
"""System for managing user notifications, warnings, and error messages throughout the napari interface.
notification_manager
"""
Global notification manager instance for dispatching and handling notifications.
Provides centralized management of info, warning, error, and debug messages.
"""Constants and utilities related to threading and concurrent processing.
NUMPY_VERSION_IS_THREADSAFE: bool
"""
Boolean indicating whether the current NumPy version is thread-safe.
Used to determine if threading optimizations can be safely enabled.
"""import napari
import numpy as np
# Create custom colormap
from napari.utils import Colormap
# Define custom colors (red to blue)
custom_colors = ['red', 'yellow', 'blue']
custom_cmap = Colormap(custom_colors, name='custom')
# Create data and viewer
data = np.random.random((100, 100))
viewer = napari.Viewer()
viewer.add_image(data, colormap=custom_cmap, name='Custom Colors')
# Use direct label colormap
labels = np.zeros((100, 100), dtype=int)
labels[25:75, 25:75] = 1
labels[10:40, 60:90] = 2
from napari.utils import DirectLabelColormap
label_colors = {0: 'black', 1: 'red', 2: 'blue'}
label_cmap = DirectLabelColormap(label_colors)
viewer.add_labels(labels, colormap=label_cmap, name='Direct Labels')import napari
import numpy as np
import time
# Progress with iterable
data_list = []
for i in napari.utils.progrange(10, desc="Generating data"):
# Simulate work
time.sleep(0.1)
data_list.append(np.random.random((50, 50)))
# Manual progress updates
with napari.utils.progress(total=100, desc="Processing") as pbar:
for i in range(100):
# Simulate work
time.sleep(0.01)
pbar.update(1)
# Cancelable progress
def long_computation():
results = []
for i in napari.utils.cancelable_progress(
range(1000),
desc="Long computation"
):
# Simulate expensive operation
time.sleep(0.01)
results.append(i * 2)
# Check if cancelled
if i > 100: # User can cancel via GUI
break
return results
# results = long_computation()import napari
# Get system information
info = napari.utils.sys_info()
print(info)
# Get citation information
citation = napari.utils.citation_text()
print(citation)# In Jupyter notebook
import napari
import numpy as np
# Create viewer and data
data = np.random.random((100, 100))
viewer = napari.Viewer()
viewer.add_image(data, name='Sample')
# Take screenshot for notebook display
screenshot = napari.utils.nbscreenshot(viewer, canvas_only=True)
# Display in notebook (automatically calls _repr_png_)
screenshotimport napari
# Access the global notification manager
manager = napari.notification_manager
# The notification manager handles system-wide messages
# and is used internally by napari for error reporting
# and user feedbackimport napari
import numpy as np
# Configure dask cache for large datasets
napari.utils.resize_dask_cache('2GB')
# Create large dataset
large_data = np.random.random((1000, 1000, 100))
# Create viewer
viewer = napari.Viewer()
viewer.add_image(large_data, name='Large Dataset')
# Check if NumPy threading is safe
if napari.utils.NUMPY_VERSION_IS_THREADSAFE:
print("NumPy threading optimizations available")
else:
print("Using single-threaded NumPy operations")import napari
import numpy as np
import time
# Setup memory management
napari.utils.resize_dask_cache('1GB')
# Create viewer
viewer = napari.Viewer(title='Analysis Pipeline')
# Generate data with progress tracking
datasets = []
for i in napari.utils.progrange(5, desc="Loading datasets"):
# Simulate loading data
time.sleep(0.2)
data = np.random.random((100, 100)) + i * 0.1
datasets.append(data)
# Process data with cancelable progress
processed_data = []
with napari.utils.cancelable_progress(
datasets,
desc="Processing datasets"
) as pdata:
for i, data in enumerate(pdata):
# Add to viewer
viewer.add_image(data, name=f'Dataset {i}')
# Simulate processing
time.sleep(0.1)
processed = data * 2
processed_data.append(processed)
# Create custom colormap for final result
from napari.utils import Colormap
result_cmap = Colormap(['black', 'red', 'yellow', 'white'], name='heat')
# Add final processed result
final_result = np.mean(processed_data, axis=0)
viewer.add_image(final_result, colormap=result_cmap, name='Final Result')
# Take screenshot for documentation
screenshot = napari.utils.nbscreenshot(viewer)
# Print system info for debugging
print("System Information:")
print(napari.utils.sys_info())
napari.run()Install with Tessl CLI
npx tessl i tessl/pypi-napari