计算barycentric坐标的python代码

作为反复调用的工具,以免忘记重新造轮子


import numpy as np

def barycenter_coord(triangles2d, point):
    linea = triangles2d[1] - triangles2d[0]
    a, c = linea[0], linea[1]
    lineb = triangles2d[2] - triangles2d[0]
    b, d = lineb[0], lineb[1]
    ss = a * d - b * c
    if abs(ss) < 1e-9:
        return [-1, -1, 3, False]
    linex = point - triangles2d[0]
    k1 = (d * linex[0] - b * linex[1]) / ss
    k2 = (-c * linex[0] + a * linex[1]) / ss
    k0 = 1 - k1 - k2
    return [k0, k1, k2, k0>=0 and k1>=0 and k2>=0]

## 测试代码
for i in range(100):
    triangles2d = np.random.random((3, 2))
    res = np.random.random(3)
    res[0] = 0.3
    res[1] = 0.3
    res[2] = 1 - res[0] - res[1]
    point = res[0] * triangles2d[0] + \
    res[1] * triangles2d[1] + \
    res[2] * triangles2d[2]
    #
    # point = np.random.random(2)
    # point = np.array([0., 0.5])

    res11 = barycenter_coord(triangles2d, point.copy())
    pp = res11[0] * triangles2d[0] + \
         res11[1] * triangles2d[1] +\
         res11[2] * triangles2d[2] - point
    print("result=", res11, "   pp=", pp, "   res11 - res=", np.array(res11[:3]) - res)


你可能感兴趣的:(python,numpy,python,开发语言)