gpt4 book ai didi

python - 如何插入旋转网格?

转载 作者:行者123 更新时间:2023-12-01 08:58:00 25 4
gpt4 key购买 nike

我有

[[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]]

我想将其插值到左边缘有一个角的旋转网格中。类似于:

[[2, ~2, 2],
[~4, ~4, ~4],
[6, ~6, 6]]

(我使用~表示近似值。)

(当然,我的实际数据更复杂。场景是我想将DEM数据按像素映射到旋转图像上。)

这是设置:

import numpy
from scipy import interpolate as interp

grid = numpy.ndarray((5, 5))
for I in range(grid.shape[0]):
for j in range(grid.shape[1]):
grid[I, j] = I + j

grid = ndimage.interpolation.shift(
ndimage.interpolation.rotate(grid, -45, reshape=False),
-1)

source_x, source_y = numpy.meshgrid(
numpy.arange(0, 5), numpy.arange(0, 5))
target_x, target_y = numpy.meshgrid(
numpy.arange(0, 2), numpy.arange(0, 2))

print(interp.griddata(
numpy.array([source_x.ravel(), source_y.ravel()]).T,
grid.ravel(),
target_x, target_y))

这给了我:

[[2.4467   2.6868 2.4467]
[4. 4. 4. ]
[5.5553 5.3132 5.5553]]

这是有希望的。但是,旋转和移位值是硬编码的,我至少应该能够准确获取左上角。

我确实知道我想要插值的网格角的索引。也就是说,我有

upper_left = 2, 0
upper_right = 0, 2
lower_right = 4, 2
lower_left = 2, 4

最佳答案

这可能不够内置,不符合您的口味,但这里有一种方法可以更直接地使用您的起点(网格角),并应用样条插值(默认为三次)。

import numpy as np
from scipy.interpolate import RectBivariateSpline

# input data
data = np.array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])

upper_left = 2, 0
upper_right = 0, 2
lower_right = 2, 4 # note that I swapped this
lower_left = 4, 2 # and this
n_steps = 3, 3


# build interpolator
m, n = data.shape
x, y = np.arange(m), np.arange(n)

interpolator = RectBivariateSpline(x, y, data)

# build grid
ul,ur,ll,lr = map(np.array, (upper_left,upper_right,lower_left,lower_right))
assert np.allclose(ul + lr, ur + ll) # make sure edges are parallel

x, y = ul[:, None, None] \
+ np.outer(ll-ul, np.linspace(0.0, 1.0, n_steps[0]))[:, :, None] \
+ np.outer(ur-ul, np.linspace(0.0, 1.0, n_steps[1]))[:, None, :]

# intepolate on grid
print(interpolator.ev(x, y))

打印:

[[2. 2. 2.]
[4. 4. 4.]
[6. 6. 6.]]

关于python - 如何插入旋转网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52672317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com