简体   繁体   English

Python中的2D最近邻插值

[英]2D Nearest Neighbor Interpolation in Python

Suppose that we have the following look up table 假设我们有以下查找表

        | 1.23    2.63    4.74    6.43    5.64
 -------|--------------------------------------
 -------|--------------------------------------
 2.56   |  0       0      1        0       1
 4.79   |  0       1      1        1       0
 6.21   |  1       0      0        0       0

This table contains a labeling matrix (having only 0 and 1 s), x values and y values. 该表包含标记矩阵(仅具有01 s), x值和y值。 How one can have nearest-neighbor interpolation for this look up table? 如何为这个查找表进行最近邻插值

Example: 例:

Input: (5.1, 4.9)
Output: 1

Input: (3.54, 6.9)
Output: 0

Look up table 查找表

If you have the complete table you don't need interpolation, you just need to look up the index of the nearest (x, y) value and use it on the table 如果你有完整的表,你不需要插值,你只需要查找最近的(x,y)值的索引并在表上使用它

In [1]: import numpy
   ...: x = numpy.array([1.23, 2.63, 4.74, 6.43, 5.64])
   ...: y = numpy.array([2.56, 4.79, 6.21])
   ...: data = numpy.array([[0, 0, 1, 0, 1],
   ...:                     [0, 1, 1, 1, 0],
   ...:                     [1, 0, 0, 0, 0]])
   ...: 
   ...: def lookupNearest(x0, y0):
   ...:     xi = numpy.abs(x-x0).argmin()
   ...:     yi = numpy.abs(y-y0).argmin()
   ...:     return data[yi,xi]

In [2]: lookupNearest(5.1, 4.9)
Out[2]: 1

In [3]: lookupNearest(3.54, 6.9)
Out[3]: 0

Nearest-neighbor interpolation 最近邻插值

scipy.interpolate.NearestNDInterpolator will be really useful if your data is composed by scattered points 如果您的数据由分散点组成,则scipy.interpolate.NearestNDInterpolator非常有用

For example, for data like: 例如,对于以下数据:

在此输入图像描述 with red = 1, blue =0 红色= 1,蓝色= 0

In [4]: points = numpy.array([[1.1, 2.5], 
   ...:                       [1.5, 5.2], 
   ...:                       [3.1, 3.0], 
   ...:                       [2.0, 6.0], 
   ...:                       [2.8, 4.7]])
   ...: values = numpy.array([0, 1, 1, 0, 0])

In [5]: from scipy.interpolate import NearestNDInterpolator
   ...: myInterpolator = NearestNDInterpolator(points, values)

In [6]: myInterpolator(1.7,4.5)
Out[6]: 1

In [7]: myInterpolator(2.5,4.0)
Out[7]: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM