Python OpenCV – Find center of contour
Prerequisite: How to Detect Shapes in Images in Python using OpenCV?
In this article, we will learn how to find centers of contours using OpenCV in python. We will be using the findContours() and moments() functions.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
We will be using the following image for center point detection:
Step 1: Import the required module.
Step 2: Threshold of the image.
Before we go for contour detection, we have to threshold the above image which we can do using the following snippet:
The thresholding and the blur parameters can be changed and we would recommend you try tweaking with them to see how many contours are being detected with the given parameters.
You can save the threshold output using :
This is how it should look like:
We will find contours from the thresholded image using the findContours() method which returns two values, a list of all contours and their hierarchies. Now, what are contours? In simple words, a contour is a list or tree of lists of points. These points describe how a contour, that is, a vector that could be drawn as an outline around the parts of the shape based on a difference from a background. The hierarchy on the other hand shows how the shapes relate to each other, layers as such or if shapes are on top of each other. This can be determined using hierarchies.
Step 3: Now to find the contours and the hierarchies in the thresholded image we can use the findContours() method like shown below:
For simplicity and to understand how contours work and to check how many contours we can find in a thresholded image we can draw them on a blank image matrix using the following snippet:
this is how the image should look like:
Step 4: File all the center points and draw them on the image.
Now for finding out the center points we will be using the moments() method. Here we will use it to find the image moment for a particular contour. An image moment is a particular weighted average of image pixel intensities, with the help of which we can find some specific properties of an image for example radius, area, centroid, etc.
To find the centroid of the image, we use the particular formula:
cx = (M10 / M00 )
cy = ( M01 / M00 )
where cx and cy are the x and y coordinates of the center point and M is the moment
The following snippet finds all the center points and draws them on the image.
Step 5: Finally, we can save the image using :
This is what the final image would look like: