Suppose I have a image

Test Image

and I take its MorphologicalGraph by using the following code:

p1 = Binarize[ImagePad[image, ImageDimensions[image][[1]]*0.05]];
p2 = Thinning[DeleteSmallComponents[ColorNegate[DeleteSmallComponents[p1, 300]], 300]];
p2 = Pruning[p2];
p2 = Thinning[p2];
img = p2;
g = MorphologicalGraph[img, PlotRangePadding -> 2]   

Which gives

Test Graph

There are certain areas where multiple vertexes are practically on the same point, or near the same point, such as


Is there a way to merge multiple vertexes that are near each other within a certain distance into a single vertex? Or is there a good way to process this image so that this can be solved? I've tried to fit linear lines into the image, but it's not quite working. Any help is greatly appreciated!

vcoords = AssociationThread[VertexList[g], GraphEmbedding[g]];

threshold = 50.;

vlists = Select[Length@# > 1 &]@
   Gather[VertexList[g], Norm[vcoords[#] - vcoords[#2]] <= threshold &];

SetProperty[Fold[VertexContract, g, vlists], VertexCoordinates -> {v_ :> vcoords[v]}]

enter image description here

  • $\begingroup$ Thank you so much! However, an issue that I encountered is how when I set VertexLabels using SetProperty, the numbering for labels is still the same after merging Vertexes within the threshold when compared to before. Is there a way to re-number the labels after merging the Vertexes so that it is continuous? $\endgroup$ – Char Jul 5 '20 at 5:13
  • 1
    $\begingroup$ @Char, try g2 = SetProperty[Fold[VertexContract, g, vlists], {VertexLabels -> "Name", ImageSize -> Large, VertexCoordinates -> {v_ :> vcoords[v]}}]; IndexGraph[g2] $\endgroup$ – kglr Jul 5 '20 at 5:41

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.