3

I got this image after preprocessing the original image. Now, my question is how I can get the four corner's coordinates of the rectangle (largest). Sorry if this is so noob question.

enter image description here

Update: Since I am developing with OpenCV, ended up using this answer

Community
  • 1
  • 1
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240

1 Answers1

5

One simple way would be to:

  1. find all connected components
  2. calculate the convex hull for each component
  3. pick the component where the convex hull has the largest area
  4. simplify the convex hull polygon
  5. the vertices of the simplified polygon are the points you're looking for

Quick&dirty Mathematica solution:

(* find all connected components, calculate the convex hull for each component *)
convexHulls = ComponentMeasurements[ColorNegate[Binarize[src]], {"ConvexArea", "ConvexVertices"}];

(* pick the component where the convex hull has the largest area *)
vertices = SortBy[convexHulls[[All, 2]], First][[-1, 2]]

(* simplify the convex hull polygon, by iteratively removing the vertex with the lowest distance to the line through the vertex before and after it *)
distanceToNeighbors[vertices_] := MapThread[Abs[(#1 - #2).Cross[#1 - #3]/Norm[#1 - #3]]&, RotateLeft[vertices, #] & /@ {-1, 0, 1}]
removeVertexWithLowestDistance[vertices_] := With[{removeIndex = Ordering[distanceToNeighbors[vertices], 1]}, Drop[vertices, removeIndex]]
verticesSimplified = NestWhile[removeVertexWithLowestDistance, vertices, Min[distanceToNeighbors[#]] < 10&]

(* the vertices of the simplified polygon are the points you're looking for *)
Show[src, Graphics[
  {
   {EdgeForm[Red], Transparent, Polygon[verticesSimplified]},
   {Red, PointSize[Large], Point[verticesSimplified]}
   }]]

Result

Niki
  • 15,662
  • 5
  • 48
  • 74