python:插值:找到一个最小包含一个点的矩形

2024-03-28 16:32:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在实现一个双线性插值,如How to perform bilinear interpolation in Python

我有一个点的排序列表,这些点是我规则网格的顶点。你知道吗

[[x1,y1,z1],[x2,y2,z2],[x3,y3,z3],[x4,y4,z4],[x5,y5,z5],...]

我想在点(x,y)上线性插值。我编写了以下代码

def f(x, y, points):
    for i in range(len(points)-1, -1, -1):
        if (x>points[i][0])and(y>points[i][1]):
            break
    try:
        pp = [points[i], points[i+1]]
    except IndexError:
        pp = [points[i], points[i-1]]

    for j in range(len(points)):
        if (x<points[j][0])and(y<points[j][1]):
            break
    pp.append(points[j-1])
    pp.append(points[j])

    (x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp
    return (q11 * (x2 - x) * (y2 - y) +
            q21 * (x - x1) * (y2 - y) +
            q12 * (x2 - x) * (y - y1) +
            q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))

但是这个代码在边界上不起作用。我认为这是插值中的常见问题,所以我想知道如何从规则网格中选择(x,y)周围点的最小矩形。你知道吗


Tags: and代码in网格forlenif规则
2条回答

网格是规则的,所以不需要遍历所有点来确定单元索引。只需将坐标除以单元格大小,然后将结果取整为较小的整数。1D示例:如果第一个点的坐标为1,单元大小为2,则点6位于int (6-1)/2 = 2-nd间隔

限制结果索引以确保它在网格限制内-因此网格外的点将使用边界单元

 i = int((x - points[i][0]) / xsize)  #not sure what is the best way in Python
 if (i < 0):
     i = 0
 if (i >=  XCount):
     i = XCount - 1
 // same for j and y-coordinate

根据评论中的建议,我编写了以下代码:

def f(x, y, points):
    points = sorted(points)

    xunique = np.unique([point[0] for point in points])
    yunique = np.unique([point[1] for point in points])
    xmax    = np.max(xunique)
    ymax    = np.max(yunique)
    deltax  = xunique[1] - xunique[0]
    deltay  = yunique[1] - yunique[0]
    x0      = xunique[0]
    y0      = yunique[0]
    ni      = len(xunique)
    nj      = len(yunique)

    i1 = int(np.floor((x-x0)/deltax))
    if i1 == ni:
        i1 = i1 - 1
    i2 = int(np.ceil((x-x0)/deltax))
    if i2 == ni:
        i2 = i2 - 1
    j1 = int(np.floor((y-y0)/deltay))
    if j1 == nj:
        j1 = j1 - 1
    j2 = int(np.ceil((y-y0)/deltay))
    if j2 == ni:
        j2 = j2 - 1

    pp=[]
    if (i1==i2):
        if i1>0:
            i1=i1-1
        else:
            i2=i2+1
    if (j1==j2):
        if j1>0:
            j1=j1-1
        else:
            j2=j2+1

    pp=[points[i1 * nj + j1], points[i1 * nj + j2], 
            points[i2 * nj + j1], points[i2 * nj + j2]]

    (x1, y1, q11), (_x1, y2, q12), (x2, _y1, q21), (_x2, _y2, q22) = pp
    return (q11 * (x2 - x) * (y2 - y) +
                q21 * (x - x1) * (y2 - y) +
                q12 * (x2 - x) * (y - y1) +
                q22 * (x - x1) * (y - y1)) / ((x2 - x1) * (y2 - y1))

相关问题 更多 >