You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Scipy Delaunay Triangulation的simplices转Networkx图报错

问题原因与解决方法

报错原因

  • 你调用nx.Graph(simplices)时,NetworkX默认会将输入的numpy数组识别为邻接矩阵,邻接矩阵要求必须是n×n的方阵,而你传入的simplices是存储三角形顶点索引的n×3数组,形状不匹配,所以触发了对应报错。
  • 你后续写的循环调用nx.add_path的逻辑方向是对的,但存在小缺陷,且不需要提前给Graph构造函数传参。

额外注意事项

nx.add_path是按照传入列表的顺序依次连接相邻元素,对于三个顶点的三角形来说,直接传三角形顶点列表调用nx.add_path只会生成两条相邻边,会遗漏第一个顶点和最后一个顶点的连接边,导致三角网不完整。

修正后可运行代码

import numpy as np
import networkx as nx
from scipy.spatial import Delaunay as scipy_Delaunay

# tri = scipy_Delaunay(pts[:, 0:2]) # 输入点集
# simplices = tri.simplices
   
simplices = np.array([[ 9, 13, 19],
                     [11,  9,  4],
                     [ 9, 11, 13],
                     [ 0,  7,  2],
                     [ 7,  3, 18]])
# 初始化空图
G = nx.Graph()
for tri in simplices:
    # 为每个三角形添加全部三条边
    G.add_edges_from([(tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])])

nx.draw(G, with_labels=True, node_size=500, node_color='lightgreen')

可选简化写法

如果你希望保留add_path的写法,也可以将三角形顶点列表补成闭合路径:

for tri in simplices:
    nx.add_path(G, list(tri) + [tri[0]])

内容的提问来源于stack exchange,提问作者Natasha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 01:45:04