Created
July 17, 2025 15:26
-
-
Save cwood1967/532f7045fd60161016a3ee0f2b8833ee to your computer and use it in GitHub Desktop.
Rotate image to napari camera view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Set napari to 3-D mode and rotate it to the desired view | |
The output size of the rotated image need to be specified | |
to it will fit into new image. If the image in not spatially | |
isotropic it should probably be downsampled (likely in y and x). | |
I use skimage.transform.downscale_local_mean. | |
Variables | |
========= | |
dstack : array | |
The image array displayed in napari to be rotated | |
""" | |
import numpy as np | |
import scipy.ndimage as ndi | |
from scipy.spatial.transform import Rotation as R | |
camera_initial = np.array((-1, 0, 0)) ## napari initial camera vector (always this) | |
up_initial = np.array((0, -1, 0)) ## initial up vector | |
camera_rot = np.array(viewer.camera.view_direction) ## the camera direction after rotation (into screen) | |
up_rot = viewer.camera.calculate_nd_up_direction(3, (0, 1, 2)) # the up direction after rotation (screen up) | |
v_initial = np.array([camera_initial, up_initial]) # list of inital vectors | |
v_rotated = np.array([camera_rot, up_rot]) # list of rotated vectors | |
rot, rssd = R.align_vectors(v_initial, v_rotated, return_sensitivity=False) | |
rot_matrix = rot.as_matrix() | |
## get the center of the image array | |
center =(np.array(dstack[4].shape) - 1)/2 | |
"""calculate the offset, this is the point the | |
This is the point the image will be rotated around. | |
""" | |
offset = center - rm.T @ np.array((250, 250, 250)) | |
rxmaxlist = list() | |
### loop over the channels, assumes channel_axis=0 | |
for c in dstack: | |
_rx = ndi.affine_transform(c, rm.T, order=2, | |
output_shape=(500, 500, 500), | |
offset=offset) | |
_rxmax = _rx.max(axis=0) | |
rxmaxlist.append(_rxmax) | |
rxmax = np.stack(rxmaxlist) ## the output image | |
""" | |
After the rotation is finished, add it to napari, then push the home button. | |
The home view of the new image should look like the rotated view | |
of the original image. | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment