Drawing Functions
Drawing functions work with matrices/images of arbitrary depth.
The boundaries of the shapes can be rendered with antialiasing (implemented only for 8-bit images for now).
All the functions include the parameter color
that uses an RGB value (that may be constructed
with CV_RGB
or the :ocv:class:`Scalar_` constructor
) for color
images and brightness for grayscale images. For color images, the channel ordering
is normally Blue, Green, Red.
This is what :ocv:func:`imshow`, :ocv:func:`imread`, and :ocv:func:`imwrite` expect.
So, if you form a color using the
Scalar
constructor, it should look like:
\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])
If you are using your own image rendering and I/O functions, you can use any channel ordering. The drawing functions process each channel independently and do not depend on the channel order or even on the used color space. The whole image can be converted from BGR to RGB or to a different color space using :ocv:func:`cvtColor` .
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means that the coordinates can be passed as fixed-point numbers encoded as integers. The number of fractional bits is specified by the shift
parameter and the real point coordinates are calculated as
\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})
. This feature is especially effective when rendering antialiased shapes.
Note
The functions do not support alpha-transparency when the target image is 4-channel. In this case, the color[3]
is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
circle
Draws a circle.
The function circle
draws a simple or filled circle with a given center and radius.
clipLine
Clips the line against the image rectangle.
The functions clipLine
calculate a part of the line segment that is entirely within the specified rectangle.
They return false
if the line segment is completely outside the rectangle. Otherwise, they return true
.
ellipse
Draws a simple or thick elliptic arc or fills an ellipse sector.
The functions ellipse
with less parameters draw an ellipse outline, a filled ellipse, an elliptic arc, or a filled ellipse sector.
A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
:ocv:func:`ellipse2Poly` and then render it with
:ocv:func:`polylines` or fill it with
:ocv:func:`fillPoly` . If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass startAngle=0
and endAngle=360
. The figure below explains the meaning of the parameters.
Figure 1. Parameters of Elliptic Arc

ellipse2Poly
Approximates an elliptic arc with a polyline.
The function ellipse2Poly
computes the vertices of a polyline that approximates the specified elliptic arc. It is used by
:ocv:func:`ellipse` .
fillConvexPoly
Fills a convex polygon.
The function fillConvexPoly
draws a filled convex polygon.
This function is much faster than the function fillPoly
. It can fill not only convex polygons but any monotonic polygon without self-intersections,
that is, a polygon whose contour intersects every horizontal line (scan line) twice at the most (though, its top-most and/or the bottom edge could be horizontal).
fillPoly
Fills the area bounded by one or more polygons.
The function fillPoly
fills an area bounded by several polygonal contours. The function can fill complex areas, for example,
areas with holes, contours with self-intersections (some of their parts), and so forth.
getTextSize
Calculates the width and height of a text string.
The function getTextSize
calculates and returns the size of a box that contains the specified text.
That is, the following code renders some text, the tight box surrounding it, and the baseline:
// Use "y" to show that the baseLine is about
string text = "Funny text inside the box";
int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
double fontScale = 2;
int thickness = 3;
Mat img(600, 800, CV_8UC3, Scalar::all(0));
int baseline=0;
Size textSize = getTextSize(text, fontFace,
fontScale, thickness, &baseline);
baseline += thickness;
// center the text
Point textOrg((img.cols - textSize.width)/2,
(img.rows + textSize.height)/2);
// draw the box
rectangle(img, textOrg + Point(0, baseline),
textOrg + Point(textSize.width, -textSize.height),
Scalar(0,0,255));
// ... and the baseline first
line(img, textOrg + Point(0, thickness),
textOrg + Point(textSize.width, thickness),
Scalar(0, 0, 255));
// then put the text itself
putText(img, text, textOrg, fontFace, fontScale,
Scalar::all(255), thickness, 8);
InitFont
Initializes font structure (OpenCV 1.x API).
The function initializes the font structure that can be passed to text rendering functions.
line
Draws a line segment connecting two points.
The function line
draws the line segment between pt1
and pt2
points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings.
Antialiased lines are drawn using Gaussian filtering. To specify the line color, you may use the macro CV_RGB(r, g, b)
.
LineIterator
Class for iterating pixels on a raster line.
class LineIterator
{
public:
// creates iterators for the line connecting pt1 and pt2
// the line will be clipped on the image boundaries
// the line is 8-connected or 4-connected
// If leftToRight=true, then the iteration is always done
// from the left-most point to the right most,
// not to depend on the ordering of pt1 and pt2 parameters
LineIterator(const Mat& img, Point pt1, Point pt2,
int connectivity=8, bool leftToRight=false);
// returns pointer to the current line pixel
uchar* operator *();
// move the iterator to the next pixel
LineIterator& operator ++();
LineIterator operator ++(int);
// internal state of the iterator
uchar* ptr;
int err, count;
int minusDelta, plusDelta;
int minusStep, plusStep;
};
The class LineIterator
is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line or draw a line with an effect (for example, with XOR operation).
The number of pixels along the line is stored in LineIterator::count
.
// grabs pixels along the line (pt1, pt2)
// from 8-bit 3-channel image to the buffer
LineIterator it(img, pt1, pt2, 8);
vector<Vec3b> buf(it.count);
for(int i = 0; i < it.count; i++, ++it)
buf[i] = *(const Vec3b)*it;
rectangle
Draws a simple, thick, or filled up-right rectangle.
The function rectangle
draws a rectangle outline or a filled rectangle whose two opposite corners are pt1
and pt2
, or r.tl()
and r.br()-Point(1,1)
.
polylines
Draws several polygonal curves.
The function polylines
draws one or more polygonal curves.
drawContours
Draws contours outlines or filled contours.
The function draws contour outlines in the image if \texttt{thickness} \ge 0 or fills the area bounded by the contours if \texttt{thickness}<0 . The example below shows how to retrieve connected components from the binary image and label them:
#include "cv.h"
#include "highgui.h"
using namespace cv;
int main( int argc, char** argv )
{
Mat src;
// the first command-line parameter must be a filename of the binary
// (black-n-white) image
if( argc != 2 || !(src=imread(argv[1], 0)).data)
return -1;
Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3);
src = src > 1;
namedWindow( "Source", 1 );
imshow( "Source", src );
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( src, contours, hierarchy,
CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE );
// iterate through all the top-level contours,
// draw each connected component with its own random color
int idx = 0;
for( ; idx >= 0; idx = hierarchy[idx][0] )
{
Scalar color( rand()&255, rand()&255, rand()&255 );
drawContours( dst, contours, idx, color, CV_FILLED, 8, hierarchy );
}
namedWindow( "Components", 1 );
imshow( "Components", dst );
waitKey(0);
}
putText
Draws a text string.
The function putText
renders the specified text string in the image.
Symbols that cannot be rendered using the specified font are
replaced by question marks. See
:ocv:func:`getTextSize` for a text rendering code example.