OpenCV  4.2.0
Open Source Computer Vision
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:

cv::String
std::string String
Definition: cvstd.hpp:150
cv::rectangle
void rectangle(InputOutputArray img, Rect rec, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
cv::Rect
Rect2i Rect
Definition: types.hpp:462
cv::cvtColor
void cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0)
Converts an image from one color space to another.
cv::samples::findFile
cv::String findFile(const cv::String &relative_path, bool required=true, bool silentMode=false)
Try to find requested data file.
cv::Mat::zeros
static MatExpr zeros(int rows, int cols, int type)
Returns a zero array of the specified size and type.
cv::minEnclosingCircle
void minEnclosingCircle(InputArray points, Point2f &center, float &radius)
Finds a circle of the minimum area enclosing a 2D point set.
cv::threshold
double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
Applies a fixed-level threshold to each array element.
cv::waitKey
int waitKey(int delay=0)
Waits for a pressed key.
cv::Canny
void Canny(InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false)
Finds edges in an image using the Canny algorithm .
cv::boundingRect
Rect boundingRect(InputArray array)
Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image.
highgui.hpp
cv::namedWindow
void namedWindow(const String &winname, int flags=WINDOW_AUTOSIZE)
Creates a window.
cv::Scalar_< double >
cv::findContours
void findContours(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset=Point())
Finds contours in a binary image.
cv::Size
Size2i Size
Definition: types.hpp:347
cv::rectangle
void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a simple, thick, or filled up-right rectangle.
cv::Canny
void Canny(InputArray dx, InputArray dy, OutputArray edges, double threshold1, double threshold2, bool L2gradient=false)
cv::imread
Mat imread(const String &filename, int flags=IMREAD_COLOR)
Loads an image from a file.
cv::Mat::empty
bool empty() const
Returns true if the array has no elements.
CV_8UC3
#define CV_8UC3
Definition: interface.h:90
cv::Mat::size
MatSize size
Definition: mat.hpp:2108
imgcodecs.hpp
cv::dnn::print
static void print(const MatShape &shape, const String &name="")
Definition: shape_utils.hpp:188
cv::findContours
void findContours(InputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset=Point())
cv::imshow
void imshow(const String &winname, InputArray mat)
Displays an image in the specified window.
cv::approxPolyDP
void approxPolyDP(InputArray curve, OutputArray approxCurve, double epsilon, bool closed)
Approximates a polygonal curve(s) with the specified precision.
cv::Scalar
Scalar_< double > Scalar
Definition: types.hpp:669
cv::RNG
Random Number Generator.
Definition: core.hpp:2768
cv::drawContours
void drawContours(InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar &color, int thickness=1, int lineType=LINE_8, InputArray hierarchy=noArray(), int maxLevel=INT_MAX, Point offset=Point())
Draws contours outlines or filled contours.
cv::blur
void blur(InputArray src, OutputArray dst, Size ksize, Point anchor=Point(-1,-1), int borderType=BORDER_DEFAULT)
Blurs an image using the normalized box filter.
cv::Point
Point2i Point
Definition: types.hpp:194
cv::Mat
n-dimensional dense array class
Definition: mat.hpp:791
cv::imshow
void imshow(const String &winname, const ogl::Texture2D &tex)
Displays OpenGL 2D texture in the specified window.
cv::CommandLineParser
Designed for command line parsing.
Definition: utility.hpp:796
cv::COLOR_BGR2GRAY
convert between RGB/BGR and grayscale, color conversions
Definition: imgproc.hpp:542
cv::createTrackbar
int createTrackbar(const String &trackbarname, const String &winname, int *value, int count, TrackbarCallback onChange=0, void *userdata=0)
Creates a trackbar and attaches it to the specified window.
cv
"black box" representation of the file storage associated with a file on disk.
Definition: affine.hpp:51
imgproc.hpp
cv::CHAIN_APPROX_SIMPLE
Definition: imgproc.hpp:434
cv::RETR_TREE
Definition: imgproc.hpp:422
cv::datasets::circle
Definition: gr_skig.hpp:62
cv::circle
void circle(InputOutputArray img, Point center, int radius, const Scalar &color, int thickness=1, int lineType=LINE_8, int shift=0)
Draws a circle.