I have a numpy array full of values that I would like to create vertices from for every point in the array. I am using networkx as my graphing support method(documentation here: http://networkx.github.io/documentation/latest/tutorial/ )
I would like to treat each element within the array as a pixel location and create a vertex instance at each location. This is easy using a simple for loop:
new=np.arange(16)
gnew=nx.Graph()
for x in new:
if new[x]>0:
gnew.add_node(x)
h=gnew.number_of_nodes()
print h
And as expected, 15 nodes will be printed. However, this becomes more tricky when you have identical values. For example:
new=np.ones(16)
gnew=nx.Graph()
for x in new:
if new[x]>0:
gnew.add_node(x)
h=gnew.number_of_nodes()
print h
Now, because all values are identical-(1), only one node will be added to the graph. Is there a way to circumnavigate this?
NetworkX requires that each node have a unique name. You could generate unique names and then set the elements of your array to be attributes of the nodes, eg
new = np.ones(16);
othernew = np.arange(16)
G = nx.Graph()
for i in range(len(othernew)):
if new[i]>0:
G.add_node(othernew[i])
G.node[othernew[i]]['pos'] = new[i] #This gives the node a position attribute with value new[i]
h = G.order()
print(h)
>>16
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.