# Index of MorphologicalGraph[] and GraphEmbedding[] do not match

I am planning to automatically detect number of bifurcation of each node in tree structure from images. At first we obtain tree graph from image using

branchGraph = MorphologicalGraph[image, VertexLabels -> "Name"]


Next we try to obtain coordinates of each nodes using GraphEmbedding[].

nodeCoordinates = GraphEmbedding[branchGraph]


We can obtain coordinate by this, but correlation between node index in the graph and location in the list is not identical.

graphEmbeddingIndex =
Show[Graphics[
Table[{Red, Text[i, nodeCoordinates[[i]]]}, {i, 1,
Length[nodeCoordinates]}]]]

Show[branchGraph, graphEmbeddingIndex]


Is there any good way to know the coordinate of certain node in a graph?

Sincerely,

Takashi Miura.

img = Import["https://i.stack.imgur.com/U5yMN.png"]


g = MorphologicalGraph[img, VertexLabels -> "Name", ImagePadding -> 20]


The vertex coordinates given by GraphEmbedding[g] are in the order of VertexList[g]. That is, GraphEmbedding[g][[i]] corresponds to the vertex VertexList[g][[i]], which, in turn, is not necessarily equal to i, since the vertices in VertexList[g] are in the order used in the graph g:

VertexList[g]


{1, 4, 2, 3, 5, 11, 6, 7, 9, 12, 8, 13, 14, 10, 15, 16, 17, 18, 19, 20}

So if you change your definition of nodeCoordinates to

nodeCoordinates = GraphEmbedding[g][[Ordering[VertexList[g]]]];


or to

nodeCoordinates = PropertyValue[{g, VertexIndex[g, #]}, VertexCoordinates] & /@
VertexList[g];


then we get the correct mapping using the modified nodeCoordinates in your graphEmbeddingIndex or, more directly,

Show[g, Epilog -> Table[{Red, Text[Style[i, 16], nodeCoordinates[[i]]]},
{i, 1, Length[nodeCoordinates]}], ImagePadding -> 20]


• This worked fine! Thank you very much! – Takashi Miura Jul 21 '18 at 11:21
• @TakashiMiura, my pleasure. Welcome to mma.se. – kglr Jul 21 '18 at 11:45