OpenCV  4.10.0-dev
Open Source Computer Vision
No Matches
Creating Bounding boxes and circles for contours

Table of Contents

Prev Tutorial: Convex Hull
Next Tutorial: Creating Bounding rotated boxes and ellipses for contours

Original author Ana Huamán
Compatibility OpenCV >= 3.0


In this tutorial you will learn how to:




The main function is rather simple, as follows from the comments we do the following:

  • Open the image, convert it into grayscale and blur it to get rid of the noise.
  • Create a window with header "Source" and display the source file in it.
  • Create a trackbar on the source_window and assign a callback function to it. In general callback functions are used to react to some kind of signal, in our case it's trackbar's state change. Explicit one-time call of thresh_callback is necessary to display the "Contours" window simultaneously with the "Source" window.

The callback function does all the interesting job.

  • Use cv::Canny to detect edges in the images.
  • Finds contours and saves them to the vectors contour and hierarchy.
  • For every found contour we now apply approximation to polygons with accuracy +-3 and stating that the curve must be closed. After that we find a bounding rect for every polygon and save it to boundRect. At last we find a minimum enclosing circle for every polygon and save it to center and radius vectors.

We found everything we need, all we have to do is to draw.

  • Create new Mat of unsigned 8-bit chars, filled with zeros. It will contain all the drawings we are going to make (rects and circles).
  • For every contour: pick a random color, draw the contour, the bounding rectangle and the minimal enclosing circle with it.
  • Display the results: create a new window "Contours" and show everything we added to drawings on it.


Here it is: