13

How do these function works? I am using Python3.7 and OpenCv 4.2.0. Thanks in Advance.

approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
Aditya Anand
  • 161
  • 1
  • 1
  • 7
  • 3
    Welcome to Stack Overflow. Please take the **tour** (https://stackoverflow.com/tour) and read the information guides in the **help center** (https://stackoverflow.com/help), in particular, "How to Ask A Good Question" (https://stackoverflow.com/help/how-to-ask), "What Are Good Topics" (https://stackoverflow.com/help/on-topic) and "How to create a Minimal, Reproducible Example" (https://stackoverflow.com/help/minimal-reproducible-example). Please read the documentation and do some research before asking questions on this forum – fmw42 Jun 09 '20 at 04:55
  • Thanks sir. @MihailDuchev If you don't mind please recommend some source of learning. – Aditya Anand Jun 09 '20 at 11:31

1 Answers1

13

If you are looking for a example snippet, below is one:

import cv2
import imutils

# edged is the edge detected image
cnts = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
# loop over the contours
for c in cnts:
    # approximate the contour
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)
    # if our approximated contour has four points, then we
    # can assume that we have found our screen
    if len(approx) == 4:
        screenCnt = approx
        break

In the above snippet, first it finds the contours from a edge detected image, then it sorts the contours to find the five largest contours. Finally it loop over the contours and used cv2.approxPolyDP function to smooth and approximate the quadrilateral. cv2.approxPolyDP works for the cases where there are sharp edges in the contours like a document boundary.

amras
  • 1,499
  • 2
  • 6
  • 10
  • Thank You. and how cv2.arcLength() works. I know definition.Wanted to know why it is being used and how it works(I saw on internet but didn't get it). – Aditya Anand Jun 09 '20 at 03:40
  • 4
    ```cv2.arcLength()``` is used to calculate the perimeter of the contour. If the second argument is ```True``` then it considers the contour to be closed. Then this perimeter is used to calculate the epsilon value for ```cv2.approxPolyDP()``` function with a precision factor for approximating a shape. You can look into the link: https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_contours/py_contour_features/py_contour_features.html where it is explained. There is also a link to the wiki for Douglas-Peucker algorithm behind cv2.approxPolyDP() method. – amras Jun 09 '20 at 04:11