基本上,是否可以让scipy.ndimage.map_coordinates
返回多值结构,而不仅仅是标量?我希望能够插入一次以在一个点上检索5个值,而不是必须插值5次。
这是我在MWE上尝试演示这个问题。我将从标量的3D插值开始。我暂时不会介绍积分,因为那不是重点。
import numpy as np
from scipy import ndimage
coords = np.array([[1.,1.,1.]])
a = np.arange(3*3*3).reshape(3,3,3)
ndimage.map_coordinates(a,coords.T) # array([13.])
现在,假设我希望a
拥有一对值,而不仅仅是一对。我的直觉是
a = np.arange(3*3*3*2).reshape(3,3,3,2)
a[1,1,1] # array([26.,27.])
ndimage.map_coordinates(a[:,:,:],coords.T) # I'd like array([26.,27.])
取代所需的输出,我得到以下内容:
RuntimeError Traceback (most recent call last)
(...)/<ipython-input-84-77334fb7469f> in <module>()
----> 1 ndimage.map_coordinates(a[:,:,:],np.array([[1.,1.,1.]]).T)
/usr/lib/python2.7/dist-packages/scipy/ndimage/interpolation.pyc in map_coordinates(input, coordinates, output, order, mode, cval, prefilter)
287 raise RuntimeError('input and output rank must be > 0')
288 if coordinates.shape[0] != input.ndim:
--> 289 raise RuntimeError('invalid shape for coordinate array')
290 mode = _extend_mode_to_code(mode)
291 if prefilter and order > 1:
RuntimeError: invalid shape for coordinate array
我无法找到任何结构(a
,coords
等)形状的排列,这些结构给出了我正在寻找的答案。此外,如果有更好的方法来执行此操作而不是使用map_coordinates
,请继续。我认为scipy.interpolate.interp1d
可能是要走的路,但我找不到任何文件或暗示它可能会做什么......
答案 0 :(得分:2)
我认为那是不可能的。
但张量积插值并不困难:
import numpy as np
from scipy.interpolate import interp1d
def interpn(*args, **kw):
"""Interpolation on N-D.
ai = interpn(x, y, z, ..., a, xi, yi, zi, ...)
where the arrays x, y, z, ... define a rectangular grid
and a.shape == (len(x), len(y), len(z), ...)
"""
method = kw.pop('method', 'cubic')
if kw:
raise ValueError("Unknown arguments: " % kw.keys())
nd = (len(args)-1)//2
if len(args) != 2*nd+1:
raise ValueError("Wrong number of arguments")
q = args[:nd]
qi = args[nd+1:]
a = args[nd]
for j in range(nd):
a = interp1d(q[j], a, axis=j, kind=method)(qi[j])
return a
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 6)
y = np.linspace(0, 1, 7)
k = np.array([0, 1])
z = np.cos(2*x[:,None,None] + k[None,None,:]) * np.sin(3*y[None,:,None])
xi = np.linspace(0, 1, 60)
yi = np.linspace(0, 1, 70)
zi = interpn(x, y, z, xi, yi, method='linear')
plt.subplot(221)
plt.imshow(z[:,:,0].T, interpolation='nearest')
plt.subplot(222)
plt.imshow(zi[:,:,0].T, interpolation='nearest')
plt.subplot(223)
plt.imshow(z[:,:,1].T, interpolation='nearest')
plt.subplot(224)
plt.imshow(zi[:,:,1].T, interpolation='nearest')
plt.show()