pythonscipyimage-rotationrotational-matricesscipy.ndimage

Rotation of 3d array and point cloud not matching


I have the following problem: I have a 3d numpy array representing a stack of images. I also have a point cloud (n,3) of some relevant locations in the 3d array, which I have plotted in there. I want to rotate both by an angle around the x-axis. I do the following:

#for point cloud

rotation_matrix = scipy.spatial.transform.Rotation.from_euler('x', x_rot, degrees=True)
rotated_stack_points = rotation_matrix.apply(stack_points)

#for 3d stack

rotated_marked_xy = scipy.ndimage.interpolation.rotate(gfp_stack, angle=-x_rot, axes=(1, 2), reshape=True)

Then I plot the rotated point cloud in the rotated 3d array. The problem is that there is always a xy offset between the points plotted pre rotation and after rotation and can't figure out why. This offset changes with the rotation angle, it's not fixed. Any ideas why this happens?


Solution

  • If you rotate by the same angle with different centers of rotation one output will be translated compared to the other.

    The rotation matrix obtained by from euler will perform a rotation centered at the origin.

    import scipy.spatial.transform
    rotation_matrix = scipy.spatial.transform.Rotation.from_euler('x', 30, degrees=True)
    rotation_matrix.apply([0,0,0])
    

    The ndimage.rotate method rotates around the center of the image, and the reshape=True will extend the borders so that the corners lie in the new box.

    import scipy.ndimage
    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.ones((3, 100, 100))
    xr = scipy.ndimage.rotate(x, 30, axes=(1,2))
    plt.imshow(xr[0])
    xr.shape
    
    (3, 137, 137)
    

    enter image description here

    You can change the center of rotation by applying translate(-c) rotate translate(+c) sequence