OpenCV  4.1.1-pre
Open Source Computer Vision
Looking for a C++ dev who knows OpenCV?
I'm looking for work. Hire me!
Creating Bounding boxes and circles for contours

Prev Tutorial: Convex Hull

Next Tutorial: Creating Bounding rotated boxes and ellipses for contours

Goal

In this tutorial you will learn how to:

Theory

Code

Explanation

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 simultaniously 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.

Result

Here it is:

Bounding_Rects_Circles_Source_Image.jpg
Bounding_Rects_Circles_Result.jpg