Title: OpenCV center of contour - PyImageSearch

URL Source: https://pyimagesearch.com/2016/02/01/opencv-center-of-contour/

Published Time: 2016-02-01T15:00:19+00:00

Markdown Content:
[![Image 1: center_of_contour_results](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20486'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/01/center_of_contour_results.gif)

Today, we are going to start a new 3-part series of tutorials on **_shape detection and analysis_**.

Throughout this series, we’ll learn how to:

1.  Compute the center of a contour/shape region.
2.  Recognize various shapes, such as circles, squares, rectangles, triangles, and pentagons using only contour properties.
3.  Label the color of a shape.

While today’s post is a bit basic (at least in context of some of the more advanced concepts on the PyImageSearch blog recently), it still addresses a question that I get asked a lot:

> **“How do I compute the center of a contour using Python and OpenCV?**

In today’s post, I’ll answer that question.

And in later posts in this series, we’ll build upon our knowledge of contours to recognize shapes in images.

![Image 2](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20128%20128'%3E%3C/svg%3E)

#### Looking for the source code to this post?

[Jump Right To The Downloads Section](#download-the-code)

[![Image 3: Figure 1: An example image containing a set of shapes that we are going to compute the center of the contour for.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20467'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/01/shapes_and_colors.jpg)

**Figure 1:** An example image containing a set of shapes that we are going to compute the center of the contour for.

In above image, you can see a variety of shapes cut out from pieces of construction paper. Notice how these shapes are not _perfect_. The rectangles aren’t quite rectangular — and the circles are not entirely circular either. These are _human drawn and human cut out shapes_, implying there is _variation_ in each shape type.

With this in mind, the goal of today’s tutorial is to (1) _detect the outline of each shape_ in the image, followed by (2) _computing the center of the contour_ — also called the _centroid_ of the region.

In order to accomplish these goals, we’ll need to perform a bit of image pre-processing, including:

*   Conversion to grayscale.
*   Blurring to reduce high frequency noise to make our contour detection process more accurate.
*   Binarization of the image. Typically edge detection and thresholding are used for this process. In this post, we’ll be applying thresholding.

Before we start coding, make sure you have the [imutils Python package](https://github.com/jrosebr1/imutils) installed on your system:

$ pip install --upgrade imutils

From there, we can go ahead and get started.

Open up a new file, name it `center_of_shape.py` , and we’ll get coding:

\# import the necessary packages
import argparse
import imutils
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add\_argument("-i", "--image", required=True,
	help="path to the input image")
args = vars(ap.parse\_args())

# load the image, convert it to grayscale, blur it slightly,
# and threshold it
image = cv2.imread(args\["image"\])
gray = cv2.cvtColor(image, cv2.COLOR\_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH\_BINARY)\[1\]

We start off on **Lines 2-4** by importing our necessary packages, followed by parsing our command line arguments. We only need a single switch here, `--image` , which is the path to where the image we want to process resides on disk.

We then take this image, load it from disk, and pre-process it by applying grayscale conversion, Gaussian smoothing using a _5 x 5_ kernel, and finally thresholding (**Lines 14-17**).

The output of the thresholding operation can be seen below:

[![Image 4: Figure 2: Thresholding our image returns a binary image, where the shapes appear as white on a black foreground.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20486'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/01/center_of_contour_thresh.jpg)

**Figure 2:** Thresholding our image returns a binary image, where the shapes appear as white on a black foreground.

Notice how after applying thresholding the shapes are represented as a _white foreground_ on a _black background_.

The next step is to find the location of these white regions using contour detection:

\# find contours in the thresholded image
cnts = cv2.findContours(thresh.copy(), cv2.RETR\_EXTERNAL,
	cv2.CHAIN\_APPROX\_SIMPLE)
cnts = imutils.grab\_contours(cnts)

A call to `cv2.findContours` on **Lines 20 and 21** returns the set of outlines (i.e., contours) that correspond to each of the white blobs on the image. **Line 22** then grabs the appropriate tuple value based on whether we are using OpenCV 2.4, 3, or 4. You can read more about how the return signature of `cv2.findContours` changed between OpenCV versions [in this post](https://pyimagesearch.com/2015/08/10/checking-your-opencv-version-using-python/).

We are now ready to process each of the contours:

\# loop over the contours
for c in cnts:
	# compute the center of the contour
	M = cv2.moments(c)
	cX = int(M\["m10"\] / M\["m00"\])
	cY = int(M\["m01"\] / M\["m00"\])

	# draw the contour and center of the shape on the image
	cv2.drawContours(image, \[c\], -1, (0, 255, 0), 2)
	cv2.circle(image, (cX, cY), 7, (255, 255, 255), -1)
	cv2.putText(image, "center", (cX - 20, cY - 20),
		cv2.FONT\_HERSHEY\_SIMPLEX, 0.5, (255, 255, 255), 2)

	# show the image
	cv2.imshow("Image", image)
	cv2.waitKey(0)

On **Line 25** we start looping over each of the individual contours, followed by computing [image moments](https://en.wikipedia.org/wiki/Image_moment) for the contour region on **Line 27**.

In computer vision and image processing, image moments are often used to characterize the shape of an object in an image. These moments capture basic statistical properties of the shape, including the _area_ of the object, the _centroid_ (i.e., the center _(x, y)_\-coordinates of the object), _orientation_, along with other desirable properties.

Here we are only interested in the _center of the contour_, which we compute on **Lines 28 and 29**.

From there, **Lines 32-34** handle:

*   Drawing the outline of the contour surrounding the current shape by making a call to `cv2.drawContours` .
*   Placing a white circle at the _**center**_ `(cX, cY)` -coordinates of the shape.
*   Writing the text `center` near the white circle.

To execute our script, just open up a terminal and execute the following command:

$ python center\_of\_shape.py --image shapes\_and\_colors.png

Your results should look something like this:

[![Image 5: Figure 3: Looping over each of the shapes individually and then computing the center (x, y)-coordinates for each shape.](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20500%20486'%3E%3C/svg%3E)](https://pyimagesearch.com/wp-content/uploads/2016/01/center_of_contour_results.gif)

**Figure 3:** Looping over each of the shapes individually and then computing the center (x, y)-coordinates for each shape.

Notice how each of the shapes are successfully detected, followed by the center of the contour being computed and drawn on the image.

### What's next? We recommend [PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend).

**Course information:**  
84 total classes • 114+ hours of on-demand code walkthrough videos • Last updated: February 2024  
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

**I strongly believe that if you had the right teacher you could _master_ computer vision and deep learning.**

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s _not_ the case.

All you need to master computer vision and deep learning is for someone to explain things to you in _simple, intuitive_ terms. _And that’s exactly what I do_. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to _successfully_ and _confidently_ apply computer vision to your work, research, and projects. Join me in computer vision mastery.

**Inside PyImageSearch University you'll find:**

*   ✓ **84 courses** on essential computer vision, deep learning, and OpenCV topics
*   ✓ **84 Certificates** of Completion
*   ✓ **114+ hours** of on-demand video
*   ✓ **Brand new courses released _regularly_**, ensuring you can keep up with state-of-the-art techniques
*   ✓ **Pre-configured Jupyter Notebooks in Google Colab**
*   ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
*   ✓ Access to **centralized code repos for _all_ 536+ tutorials** on PyImageSearch
*   ✓ **Easy one-click downloads** for code, datasets, pre-trained models, etc.
*   ✓ **Access** on mobile, laptop, desktop, etc.

[Click here to join PyImageSearch University](https://pyimagesearch.com/pyimagesearch-university/?utm_source=blogPost&utm_medium=bottomBanner&utm_campaign=What%27s%20next%3F%20I%20recommend)

Summary
-------

In this lesson, we learned how to compute the center of a contour using OpenCV and Python.

This post is the _first_ in a _three part series_ on **shape analysis**.

In next week’s post, we’ll learn how to _**identify shapes**_ in an image.

Then, two weeks from now, we’ll learn how to _**analyze the color of each shape**_ and **_label the shape with a specific color_** (i.e., “red”, “green”, “blue”, etc.).

To be notified when these posts go live, **be sure to enter your email address using the form below!**

![Image 6](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20410%20567'%3E%3C/svg%3E)

#### Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a **FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning.** Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!