How to Approximate Contours in an Image in Python using OpenCV
In this article, we show how to approximate contours in an image in Python using the OpenCV module.
OpenCV has functions that can locate and approximate contours in an image.
OpenCV has a function, cv2.approxPolyDP(), that allows us to approximate contours in an image.
Approximating contours allows us to straighten out various contours to make them curvy or messy. Lines that aren't straight may be straightened. Things of that sort occur with approximation. It is very good when an image has outside noise or jagged edges that are better straightened.
In this code, we will use the following image shown below of a crudely-built house.
Once we do approximation on this image, OpenCV produces the following output.
So you can see that contours are approximated in the image.
Let's go over the code now.
Let's now go over this code.
First, we import OpenCV using the line, import cv2
Next, we read in the image, which in this case is, Shapes.png
We create an original image because we modify our image throughout the code.
We then create a grayscale of the image and then the image with Canny edges.
We then get the contours of an image through the cv2.findContours() function. We are only concerned with the external contours of the image, as we are looking for the individual objects of our image and not the internal contours within an object.
We then have a for loop in which we go through each of the contours in the image.
We create a variable, accuracy, that wet set equal to 0.03 * cv2.arcLength(c,True). You can adjust this value a little, but this value works well in this case.
We then create another variable, approx, which we set equal to the approxPolyDP() function, which uses the accuracy we set previously on the contour.
We then draw the contours based on the approx variable with a green color with a line thickness of 2.
We then show the image.
And this is how we can approximate contours in an image in Python
using OpenCV.
Related Resources
How to Draw a Rectangle in Python using OpenCV
How to Draw a Circle in Python using OpenCV
How to Draw a Line in Python using OpenCV
How to Add Text to an Image in Python using OpenCV
How to Display an OpenCV image in Python with Matplotlib
How to Use Callback functions to Connect Images to Events in Python using OpenCV
How to Check for Multiple Events in Python using OpenCV