9
$\begingroup$

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

example

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?

example2

$\endgroup$
  • $\begingroup$ 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"] $\endgroup$ – Bob Hanlon Mar 23 at 17:32
11
$\begingroup$
doodle = Import["https://i.stack.imgur.com/QJcLR.jpg"]

enter image description here

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

enter image description here

EdgeList[mg]

enter image description here

Graph[mg, PlotTheme -> "VintageDiagram"]

enter image description here

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

enter image description here

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

enter image description here

Graph[mg2, PlotTheme -> "VintageDiagram"]

enter image description here

| improve this answer | |
$\endgroup$
3
$\begingroup$

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.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.