While working on an answer for another problem I hit upon one of my own.
I took the image given in that question and cleaned it up so that I could detect the grid lines:
i = ColorNegate@
Binarize[Import["https://i.sstatic.net/NbTGY.jpg"], .99]
lines = ImageLines[
Image[ImageData@Dilation[i, 0.5] -
ImageData@DeleteBorderComponents@Dilation[i, 0.5]]
];
Show[i, Graphics[{Thick, Green, Line /@ lines}]]
From here I would like to rotate the grid so that the they are absolutely vertical and horizontal. The original picture looks like a scanned piece of paper and I imagine it could be rotated more than this sample is.
My attempt was to separate the horizontal lines from the vertical lines:
hor = Select[lines, #[[1, 1]] == 0 &];
ver = Reverse[Select[lines, #[[2, 2]] == 0 &], 2];
Then I would like to find a transfer function that will bring the end point of each horizontal line to the same y value that the starting point has, and respectively for the vertical lines.
So my fruitless attempt to do that looks like this:
pts = {Join[Transpose[Apply[{#, 0} &, ver, {2}]][[1]],
Transpose[Apply[{0, #2} &, hor, {2}]][[1]]],
Join[Transpose[Apply[{#, 0} &, ver, {2}]][[2]],
Transpose[Apply[{0, #2} &, hor, {2}]][[2]]]}
pts // MatrixForm
And then
transf = FindGeometricTransform[pts[[1]], pts[[2]]][[2]];
newLines = transf@# & /@ lines;
Show[ImagePerspectiveTransformation[i, transf, DataRange -> Full],
Graphics[{Thick, Green, Line /@ newLines, Yellow, Line /@ lines}]]
It returns errors and I don't get the rotation I'm looking for.
Any ideas are welcome as long as they start from the lines that I have. It may be possible to find the grid in a different way and perhaps then the procedure to find the rotation would not be the same.
FindGeometricTransform
from another answer, but I don't seem to have understood it properly: mathematica.stackexchange.com/questions/1524/… $\endgroup$