我正在使用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()
上面是我使用过的m5_骨骼.png图像。
您需要更换:
path = nx.astar_path(graph, graph.nodes.get(0), graph.nodes.get(10))
与
path = nx.astar_path(graph, 0, 10)
也就是说,该函数采用节点的ID作为输入,而不是节点的内容。
我是一名优秀的程序员,十分优秀!