# Merge vertexes that are close together in MorphologicalGraph

Suppose I have a image and I take its MorphologicalGraph by using the following code:

p1 = Binarize[ImagePad[image, ImageDimensions[image][]*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 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]}] • 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? – Char Jul 5 at 5:13
• @Char, try g2 = SetProperty[Fold[VertexContract, g, vlists], {VertexLabels -> "Name", ImageSize -> Large, VertexCoordinates -> {v_ :> vcoords[v]}}]; IndexGraph[g2] – kglr Jul 5 at 5:41