网格插值


作者Lou Xiao创建时间2023-06-02 16:56:28更新时间2023-06-02 16:56:28

如何使用Scipy进行网格(grid)插值?

2d网格的插值代码

1.双击鼠标左键复制此行;2.单击复制所有代码。
                                
                                    
1 import numpy as np
2 from scipy.interpolate import RegularGridInterpolator
3
4
5 def geometry_interpolate2d(
6 old_arr: np.ndarray, # assure shape [?, latitude, longitude]
7 old_latitudes: np.ndarray,
8 old_longitudes: np.ndarray,
9 new_latitudes: np.ndarray,
10 new_longitudes: np.ndarray,
11 ):
12 assert old_arr.ndim == 3
13 channels = np.arange(old_arr.shape[0])
14 # method='linear': 线性插值
15 fn = RegularGridInterpolator((channels, old_latitudes, old_longitudes,), old_arr, method='linear')
16 mesh_channels, mesh_lats, mesh_lngs = np.meshgrid(channels, new_latitudes, new_longitudes, indexing='ij')
17 new_arr = fn((mesh_channels, mesh_lats, mesh_lngs))
18 return new_arr
19
20
21 def main():
22 # latitude
23 lats = np.linspace(90, 0, 5)
24 # longitude
25 lngs = np.linspace(0, 90, 5)
26 # mesh grid, shape [channels, latitudes, longitudes]
27 grid = np.arange(3 * 5 * 5).reshape((3, 5, 5))
28 new_lats = np.linspace(90, 0, 9)
29 new_lngs = np.linspace(0, 90, 9)
30 new_grid = geometry_interpolate2d(grid, lats, lngs, new_lats, new_lngs)
31 for i in range(3):
32 print("Old:\n", grid[i])
33 print("New:\n", new_grid[i])
34 print("=" * 40)
35
36
37 if __name__ == '__main__':
38 main()
文章目录