Setting napari viewer zoom/pan position from script

If I want the user to focus on a particular part of an image, is there a viewer method to set the viewer coordinates and zoom? I played around a bit with viewer.dims methods but couldn’t seem to do this. Thanks so much!

1 Like

Hi @naten7k,

The napari canvas is actually an instance of a Vispy SceneCanvas… and those sorts of properties (zoom, center point) all live on the vispy camera viewing the scene. Currently, those objects are buried pretty deep in napari, but hopefully this should get you started:

>>> viewer = napari.Viewer()

>>> viewer.window.qt_viewer.view.camera
# in 2D mode, it's a PanZoomCamera: 
<PanZoomCamera name=PanZoomCamera at 0x13cedc580>
# in 3D mode the camera would be an ArcballCamera:
<ArcballCamera name=ArcballCamera at 0x141a4c4f0>

# you can get_state and set_state on the camera:
>>> state = viewer.window.qt_viewer.view.camera.get_state()
>>> state
{'rect': <Rect (-25.6, -25.6) (563.2, 563.2)>}

# now go ahead and move the canvas around,
# to return to the saved position:
>>> viewer.window.qt_viewer.view.camera.set_state(state)

Browse the vispy docs linked above for more camera methods. And for some excellent examples of controlling, saving, and recovering the camera viewpoint, I highly recommend browsing the source of @guiwitz’s naparimovie repo

2 Likes

We have a WIP PR here https://github.com/napari/napari/pull/854 to add a camera model, this will make it much easier to do what you want to do. It’s waiting on some more improvements to our physical/ world coordinates systems, but then we’ll want to get it in. Thanks for bearing with us.