python - 使用纽厄尔方法在 Python 中计算表面法线

标签 python 3d geometry

我正在尝试基于 here 中的以下伪代码,在 Python 中实现 Newell 方法来计算表面法向量。 .

Begin Function CalculateSurfaceNormal (Input Polygon) Returns Vector

   Set Vertex Normal to (0, 0, 0)

   Begin Cycle for Index in [0, Polygon.vertexNumber)

      Set Vertex Current to Polygon.verts[Index]
      Set Vertex Next    to Polygon.verts[(Index plus 1) mod Polygon.vertexNumber]

      Set Normal.x to Sum of Normal.x and (multiply (Current.y minus Next.y) by (Current.z plus Next.z))
      Set Normal.y to Sum of Normal.y and (multiply (Current.z minus Next.z) by (Current.x plus Next.x))
      Set Normal.z to Sum of Normal.z and (multiply (Current.x minus Next.x) by (Current.y plus Next.y))

   End Cycle

   Returning Normalize(Normal)

End Function

这是我的代码:

Point3D = collections.namedtuple('Point3D', 'x y z')

def surface_normal(poly):
    n = [0.0, 0.0, 0.0]

    for i, v_curr in enumerate(poly):
        v_next = poly[(i+1) % len(poly)]
        n[0] += (v_curr.y - v_next.y) * (v_curr.z - v_next.z)
        n[1] += (v_curr.z - v_next.z) * (v_curr.x - v_next.x)
        n[2] += (v_curr.x - v_next.x) * (v_curr.y - v_next.y)

    normalised = [i/sum(n) for i in n]

    return normalised

def test_surface_normal():
    poly = [Point3D(0.0, 0.0, 0.0),
            Point3D(0.0, 1.0, 0.0),
            Point3D(1.0, 1.0, 0.0),
            Point3D(1.0, 0.0, 0.0)]

    assert surface_normal(poly) == [0.0, 0.0, 1.0]

这在标准化步骤中失败,因为此时的 n[0.0, 0.0, 0.0]。如果我理解正确的话,它应该是 [0.0, 0.0, 1.0] ( confirmed 作者:Wolfram Alpha)。

我在这里做错了什么?在 python 中是否有更好的计算表面法线的方法?我的多边形将始终是平面的,因此如果有其他方法,纽厄尔方法并不是绝对必要的。

最佳答案

好吧,这个问题实际上是一个愚蠢的问题。

如下行:

n[0] += (v_curr.y - v_next.y) * (v_curr.z - v_next.z)

应该是:

n[0] += (v_curr.y - v_next.y) * (v_curr.z + v_next.z) 

第二组括号中的值应该相加,而不是相减。

关于python - 使用纽厄尔方法在 Python 中计算表面法线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001642/

相关文章:

swift - 通过旋转获取 SCNNode 的边界体积

python - 如何使用 .whl 文件调用 pyspark 代码?

python - all() 和 .all() 之间的区别,用于检查可迭代是否在任何地方都为 True

python - 如何在 python/plotly 中制作 2D 向量分布的 3D 直方图

r - Z - R 中多边形(shapefile)的值

image - 如何在 MATLAB 中的图像上画一个圆圈?

python - 使用 Docker Python SDK (docker-py) 登录注册表

Python Numpy 数组附加空白列

c++ - 我需要什么来构建光线追踪 3d 图像的简单 3d 编辑器

2个方向均匀排列步数的算法