n-dimensional array viewer in Python with fast, interactive multi-dimensional image visualization
—
The core viewer functionality provides the main interface for creating and controlling napari viewers, managing the visualization window, and coordinating the display of multi-dimensional scientific data.
The main viewer class that serves as the primary interface for napari applications. Manages the display window, layer stack, and user interactions.
class Viewer:
def __init__(
self,
*,
title: str = 'napari',
ndisplay: int = 2,
order: tuple = (),
axis_labels: tuple = (),
show: bool = True,
**kwargs
):
"""
Create a new napari viewer.
Parameters:
- title: Window title
- ndisplay: Number of displayed dimensions (2 or 3)
- order: Order of dimension display
- axis_labels: Labels for each dimension
- show: Whether to show the viewer window immediately
"""
def add_image(self, data, **kwargs):
"""
Add an image layer to the viewer.
Parameters:
- data: array-like, image data
- kwargs: Layer-specific parameters
Returns:
Image layer object
"""
def add_labels(self, data, **kwargs):
"""
Add a labels layer for segmentation/annotation.
Parameters:
- data: array-like, integer label data
- kwargs: Layer-specific parameters
Returns:
Labels layer object
"""
def add_points(self, data, **kwargs):
"""
Add a points layer for coordinate data.
Parameters:
- data: array-like, point coordinates
- kwargs: Layer-specific parameters
Returns:
Points layer object
"""
def add_shapes(self, data, **kwargs):
"""
Add a shapes layer for geometric annotations.
Parameters:
- data: list of shape data
- kwargs: Layer-specific parameters
Returns:
Shapes layer object
"""
def add_surface(self, data, **kwargs):
"""
Add a surface layer for 3D mesh data.
Parameters:
- data: tuple of (vertices, faces, values)
- kwargs: Layer-specific parameters
Returns:
Surface layer object
"""
def add_tracks(self, data, **kwargs):
"""
Add a tracks layer for time-series point data.
Parameters:
- data: array-like, track data with time information
- kwargs: Layer-specific parameters
Returns:
Tracks layer object
"""
def add_vectors(self, data, **kwargs):
"""
Add a vectors layer for directional data.
Parameters:
- data: array-like, vector data (positions and directions)
- kwargs: Layer-specific parameters
Returns:
Vectors layer object
"""
def open(self, path, **kwargs):
"""
Open file(s) and add as layer(s) using plugin system.
Parameters:
- path: str or list of str, file path(s) to open
- kwargs: Additional parameters for layer creation
Returns:
List of created layers
"""
@property
def layers(self):
"""Access the LayerList containing all viewer layers."""
@property
def dims(self):
"""Access the Dims object controlling dimensional navigation."""
@property
def camera(self):
"""Access the Camera object controlling view parameters."""
@property
def window(self):
"""Access to the main application window."""
def screenshot(self, path=None, *, size=None, scale=None, canvas_only=True, flash=False):
"""
Take screenshot of current view.
Parameters:
- path: Optional path to save screenshot
- size: Output size tuple (width, height)
- scale: Scale factor for high-resolution output
- canvas_only: If True, only capture the canvas area
- flash: If True, briefly flash the widget
Returns:
numpy.ndarray: Screenshot as RGBA array
"""
def export_figure(self, path=None, *, scale_factor=1, flash=False):
"""
Export high-resolution figure of the full data extent.
Parameters:
- path: Optional path to save figure
- scale_factor: Scale factor for high-resolution output
- flash: If True, briefly flash the widget
Returns:
numpy.ndarray: Figure as RGBA array
"""
def reset_view(self, *, margin=0.05, reset_camera_angle=True):
"""
Reset camera and fit layers to canvas.
Parameters:
- margin: Margin around data as fraction of canvas
- reset_camera_angle: Whether to reset 3D camera angles
"""
def update_console(self, variables):
"""
Update console namespace with variables.
Parameters:
- variables: Dictionary of variables to add to console
"""
def open_sample(self, plugin, sample, reader_plugin=None, **kwargs):
"""
Open sample data from plugins.
Parameters:
- plugin: Plugin name providing sample data
- sample: Sample data identifier
- reader_plugin: Optional specific reader plugin
- kwargs: Additional parameters for layer creation
Returns:
List of created layers
"""
@classmethod
def close_all(cls):
"""
Close all viewer instances.
Useful for cleanup in scripts and testing.
Returns:
int: Number of closed viewers
"""Global functions for managing viewer instances and the napari application lifecycle.
def current_viewer():
"""
Get the currently active viewer instance.
Returns:
Viewer or None: The active viewer, or None if no viewer exists
"""
def run(
*,
force: bool = False,
gui_exceptions: bool = False,
max_loop_level: int = 1,
_func_name: str = 'run'
):
"""
Start the Qt event loop for napari GUI applications.
Parameters:
- force: Force running even if event loop exists
- gui_exceptions: Show GUI dialog for unhandled exceptions
- max_loop_level: Maximum nesting level for event loop
"""Convenience functions that create a viewer and add a specific type of layer in one call.
def view_image(*args, **kwargs):
"""
Create a viewer and add an image layer.
Returns:
Viewer: The newly-created viewer with image layer
"""
def view_labels(*args, **kwargs):
"""
Create a viewer and add a labels layer.
Returns:
Viewer: The newly-created viewer with labels layer
"""
def view_points(*args, **kwargs):
"""
Create a viewer and add a points layer.
Returns:
Viewer: The newly-created viewer with points layer
"""
def view_shapes(*args, **kwargs):
"""
Create a viewer and add a shapes layer.
Returns:
Viewer: The newly-created viewer with shapes layer
"""
def view_surface(*args, **kwargs):
"""
Create a viewer and add a surface layer.
Returns:
Viewer: The newly-created viewer with surface layer
"""
def view_tracks(*args, **kwargs):
"""
Create a viewer and add a tracks layer.
Returns:
Viewer: The newly-created viewer with tracks layer
"""
def view_vectors(*args, **kwargs):
"""
Create a viewer and add a vectors layer.
Returns:
Viewer: The newly-created viewer with vectors layer
"""
def view_path(path, **kwargs):
"""
Create a viewer and open file(s) from path.
Parameters:
- path: str or list of str, file path(s) to open
- kwargs: Additional parameters for layer creation
Returns:
Viewer: The newly-created viewer with opened data
"""
def imshow(*args, **kwargs):
"""
Create a viewer and display an image (matplotlib-style interface).
Returns:
Viewer: The newly-created viewer with image layer
"""import napari
import numpy as np
# Create empty viewer
viewer = napari.Viewer(title="My Analysis", ndisplay=2)
# Add data
image_data = np.random.random((100, 100))
viewer.add_image(image_data, name="Sample Image")
# Start the GUI
napari.run()import napari
import numpy as np
# Create 4D time-lapse data (time, z, y, x)
data_4d = np.random.random((10, 20, 100, 100))
# Create viewer with appropriate axis labels
viewer = napari.Viewer(
title="Time-lapse Z-stack",
axis_labels=['time', 'z', 'y', 'x']
)
viewer.add_image(data_4d, name="Time-lapse")
napari.run()import napari
import numpy as np
# Quick image viewing
image = np.random.random((100, 100))
viewer = napari.view_image(image, title="Quick View")
# Equivalent to matplotlib's imshow
viewer = napari.imshow(image, title="Matplotlib Style")
napari.run()Install with Tessl CLI
npx tessl i tessl/pypi-napari