循環我在python定義的一些形狀,其具有相應的角點,這樣的:通過節點和提取的屬性在Networkx
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')
爲此,我要通過節點循環,提取center
的形狀,提取其他形狀(不是它們自己,它是無用的)並且使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 inside triangle
)或一些錯誤的關係(如pentagon inside square
)
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