我在Python中定义了一些形状和相应的角点,就像这样:
square = [[251, 184],
[22, 192],
[41, 350],
[244, 346]]
triangle = [[250, 181],
[133, 43],
[21, 188]]
pentagon = [[131, 37],
[11, 192],
[37, 354],
[247, 350],
[256, 182]]
然后,我使用NetworkX包创建一个图:
G = nx.DiGraph()
接下来,我为每个形状在图表中创建一个节点:
G.add_node('square', points = square, center = (139, 265))
G.add_node('triangle', points = triangle, center = (139, 135))
G.add_node('pentagon', points = pentagon, center = (138, 223))
现在的问题是,如果符合以下条件,我必须创建一些连接两个节点的边缘: 如果一个形状的中心在另一个形状内或外,则创建这样的边缘:
G.add_edge('triangle', 'pentagon', relation = 'inside')
G.add_edge('triangle', 'square', relation = 'outside')
为了做到这一点,我必须循环遍历节点,提取形状的中心
,提取其他形状(不是自己的)的点
,并进行pointPolygonTest
。我已经尝试了很多次,但没有找到任何解决方案。我得到的最接近(并不是很有效)的解决方案是这个:
nodes_p=dict([((u),d['points']) for u,d in G.nodes(data=True)])
nodes_c=dict([((u),d['center']) for u,d in G.nodes(data=True)])
for z,c in nodes_c.items():
print z + ' with center', c
for z,p in nodes_p.items():
p_array = np.asarray(p)
if cv2.pointPolygonTest(p_array,c,False)>=0:
print 'inside ' + z
#create edge
else:
print 'outside ' + z
#create edge
这会给我以下输出,但不太理想,因为存在一些应该避免的关系(比如 三角形内嵌三角形
)或者一些错误的关系(比如 五边形内嵌正方形
)
triangle with center (139, 135)
inside triangle
outside square
inside pentagon
square with center (139, 265)
outside triangle
inside square
inside pentagon
pentagon with center (138, 223)
outside triangle
inside square
inside pentagon
我该如何解决这个问题?任何建议都将不胜感激。提醒一下:主要问题是如何循环遍历节点并提取信息。我为整个脚本导入的软件包有:
import numpy as np
import networkx as nx
import cv2
numpy
和cv2
)添加到代码中,以帮助未来的读者。 - yardsale8