How to Create a Convex Hull of Contours in an Image in Python using OpenCV



Python


In this article, we show how to create a convex hull of contours in an image in Python using the OpenCV module.

OpenCV has functions in which it can locate and get the size of contours in an image.

We can then take these contours and do things such as draw a convex hull around a contour.

A contour hull is an outline in which a contour is enveloped by having lines trace around the entire image.

In this code, we will use the following image shown below of a hand.

Hand

Once we draw a convex hull around this hand, OpenCV produces the following output.

Convex hull in Python using OpenCV

So you can see that a convex hull follows all the extreme endpoints of a contour and creates an envelope around it.

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, hull, that creates a convex hull starting at the first contour, which will then repeat for each other contour.

We draw contours enveloping the image in a green color with a thickness of 2.

We then display the image.

And this is how we can create a convex hull around a contour 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



HTML Comment Box is loading comments...