title: How to find the best quadrilateral to approximate an OpenCV contour?
body: <p>I have an OpenCV contour <code>c</code> which is close to a quadrilateral in its shape, but it can have 4 to multiple of dozens of points.</p>
  <p>I want to find the quadrilateral <code>q</code> which is the closest to the contour <code>c</code> (one way could be to minimize the area of the difference between them).</p>
  <p>I currently use</p>
  <pre><code>q = cv2.approxPolyDP(c, 0.02 * cv2.arcLength(c, True), closed=True)
  </code></pre>
  <p>but the result is <strong>not always a quadrilateral</strong>. I have already tried techniques like those in <a href="https://stackoverflow.com/questions/62274412/cv2-approxpolydp-cv2-arclength-how-these-works">cv2.approxPolyDP() , cv2.arcLength() How these works</a> and in <a href="https://stackoverflow.com/questions/13028961/how-to-force-approxpolydp-to-return-only-the-best-4-corners-opencv-2-4-2">How to force approxPolyDP() to return only the best 4 corners? - Opencv 2.4.2</a> (binary search for example), but it doesn't always yield a quadrilateral.</p>
  <p><strong>Is there another way (probably with something else than <code>approxPolyDP</code>?) to find the best quadrilateral approximation to a contour?</strong></p>
  <p>Note: another linked question is <a href="https://stackoverflow.com/questions/22490858/crop-image-based-on-largest-quadrilateral-contour-opencv">Crop image based on largest quadrilateral contour OpenCV</a> but it does not give a solution to this problem.</p>