Skip to main content

Share a method to patch the discontinuous line in a image


Similar to this post which I have posted before(How to patch fingerprint ridges),Its solution's level higher than my expectation.So cost my these days to research this.Now I'm glad to share my fruit in here,You can use this code to produce a broken heart line.


SetAttributes[RandomDrop, HoldFirst]

RandomDrop[list_, n_] :=
Module[{pre, temp},
Do[pre = RandomInteger[{1, Length[list]}]; temp = RandomInteger[25];
If[pre + temp <= Length[list],
list = Drop[list, {pre, pre + temp}], Continue[]], n]; list]

MakeBrokenHeart[n_] :=
Module[{sortpos, graph, pos},
graph = ContourPlot[((1.2 x)^2 + (1.4 y)^2 - 1)^3 - (1.3 x)^2 y^3 ==
0, {x, -1.5, 1.5}, {y, -3/2, 3/2}, AspectRatio -> Automatic,

Frame -> False, PlotPoints -> 200];
pos = PixelValuePositions[graph // Binarize // ColorNegate, 1];
sortpos = pos[[Last@FindShortestTour[pos]]];
Binarize@ImageRotate@
ImagePad[
ImageCrop@Image[SparseArray[RandomDrop[sortpos, n] -> 1]], 5]]

Answer



What you have here is called a matching problem in graph theory: You want to connect a set of nodes so that



  • each node is connected to exactly to one edge,


  • and some cost function over the edges is minimized.


I can't find a built-in function for solving matching problems, but it's not hard to convert it to a linear programming problem.


First, I'll find all the endpoints:


img = Binarize@Import["http://i.stack.imgur.com/zWNUV.png"]    
endPoints =
PixelValuePositions[MorphologicalTransform[img, "EndPoints"], 1];
endPointIndices = Range[Length[endPoints]];

Then I make a list of edges that connect each node to it's 4 closest neighbors (you could also start with a complete graph and get the same result in the end; this just keeps the search space smaller):



near = Nearest[endPoints -> endPointIndices];    
allEdges = DeleteDuplicates@Flatten@Table[
edge[Sort[{i, j}]], {i, endPointIndices}, {j,
Rest@near[endPoints[[i]], 5]}];

Now allEdges contains a list of the form edge[{1, 3}], edge[{1, 5}], edge[{1, 6}]..., connecting each node to its neighbors:


HighlightImage[img, allEdges /. edge[idx_] :> Line[endPoints[[idx]]]]

enter image description here


Next I want a rough direction for each endpoint. There are a lot of ways to do this. I'll simply select, for each end point, the points in the same arc that are closer than 20 pixels and take the mean of those points:



components = Image@MorphologicalComponents[img];
endPointNeighbors = Table[
pointsInSameComponent =
PixelValuePositions[components, PixelValue[components, pt]];
N@Mean[Select[pointsInSameComponent, Norm[# - pt] < 20 &]]
, {pt, endPoints}];

endPointNeighbors[[i]] now contains the center of the neighbors on the same arc as endpoint[[i]]:


HighlightImage[img, 
Table[Arrow[{endPointNeighbors[[i]], endPoints[[i]]}], {i,

endPointIndices}]]

enter image description here


So that gives me the "direction" from each endpoint:


endPointDirection[i_] := 
Normalize[endPoints[[i]] - endPointNeighbors[[i]]]

and I can define a "cost" for each edge:


edgeCost[edge[{i_, j_}]] := 
Norm[endPoints[[i]] - endPoints[[j]]] +

10*endPointDirection[i].endPointDirection[j]

(I've used a weighted sum of the distance of the end points and the scalar product of the edge directions. You can read it as "if the lines point in the same direction, make the edge 10 pixels longer; if the lines point in opposite directions, make it 10 pixels shorter". So edges pointing in the right direction are cheaper. You could probably come up with a smarter cost function.)


So far so well. Now I'll use FindMinimum to find a set of edges that minimizes the cost, and assigns exactly one edge to each end point.


I'll use variables connected[{i, j}], where connected[{i,j}] == 1 means that endpoints i and j are connected, so I have the variables:


allVariables = allEdges /. edge[idx__] :> connected[idx];

and the total cost of all connected edges:


cost = Total[
allEdges /. e : edge[{i_, j_}] :> N@edgeCost[e]*connected[{i, j}]];


The connected[{i,j}]-variables should all be between 0 and 1 (in fact, the result will always be 0 or 1, exactly):


connectedRange = allEdges /. edge[idx__] :> 0 <= connected[idx] <= 1;

And I want each end point to be connected to exactly one edge:


singleEdge = Table[
Total[Cases[allEdges,
edge[idx_] /; MemberQ[idx, i] :> connected[idx]]] == 1,
{i, endPointIndices}];


Optimization:


{totalCost, solution} = 
FindMinimum[Flatten[{cost, connectedRange, singleEdge}],
allVariables];

yields a solution that looks like this:



connected[{1, 3}] -> 1., connected[{1, 5}] -> 0., connected[{1, 6}] -> 0., connected[{1, 9}] -> 0., connected[{2, 4}] -> 1.



So we can pick the edges where connected is 1:



connectedEdges = Pick[allEdges, Round[allVariables /. solution], 1];

and display them:


HighlightImage[img, 
connectedEdges /. edge[idx_] :> Line[endPoints[[idx]]]]

enter image description here


The algorithm is guaranteed to connect every end point to exactly one edge (and will therefore fail if the number of end points is odd), and it will always have the lowest possible cost (it's a linear programming problem, so FindMinimum is fast and guaranteed to find the optimal solution`). But the quality of the final matching will depend on the edge cost function, of course.


So for example, if I only minimize the distance between edges, I'll get this matching:


enter image description here



The total distance of all the edges is shorter, so the algorithm is correct. Or in other words: You'll probably have to play with the cost function a little to get the results you want.


Comments

Popular posts from this blog

front end - keyboard shortcut to invoke Insert new matrix

I frequently need to type in some matrices, and the menu command Insert > Table/Matrix > New... allows matrices with lines drawn between columns and rows, which is very helpful. I would like to make a keyboard shortcut for it, but cannot find the relevant frontend token command (4209405) for it. Since the FullForm[] and InputForm[] of matrices with lines drawn between rows and columns is the same as those without lines, it's hard to do this via 3rd party system-wide text expanders (e.g. autohotkey or atext on mac). How does one assign a keyboard shortcut for the menu item Insert > Table/Matrix > New... , preferably using only mathematica? Thanks! Answer In the MenuSetup.tr (for linux located in the $InstallationDirectory/SystemFiles/FrontEnd/TextResources/X/ directory), I changed the line MenuItem["&New...", "CreateGridBoxDialog"] to read MenuItem["&New...", "CreateGridBoxDialog", MenuKey["m", Modifiers-...

How to thread a list

I have data in format data = {{a1, a2}, {b1, b2}, {c1, c2}, {d1, d2}} Tableform: I want to thread it to : tdata = {{{a1, b1}, {a2, b2}}, {{a1, c1}, {a2, c2}}, {{a1, d1}, {a2, d2}}} Tableform: And I would like to do better then pseudofunction[n_] := Transpose[{data2[[1]], data2[[n]]}]; SetAttributes[pseudofunction, Listable]; Range[2, 4] // pseudofunction Here is my benchmark data, where data3 is normal sample of real data. data3 = Drop[ExcelWorkBook[[Column1 ;; Column4]], None, 1]; data2 = {a #, b #, c #, d #} & /@ Range[1, 10^5]; data = RandomReal[{0, 1}, {10^6, 4}]; Here is my benchmark code kptnw[list_] := Transpose[{Table[First@#, {Length@# - 1}], Rest@#}, {3, 1, 2}] &@list kptnw2[list_] := Transpose[{ConstantArray[First@#, Length@# - 1], Rest@#}, {3, 1, 2}] &@list OleksandrR[list_] := Flatten[Outer[List, List@First[list], Rest[list], 1], {{2}, {1, 4}}] paradox2[list_] := Partition[Riffle[list[[1]], #], 2] & /@ Drop[list, 1] RM[list_] := FoldList[Transpose[{First@li...

plotting - How to draw lines between specified dots on ListPlot?

I would like to create a plot where I have unconnected dots and some connected. So far, I have figured out how to draw the dots. My code is the following: ListPlot[{{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4,13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full] I have thought using ListLinePlot command, but I don't know how to specify to the command to draw only selected lines between the dots. Do have any suggestions/hints on how to do that? Thank you. Answer One possibility would be to use Epilog with Line : ListPlot[ {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {1, 4}, {2, 5}, {3, 6}, {4, 7}, {1, 7}, {2, 8}, {3, 9}, {4, 10}, {1, 10}, {2, 11}, {3, 12}, {4, 13}, {2.5, 7}}, Ticks -> {{1, 2, 3, 4}, None}, AxesStyle -> Thin, TicksStyle -> Directive[Black, Bold, 12], Mesh -> Full, Epilog -> { Line[ ...