gpt4 book ai didi

python - networkx.exception.NodeNotFound 即使节点存在

转载 作者:太空宇宙 更新时间:2023-11-03 19:45:32 25 4
gpt4 key购买 nike

我正在使用sknw用于从骨架化图像构建图形(图像由 scikit-image 生成)。问题是当我尝试使用 skimage networkx.exception.NodeNotFound 中给出的任何算法绘制最短路径时。但函数 graph.has_node() 表示该节点存在。

困了好几天了,不知道该怎么办。如有任何帮助,我们将不胜感激。

代码

from skimage.morphology import skeletonize
from skimage import data, io
from skimage.graph import shortest_path
import matplotlib.pyplot as plt
import sknw
import networkx as nx
import numpy as np
import numba


img = io.imread('m5_skeleton.png')
ske = skeletonize(img).astype(np.uint16)

# build graph from skeleton
graph = sknw.build_sknw(ske)

# draw image
plt.imshow(img, cmap='gray')

# draw edges by pts
for (s, e) in graph.edges():
ps = graph[s][e]['pts']
plt.plot(ps[:, 1], ps[:, 0], 'green')

# draw node by o
nodes = graph.nodes()
ps = np.array([nodes[i]['o'] for i in nodes])
plt.plot(ps[:, 1], ps[:, 0], 'r.')

print('------------------------------------------------------------------------------')
print('nodes')
print('------------------------------------------------------------------------------')
print(nodes)
print('------------------------------------------------------------------------------')

# title and show
plt.title('Build Graph')
plt.savefig('m5_graph.svg', dpi=1200)

pos = nx.spring_layout(graph)
print('------------------------------------------------------------------------------')
print('pos')
print('------------------------------------------------------------------------------')
print(pos)
print('------------------------------------------------------------------------------')

# nx.draw(graph, pos, node_color='k')

# draw path in red
print('graph.has_node(0): ' + str(graph.has_node(0)))
print('graph.has_node(10): ' + str(graph.has_node(10)))

# source = graph.nodes[0]
# target = graph.nodes[2]

path = nx.astar_path(graph, graph.nodes.get(0), graph.nodes.get(10))
h = graph.subgraph(path)
path_edges = zip(path, path[1:])
path_edges = set(path_edges)
nx.draw_networkx_nodes(h, pos, nodelist=path, node_color='b', cmap='gray')
nx.draw_networkx_edges(h, pos, edge_cmap='gray')
plt.axis('equal')

plt.show()

enter image description here上面是我使用过的m5_骨骼.png图像。

最佳答案

您需要更换:

path = nx.astar_path(graph, graph.nodes.get(0), graph.nodes.get(10))

path = nx.astar_path(graph, 0, 10)

也就是说,该函数采用节点的ID作为输入,而不是节点的内容。

关于python - networkx.exception.NodeNotFound 即使节点存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60169019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com