Drawing Things

Something that frequently occurs is the need to draw some kind of picture or to draw something on top of an image obtained from somewhere else. Toward this end, OpenCV provides a menagerie of functions that will allow us to make lines, squares, circles, and the like.

Lines

The simplest of these routines just draws a line by the Bresenham algorithm [Bresenham65]:

void  cvLine(
  CvArr*   array,
  CvPoint  pt1,
  CvPoint  pt2,
  CvScalar color,
  int      thickness    = 1,
  int      connectivity = 8
);

The first argument to cvLine() is the usual CvArr*, which in this context typically means an IplImage* image pointer. The next two arguments are CvPoints. As a quick reminder, CvPoint is a simple structure containing only the integer members x and y. We can create a CvPoint "on the fly" with the routine cvPoint(int x, int y), which conveniently packs the two integers into a CvPoint structure for us.

The next argument, color, is of type CvScalar. CvScalars are also structures, which (you may recall) are defined as follows:

typdef struct {
  double val[4];
} CvScalar;

As you can see, this structure is just a collection of four doubles. In this case, the first three represent the red, green, and blue channels; the fourth is not used (it can be used for an alpha channel when appropriate). One typically makes use of the handy macro CV_RGB(r, g, b). This macro takes three numbers and packs them up into a CvScalar.

The next two arguments are optional. The thickness is the thickness of the line (in pixels), and

Get Learning OpenCV now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.