用 numpy 数组中的最近邻填充 nan

tbr*_*ere 5 python numpy nan

我得到了这个带有缺失值的二维 numpy 数组。是否有一种简单(且相当快)的方法用最接近的(最好是欧几里德距离,但曼哈顿也可以)非纳米值填充纳米值?我在 numpy 或 scipy\xe2\x80\xa6 中找不到这样的函数

\n

orl*_*rlp 13

使用scipy.interpolate.NearestNDInterpolator

例如:

from scipy.interpolate import NearestNDInterpolator
data = ... # shape (w, h)
mask = np.where(~np.isnan(data))
interp = NearestNDInterpolator(np.transpose(mask), data[mask])
filled_data = interp(*np.indices(data.shape))
Run Code Online (Sandbox Code Playgroud)

显示它的实际效果(这里用黑色作为遮罩,image_defect来自这里):

data = image_defect
mask = np.where(~(data == 0))
interp = NearestNDInterpolator(np.transpose(mask), data[mask])
image_result = interp(*np.indices(data.shape))
Run Code Online (Sandbox Code Playgroud)

然后,使用 scipy 中的绘图代码: 在此输入图像描述