【问题标题】:Overlap graph on image using coordinates使用坐标在图像上重叠图形
【发布时间】:2020-05-29 19:16:28
【问题描述】:

我有两个坐标列表:第一个用于 x 坐标,第二个用于 y 坐标。我试图将它们用作图形的节点。

import networkx as nx
list_of_coordinates_x = list(4.5 , 4, 67, 578, 68) #random numbers
list_of_coordinates_y = list(6.7, 3, 12, 45.555, 692)

G=nx.MultiGraph()
for i in range(len(list_of_coordinates_x)):
    G.add_node(i, x = list_of_coordinates_x[i], y = list_of_coordinates_y[i])
    if i > 0:
       G.add_edge(i-1,i)

nx.draw(G,node_size=10,with_labels=False)

但是我通过这种方式获得的所有图表看起来像是随机放置在平面上的节点集。如何通过图像上的坐标固定它们?我怎样才能使用我自己的 1680x1050 .jpg 文件呢? 在使用问题第一部分的答案后,我得到了这张图:

但我想把它放在这样的图片上:

【问题讨论】:

  • 您遵循什么标准来设置节点之间的边?只是连续的节点?
  • @yatu 我在具有连续索引的节点之间制作它们。仅仅因为我的节点代表了绘图上某个移动点和边缘的坐标——它们之间的时间过渡。

标签: python python-3.x networkx


【解决方案1】:

为此,您需要将节点位置设置为属性,并使用占位符作为节点名称。因此,一种方法可能是按节点出现的顺序仅enumerate 节点,并遵循与您相同的逻辑,但将压缩坐标元素添加为pos 属性:

x = [4.5 , 420, 67, 620, 68]
y = [6.7, 68, 56, 231, 380]

G = nx.DiGraph()
coords = list(zip(x,y))
for node, coo in enumerate(coords, start=1):
    G.add_node(node, pos=coo)
    if node<len(coords):
        G.add_edge(node, node+1)

然后您可以创建一个字典为node:(x,y),这是nx.draw 中的pos 所期望的格式,并且节点以这种方式位于指定坐标上:

nodes = G.nodes(data=True)
pos = {node:attr['pos'] for node, attr in nodes}
plt.figure(figsize=(12,5))
nx.draw(G,
        nodelist=nodelist,
        pos=pos,
        node_size=500,
        node_color='orange')

为了在现有图像上重叠图表,您必须确保它们共享相同的extent。这很好解释here

多张图片叠加时,图片需要相同 程度。这并不意味着它们需要具有相同的形状,而是 他们都需要渲染到相同的坐标系,由 xmin, xmax, ymin, ymax

为此,您可以在一定程度上对图形坐标和图像强制执行。该值将取决于图像大小,因此您必须将图形和图像的范围调整为图像的实际大小。我将使用来自klearn.datasets.load_sample_image 的示例图像作为示例,但对于您自己的图像,您可以使用matplotlib.image.imread('my_image.jpg') 加载它。

from sklearn.datasets import load_sample_image
img = load_sample_image('flower.jpg')

x = [4.5 , 420, 67, 620, 68]
y = [6.7, 68, 56, 231, 380]

y_lim, x_lim = img.shape[:-1]
extent = 0, x_lim, 0, y_lim

G = nx.DiGraph()
coords = list(zip(x,y))
for node, coo in enumerate(coords, start=1):
    G.add_node(node, pos=coo)
    if node<len(coords):
        G.add_edge(node, node+1)

fig = plt.figure(frameon=False, figsize=(10,19))

plt.imshow(img, extent=extent, interpolation='nearest')

nodes = G.nodes(data=True)
pos = {node:attr['pos'] for node, attr in nodes}
nx.draw(G,
        nodelist=nodelist,
        pos=pos,
        node_size=200,
        edge_color='w',
        width=4,
        extent=extent,
        node_color='orange',
       interpolation='nearest')
plt.show()

【讨论】:

  • 什么是“压缩坐标”?
  • 它只是在列表中使用zipzip 将多个迭代聚合成元组。所以在这种情况下,它会给(x0,y0),(x1,y1),... @Arsenii
  • 对不起,我堆在这里:pos = {node:attr['pos'] for node, attr in nodes}这会儿发生了什么? attr['pos'] 是什么意思?
  • 希望这更像你想要的@Arsenii
  • 哦,非常感谢,看起来很棒)我会用它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
相关资源
最近更新 更多