当前位置: 首页 > 面试题库 >

Filling gaps in a numpy array

范浩宕
2023-03-14
问题内容

我只想用最简单的术语来插值一个3D数据集。
线性插值,最近邻,所有这些就足够了(这就是
开始一些算法,所以不需要精确的估计)。
在新的scipy版本中,griddata之类的东西会很有用,但目前我
只有scipy 0.8。所以我有一个“cube”(data[:,:,:],(NixNjxNk))数组
相同大小的标志数组(flags[:,:,:,]TrueFalse)。我
想把我的数据插值为数据元素的相应位置
flag的元素为False,例如使用数据中最近的有效数据点,或
一些“近距”点的线性组合。
数据集中至少在两个维度上可能存在较大的差距。除
使用kdtrees或类似的方法编写一个完整的最近邻算法
找不到通用的N维最近邻插值器。


问题答案:

您可以设置晶体生长样式算法,交替移动视图
沿每个轴,仅替换标记为“False”但具有
`真正的邻居。这会产生类似“最近邻”的结果(但不是
欧几里德距离或曼哈顿距离——我想它可能是最近的邻居
正在计算像素,计算所有具有公共角的连接像素)这
使用NumPy应该相当有效,因为它只在axis和
收敛迭代,而不是数据的小切片。
粗、快、稳。我想这就是你想要的:

import numpy as np
# -- setup --
shape = (10,10,10)
dim = len(shape)
data = np.random.random(shape)
flag = np.zeros(shape, dtype=bool)
t_ct = int(data.size/5)
flag.flat[np.random.randint(0, flag.size, t_ct)] = True
# True flags the data
# -- end setup --

slcs = [slice(None)]*dim

while np.any(~flag): # as long as there are any False's in flag
    for i in range(dim): # do each axis
        # make slices to shift view one element along the axis
        slcs1 = slcs[:]
        slcs2 = slcs[:]
        slcs1[i] = slice(0, -1)
        slcs2[i] = slice(1, None)

        # replace from the right
        repmask = np.logical_and(~flag[slcs1], flag[slcs2])
        data[slcs1][repmask] = data[slcs2][repmask]
        flag[slcs1][repmask] = True

        # replace from the left
        repmask = np.logical_and(~flag[slcs2], flag[slcs1])
        data[slcs2][repmask] = data[slcs1][repmask]
        flag[slcs2][repmask] = True

为了更好的测量,这里有一个由数据播种的区域的可视化(2D)最初标记为“True”。



 类似资料:

相关阅读

相关文章

相关问答