# Turn handdrawn doodles into graph

I have doodled sketches of graphs in JPG format (they roughly look like stick men, in particular the vertices are not shown - they should be where the lines meet) and want to convert them into proper graphs in Mathematica.

Note that I am not concerned about the direction of edges, the graph structure is what matters, not the orientation of the edges or their coordinates; as long as I get a graph that's isomorphic to the sketched graph, that would be fine for me).

What can I do? Any help is welcome! TIA!

This is an example of a sketch that I want Mathematica to turn into a graph

When the sketches are a bit more rough with thicker edges, then kglr's (original) approach does not seem to work. I attached another figure. Note that this at first was ONLY the lines with a blank interior. I actually used a paint program to fill the inner part with black, but it did not work accurately, which makes everything more difficult, I guess. Is there anything I can do about this?

• Graph[{1 \[UndirectedEdge] 2, 3 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 4, 5 \[UndirectedEdge] 4, 4 \[UndirectedEdge] 6, 6 \[UndirectedEdge] 7, 6 \[UndirectedEdge] 8}, PlotTheme -> "IndexLabeled", GraphLayout -> "SpringElectricalEmbedding"] Mar 23, 2020 at 17:32

doodle = Import["https://i.stack.imgur.com/QJcLR.jpg"]


mg = MorphologicalGraph @ ColorReplace[doodle, {White -> Black, Black -> White}]


EdgeList[mg]


Graph[mg, PlotTheme -> "VintageDiagram"]


doodle2 = Import["https://i.stack.imgur.com/dRyDA.png"]


mg2 = MorphologicalGraph@
SkeletonTransform @ Thinning @
Closing[ColorNegate @ Binarize @ doodle2, DiskMatrix[2]]


Graph[mg2, PlotTheme -> "VintageDiagram"]


Before using MorphologicalGraph with your image that has thick lines, try thinning, after filling in the noise in your image:

Thinning[FillingTransform[ColorNegate[Binarize[image]]]]


If that leaves a few short edges you don't want, try the Pruning function.