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

calculus and analysis - Integral of the Sinc product

Let us consider the following integral $$ B_n = \int_0^\infty \prod_{k=1,3,5,\dots}^n\frac{\sin (x/k)}{x/k}dx $$ By definition, Sinc[x] == Sin[x]/x , therefore B[n_?OddQ] := Integrate[Product[Sinc[x/k], {k, 1, n, 2}], {x, 0, Infinity}] B /@ Range[1, 13, 2] {Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2, Pi/2} OK, everything is fine. But... B[15] 467807924713440738696537864469 Pi/935615849440640907310521750000 What's going on? Answer As Eckhard wrote in comments B[n] is the n-th Borwein integral . (The letter B was not accidental :) ) This funny properties of Borwein integrals is related to the Fourier transform of Sinc function FourierTransform[Sinc[x], x, k] 1/2 Sqrt[Pi/2] (Sign[1 - k] + Sign[1 + k]) Plot[%, {k, -2, 2}, Filling -> 0] which is the box function. The result is $\pi/2$ while the sum $$ 1/3+1/5+\dots+1/n $$ B_n = \frac{\pi}{2} - \pi \bigg(\sum_{k=3,5,\ldots}^n\frac{1}{k} -1\biggr)^\frac{n-1}{2}\prod_{k=3,5,\dots}^n\frac{k}{k-1}. $$ For $n=15$ it is equal to $$ \frac{46780...

list manipulation - Solving word search puzzles

I am trying to create a code that can identify the following terms in a grid of letters: MATHEMATICA, STACK, EXCHANGE and USERS. list1={"M","S","T","A","S","I","S","X","X","T","R","X"}; list2={"A ","T ","H ","X ","R ","X ","G ","R ","S ","H ","X ","A"}; list3={"M","A","T","H","E","M","A","T","I","C","A","I"}; list4={"A","X","S","G","S","X","A","I","R","T","X","T"}; list5={"T","I","T","G","U","C","C","I","R","N",...

implicit - Plotting a function with implicitly defined variable

I have a question about plotting a function with an implicitly defined variable. I think the solution should be something similar like here: Define a function with variables linked implicitly but I quite can't get it to work. I apologize if this has been asked for, I tried doing a thorough search before asking. Anyway, I am trying to plot the following function: $$ u(x,y,t)=\text{sgn}(x+y-t+r(t))\big(e^{-\vert x+y-t+r(t) \vert }-1\big)+r(t)e^{-\vert x+y+r(t)+\ln(\frac{1}{9}r(t)^2-\frac{1}{2}r(t)+1)\vert} $$ where $r(t)$ is implicitly defined with the following equation $$ \ln\vert r(t)\vert-\frac{1}{2}\ln\vert r(t)^2-\frac{9}{2}r(t)+9\vert+\frac{3\sqrt{}{7}}{7}\tan^{-1}\big(\frac{4r(t)-9}{3\sqrt{}{7}}\big)=2t. $$ Ultimately, I would like to use Plot3D for $u(x,y)$ and use Manipulate to see the function at different time steps of $t$. Thank you in advance for your time and help. It's greatly appreciated. Edit: Here is some mathematica format to make life easier: Sign[x + y - t ...