Networkx: Importing graph with node values and edges information - networkx

I am generating random Geometric graph using networkx. I am exporting all the node and edges information into file.
I want to generate the same graph by importing all the node and edges information from file.
Code to export the node values and edge information.
G=nx.random_geometric_graph(10,0.5)
filename = "ipRandomGrid.txt"
fh=open(filename,'wb')
nx.write_adjlist(G, fh)
nx.draw(G)
plt.show()
I am trying to export it with below code and trying to change the color of some nodes. But it is generating different graph.
filename = "ipRandomGrid.txt"
fh=open(filename, 'rb')
G=nx.Graph()
G=nx.read_adjlist("ipRandomGrid.txt")
pos=nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b')
nx.draw(G)
plt.show()
How to generate the same graph with few changes in color of some nodes?

If I understand the problem you're having correctly, the trouble is here:
pos=nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,nodelist=['1','2'],node_color='b')
nx.draw(G)
You create a random layout of the graph in the first line, and use it to draw nodes '1' and '2' in the second line. You then draw the graph again in the third line without specifying the positions, which uses a spring model to position the nodes.
Your graph has no extra nodes, you've just drawn two of them in two different positions. If you want to consistently draw a graph the same way, you need to consistently use the pos you calculated. If you want it to be the same after storing and reloading, then save pos as well.

The easiest way to store node position data for your case might be using Python pickles. NetworkX has a write_gpickle() function that will do this for you. Note that the positions are already available as node attributes when you generate a random geometric graph so you probably want to use those when drawing. Here is an example of how to generate, save, load, and draw the same graph.
In [1]: import networkx as nx
In [2]: G=nx.random_geometric_graph(10,0.5)
In [3]: pos = nx.get_node_attributes(G,'pos')
In [4]: nx.draw(G,pos)
In [5]: nx.write_gpickle(G,'rgg.gpl')
In [6]: H=nx.read_gpickle('rgg.gpl')
In [7]: pos = nx.get_node_attributes(H,'pos')
In [8]: nx.draw(H,pos)

Related

Instance annotations in KITTI-360 2D instacne datasets

I am trying to count the instance of the vehicle in each image in KITTI-360 instance segmented dataset. For a trial, I first tried to do it on the single image. But I am getting only one instance value when I run my code. Which means that all the instances of the vehicle class are denoted by only one value in the image. I have attached the code that I used for finding this below.
I want to know why this is? or if I am doing something wrong in my code?
"""
This file is for the verification of the instance confirmation for the pixel values
"""
This file is for the verification of the instance confirmation for the pixel values
"""
#Imports
import os
import numpy as np
import cv2
import json
# Import image from the file location
CWD = os.getcwd()
print(CWD)
instance_folder = os.path.join(CWD, 'image_my_data', "instance")
print(instance_folder)
instance_image_path = os.path.join(instance_folder, "0000004402.png")
print(instance_image_path)
instance_image_array = cv2.imread(instance_image_path)
# print the size of the image for reference
print(instance_image_array.shape)
# Following are pixel values are measured and wanted to see what are the instance values at these pixel locations.
# Pixel location as tuples
pixel_location_1 = (210, 815)
pixel_location_2 = (200, 715)
# print the pixel location, for the above values
print('pixel values at (210, 815)', instance_image_array[pixel_location_1[0], pixel_location_1[1]])
print('pixel values at (200, 715)', instance_image_array[pixel_location_2[0], pixel_location_2[1]])
Note: the values of the pixels that I have taken above I choose by opening the image in paint and noting down the pixel coordinates in x and y in any locations where I can physically see that the two separate instances of the class are present.
Hope someone is able to help me with this.
I found the answer to my own question. The easiest way to find the instance in an image is to read the image using the cv2.imread(image, cv2.IMREAD_ANYDEPTH)
The reason for doing this is, the KITTI-360 images are 8 bit images. So, we can use the regular imread for reading the image as a RGB image but that will not give the correct instance ids. When using the method above will convert the image into a single channel read and that single channel will contain the instance ids of each object.
I hope this helps someone else.

How to Highlight any given path in pyvis network graph visualization?

I'm working on a project in which first i had to detect the shortest path in a huge network graph using a-star algorithm followed by visualizing the same graph using pyvis network. However in this pyvis network the path that I've calculated should be highlighted as shortest path.
eg: consider this code for game of thrones character network
from pyvis.network import Network
import pandas as pd
got_net = Network(height='750px', width='100%', bgcolor='#222222', font_color='white')
# set the physics layout of the network
got_net.barnes_hut()
got_data = pd.read_csv('https://www.macalester.edu/~abeverid/data/stormofswords.csv')
sources = got_data['Source']
targets = got_data['Target']
weights = got_data['Weight']
edge_data = zip(sources, targets, weights)
for e in edge_data:
src = e[0]
dst = e[1]
w = e[2]
got_net.add_node(src, src, title=src)
got_net.add_node(dst, dst, title=dst)
got_net.add_edge(src, dst, value=w)
neighbor_map = got_net.get_adj_list()
# add neighbor data to node hover data
for node in got_net.nodes:
node['title'] += ' Neighbors:<br>' + '<br>'.join(neighbor_map[node['id']])
node['value'] = len(neighbor_map[node['id']])
got_net.show('gameofthrones.html')
Now how do i highlight a specific path in this graph? i've gone through the documentation but there isn't anything similar
Here's an example using NetworkX to create the graph and gravis to visualize it. I had to use a different URL, hope it's the same data. I've used the weight as edge widths and colored some with large weights. Alternatively you can calculate a shortest path between two nodes of interest and then color that path or assign edge widths so it stands out.
Disclosure: I'm the author of gravis. I don't know if the same can be achieved with pyvis, but since I know that gravis supports the requirements well, I provided this solution and hope it's useful.
import gravis as gv
import networkx as nx
import pandas as pd
url = 'https://raw.githubusercontent.com/pupimvictor/NetworkOfThrones/master/stormofswords.csv'
got_data = pd.read_csv(url)
g = nx.Graph()
for i, (source, target, weight) in got_data.iterrows():
width = weight/10
g.add_edge(source, target, size=width, color='blue' if width > 3 else 'black')
gv.d3(g)
Edit: Here's the output if you use this code inside a Jupyter notebook. You can also use a regular Python interpreter and display the plot inside a browser window that pops up with fig = gv.d3(g) followed by fig.display().

how to create graph by edge and vertex txt file?

edge : vertex[coordinate]--vertex[coordinate]
how to feed the vertex and edge to a graph? I have tried by myself, but have problems.
import string
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph() # 建立一个空的无向图G
with open("HLN-12-1vertices.txt") as node_list:
for eachline in node_list:
G.add_node()
with open("HLN-12-1edges.txt") as edge_list:
for eachline in edge_list:
G.add_node()
print("number of edges:", G.number_of_edges()) # 输出边的数量
nx.draw(G)
plt.show()
First, you aren't actually passing the node name to the G.add_node parameter. If each line in your vertices text file has the name of the node, you can pass the variable eachline to the function (you might have to parse the file for end of line characters and other parsing if the file is formatted differently.
When you're reading the edges text file, the code again doesn't pass the edge data to the function, and you since you're passing the edge information, you need to use the function G.add_edge() instead. This function takes the parameters 'u_of_edge' and 'v_of_edge' which are the two endpoints of the edge.
Lastly, the function G.add_edge already adds new vertices to the graph if they aren't already created, so if all your vertices have an edge in the edges text file you can skip reading from the vertices text file.

How to get region of interest in images

I need to train R-CNN on my dataset. Above Image is an example in which first column contain path to that image and second column contain coordinates of bounded box(ROI). How to get those coordinates in matlab. As my dataset is large so how those coordinates can be extracted by pointing manually.
for example if i am training R-CNN foe stop signs then second column contain coordinates of bounded box containing stop sign in whole image.
I do not know which version of MATLAB you are running, but I'm assuming it is fairly new (R2017a and later). Also, by 'how to get the coordinates', I assume you mean 'how to determine' or 'how to assign' the coordinates.
I believe what you need to do is to use one of the image labeling Apps called
imageLabeler
to annotate rectangles in your training images. You either do this manually if that's amenable, or you need to use automation algorithms if you already have a detector that does something similar. See this page for more details:
https://www.mathworks.com/help/vision/ug/create-and-import-an-automation-algorithm-for-ground-truth-labeling.html
Once you have the results of labeling stored in a groundTruth object, you would need to use something like objectDetectorTrainingData to create the table you are looking for.
See https://www.mathworks.com/help/vision/ug/train-an-object-detector-from-ground-truth-data.html for more details.

qgis (segment (link) start node and end node id's extraction from shapefile )

I have been dealing with a lot of shape files editing tools last month..
I tried to get two dbf files from shape file (one for nodes and one for links) in an appropriate format (node_id,x,y for nodes and link_id,start_node_id,end_node_id,...for links)in order to create an oracle spatial network.
I got the dbf for nodes..
I want now to get the attribute table from a loaded shape file containing polylines (roads) and I want to split each polyline to its segments containing their start and end node id's besides their geometry..
Every help accepted..
You might want to clarify your question slightly, but it sounds like you want to get the details of each point in a polyline from a shapefile so that you can define segments.
I wrote an example of how you can do this using Python here:
https://gis.stackexchange.com/questions/40798/how-to-split-shapefile-per-feature-in-python-using-gdal
Specifically, pay attention to the lines:
line = geom.asPolyline()
# all points in the line
for point in line:
You should be able to achieve your goal using a variation of this basic example.
Dan