Search code examples
pythonnumpyrotationscipy.ndimage

Using Scipy.ndimage to Rotate an Array within Np.Nan Values


I have an elevation array from a .tif LiDAR surface. Example array below.

from scipy.ndimage import rotate
import numpy as np
test_surface_nan =  [[np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
                     [np.nan, np.nan, np.nan,   1,    np.nan, np.nan, np.nan],
                     [np.nan, np.nan,   1,      2,      1,    np.nan, np.nan],
                     [np.nan,   1,      2,      3,      2,      1,    np.nan],
                     [np.nan, np.nan,   1,      2,      1,    np.nan, np.nan],
                     [np.nan, np.nan, np.nan,   1,    np.nan, np.nan, np.nan],
                     [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]]

I am attempting to rotate the values within the test_surface_nan such that the values begins in row[1]using the following code.

test_surface_array_nan = np.array(test_surface_nan)
test_surface_array_nan_rotated = rotate(test_surface_array_nan,45,reshape=True)

I receive the below array. Why did the elements larger than 0 get turned into np.nan values, the np.nan values get turned into 0?

enter image description here

this was definitely not what I was expecting when looking at the scipy.ndimage.rotate website

my expectation was something along the lines of the below example

maybe_test_surface_nan =  [  [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
                             [np.nan,    1,   np.nan,   1,    np.nan,    1,   np.nan],
                             [np.nan, np.nan,   2,    np.nan,   2,    np.nan, np.nan],
                             [np.nan,    1,   np.nan,   3,    np.nan,    1,   np.nan],
                             [np.nan, np.nan,   2,    np.nan,   2,    np.nan, np.nan],
                             [np.nan,    1, np.nan,     1,    np.nan,    1,   np.nan],
                             [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan]]

Solution

  • The issue is in order= parameter that controls the interpolation. Try to set this parameter to 0:

    test_surface_array_nan_rotated = rotate(
        test_surface_array_nan, 45, reshape=True, order=0
    )
    
    print(test_surface_array_nan_rotated)
    

    Prints:

    [[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
     [ 0.  0.  0.  0. nan nan  0.  0.  0.  0.]
     [ 0.  0.  0. nan nan nan nan  0.  0.  0.]
     [ 0.  0. nan  1.  1.  1.  1. nan  0.  0.]
     [ 0. nan nan  1.  2.  2.  1. nan nan  0.]
     [ 0. nan nan  1.  2.  2.  1. nan nan  0.]
     [ 0.  0. nan  1.  1.  1.  1. nan  0.  0.]
     [ 0.  0.  0. nan nan nan nan  0.  0.  0.]
     [ 0.  0.  0.  0. nan nan  0.  0.  0.  0.]
     [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]