M.T*_*M.T 8 python interpolation numpy
我有一个二维数组(如果你愿意,还有矩阵),其中一些缺失值表示为
NaN.缺失值通常沿一个轴的条带,例如:
1 2 3 NaN 5
2 3 4 Nan 6
3 4 Nan Nan 7
4 5 Nan Nan 8
5 6 7 8 9
Run Code Online (Sandbox Code Playgroud)
在哪里我想NaN用一些有意义的数字代替's.
我查看了delaunay三角测量,但发现文档很少.
我尝试使用astropy's convolve,因为它支持使用2d数组,而且非常简单.这个问题是卷积不是插值,它将所有值移向平均值(可以通过使用窄内核来减轻).
这个问题应该是这篇文章的自然二维扩展.有没有办法NaN在2d阵列中插入/丢失值?
G M*_*G M 12
是的,您可以使用scipy.interpolate.griddata和屏蔽数组,您可以选择您喜欢使用参数的插值类型method通常'cubic'做得很好:
import numpy as np
from scipy import interpolate
#Let's create some random data
array = np.random.random_integers(0,10,(10,10)).astype(float)
#values grater then 7 goes to np.nan
array[array>7] = np.nan
Run Code Online (Sandbox Code Playgroud)
看起来像这样使用plt.imshow(array,interpolation='nearest')
:
x = np.arange(0, array.shape[1])
y = np.arange(0, array.shape[0])
#mask invalid values
array = np.ma.masked_invalid(array)
xx, yy = np.meshgrid(x, y)
#get only the valid values
x1 = xx[~array.mask]
y1 = yy[~array.mask]
newarr = array[~array.mask]
GD1 = interpolate.griddata((x1, y1), newarr.ravel(),
(xx, yy),
method='cubic')
Run Code Online (Sandbox Code Playgroud)
这是最终结果:
看看如果纳米值在边缘并被纳米值包围,则无法插值并保留nan.您可以使用fill_value参数更改它.
这取决于您的数据类型,您必须执行一些测试.例如,您可以屏蔽一些好的数据尝试不同类型的插值,例如立方体,线性等等,带有屏蔽值的数组,并计算插值值和之前屏蔽的原始值之间的差异,看看哪个方法返回你的细微差别.
你可以使用这样的东西:
reference = array[3:6,3:6].copy()
array[3:6,3:6] = np.nan
method = ['linear', 'nearest', 'cubic']
for i in method:
GD1 = interpolate.griddata((x1, y1), newarr.ravel(),
(xx, yy),
method=i)
meandifference = np.mean(np.abs(reference - GD1[3:6,3:6]))
print ' %s interpolation difference: %s' %(i,meandifference )
Run Code Online (Sandbox Code Playgroud)
这给出了这样的东西:
linear interpolation difference: 4.88888888889
nearest interpolation difference: 4.11111111111
cubic interpolation difference: 5.99400137377
Run Code Online (Sandbox Code Playgroud)
当然这是随机数,所以结果可能变化很大是正常的.因此,最好的办法是测试数据集的"有目的掩盖"部分,看看会发生什么.
from scipy import interpolate
import numpy as np
def interpolate_missing_pixels(
image: np.ndarray,
mask: np.ndarray,
method: str = 'nearest',
fill_value: int = 0
):
"""
:param image: a 2D image
:param mask: a 2D boolean image, True indicates missing values
:param method: interpolation method, one of
'nearest', 'linear', 'cubic'.
:param fill_value: which value to use for filling up data outside the
convex hull of known pixel values.
Default is 0, Has no effect for 'nearest'.
:return: the image with missing values interpolated
"""
from scipy import interpolate
h, w = image.shape[:2]
xx, yy = np.meshgrid(np.arange(w), np.arange(h))
known_x = xx[~mask]
known_y = yy[~mask]
known_v = image[~mask]
missing_x = xx[mask]
missing_y = yy[mask]
interp_values = interpolate.griddata(
(known_x, known_y), known_v, (missing_x, missing_y),
method=method, fill_value=fill_value
)
interp_image = image.copy()
interp_image[missing_y, missing_x] = interp_values
return interp_image
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8170 次 |
| 最近记录: |