Merge pull request #31288 from visweshdev/codex/python-drawing-tutorial-5x

Add Python examples to the 5.x random drawing tutorial
This commit is contained in:
Abhishek Gola
2026-12-01 18:47:31 +05:30
committed by GitHub
3 changed files with 75 additions and 191 deletions

View File

@@ -14,223 +14,91 @@ Random generator and text with OpenCV {#tutorial_random_generator_and_text}
Goals
-----
In this tutorial you will learn how to:
- Use the *Random Number generator class* (@ref cv::RNG ) and how to get a random number from a
uniform distribution.
- Display text on an OpenCV window by using the function @ref cv::putText
- Use @ref cv::RNG in C++ or NumPy's random number generator in Python to choose drawing parameters.
- Draw text on an image with @ref cv::putText.
Code
----
- In the previous tutorial (@ref tutorial_basic_geometric_drawing) we drew diverse geometric figures, giving as input
parameters such as coordinates (in the form of @ref cv::Point), color, thickness, etc. You
might have noticed that we gave specific values for these arguments.
- In this tutorial, we intend to use *random* values for the drawing parameters. Also, we intend
to populate our image with a big number of geometric figures. Since we will be initializing them
in a random fashion, this process will be automatic and made by using *loops* .
- This code is in your OpenCV sample folder. Otherwise you can grab it from
[here](https://github.com/opencv/opencv/blob/5.x/samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp)
The previous tutorial used fixed positions and colors for geometric shapes. These samples generate
positions, colors, and other drawing parameters in loops to fill the image with shapes and text.
@add_toggle_cpp
[Download the C++ sample](https://raw.githubusercontent.com/opencv/opencv/5.x/samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp).
@include samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp
@end_toggle
@add_toggle_python
[Download the Python sample](https://raw.githubusercontent.com/opencv/opencv/5.x/samples/python/drawing.py).
Run it with `python drawing.py`.
@include samples/python/drawing.py
@end_toggle
Explanation
-----------
-# Let's start by checking out the *main* function. We observe that first thing we do is creating a
*Random Number Generator* object (RNG):
@code{.cpp}
RNG rng( 0xFFFFFFFF );
@endcode
RNG implements a random number generator. In this example, *rng* is a RNG element initialized
with the value *0xFFFFFFFF*
### Create a canvas
-# Then we create a matrix initialized to *zeros* (which means that it will appear as black),
specifying its height, width and its type:
@code{.cpp}
/// Initialize a matrix filled with zeros
Mat image = Mat::zeros( window_height, window_width, CV_8UC3 );
Each sample starts with a black, three-channel image and displays it in a window.
/// Show it in a window during DELAY ms
imshow( window_name, image );
@endcode
-# Then we proceed to draw crazy stuff. After taking a look at the code, you can see that it is
mainly divided in 8 sections, defined as functions:
@code{.cpp}
/// Now, let's draw some lines
c = Drawing_Random_Lines(image, window_name, rng);
if( c != 0 ) return 0;
@add_toggle_cpp
The C++ sample seeds a @ref cv::RNG with a fixed value.
@snippet cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp setup
@end_toggle
/// Go on drawing, this time nice rectangles
c = Drawing_Random_Rectangles(image, window_name, rng);
if( c != 0 ) return 0;
@add_toggle_python
The Python sample creates the canvas with `numpy.zeros`, using `uint8` for the channel values.
@snippet python/drawing.py setup
@end_toggle
/// Draw some ellipses
c = Drawing_Random_Ellipses( image, window_name, rng );
if( c != 0 ) return 0;
### Draw random lines
/// Now some polylines
c = Drawing_Random_Polylines( image, window_name, rng );
if( c != 0 ) return 0;
Each iteration chooses two endpoints and a thickness. The integer generators take an inclusive
lower bound and an exclusive upper bound. Colors use three channel values in BGR order. The same
approach applies to the center of a circle or the vertices of a polygon. After each draw, the
sample displays the updated image and checks for a key press.
/// Draw filled polygons
c = Drawing_Random_Filled_Polygons( image, window_name, rng );
if( c != 0 ) return 0;
@add_toggle_cpp
@snippet cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp lines
@end_toggle
/// Draw circles
c = Drawing_Random_Circles( image, window_name, rng );
if( c != 0 ) return 0;
@add_toggle_python
The Python sample uses `numpy.random.randint` and chooses between `cv.line` and `cv.arrowedLine`.
@snippet python/drawing.py lines
@end_toggle
/// Display text in random positions
c = Displaying_Random_Text( image, window_name, rng );
if( c != 0 ) return 0;
### Draw random text
/// Displaying the big end!
c = Displaying_Big_End( image, window_name, rng );
@endcode
All of these functions follow the same pattern, so we will analyze only a couple of them, since
the same explanation applies for all.
@ref cv::putText draws a string at the chosen position. The origin is the bottom-left corner of the
text. Each iteration also chooses a font, scale, color, and thickness.
-# Checking out the function **Drawing_Random_Lines**:
@code{.cpp}
int Drawing_Random_Lines( Mat image, char* window_name, RNG rng )
{
int lineType = 8;
Point pt1, pt2;
@add_toggle_cpp
@snippet cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp random_text
@end_toggle
for( int i = 0; i < NUMBER; i++ )
{
pt1.x = rng.uniform( x_1, x_2 );
pt1.y = rng.uniform( y_1, y_2 );
pt2.x = rng.uniform( x_1, x_2 );
pt2.y = rng.uniform( y_1, y_2 );
@add_toggle_python
@snippet python/drawing.py random_text
@end_toggle
line( image, pt1, pt2, randomColor(rng), rng.uniform(1, 10), 8 );
imshow( window_name, image );
if( waitKey( DELAY ) >= 0 )
{ return -1; }
}
return 0;
}
@endcode
We can observe the following:
### Draw the final message
- The *for* loop will repeat **NUMBER** times. Since the function @ref cv::line is inside this
loop, that means that **NUMBER** lines will be generated.
- The line extremes are given by *pt1* and *pt2*. For *pt1* we can see that:
@code{.cpp}
pt1.x = rng.uniform( x_1, x_2 );
pt1.y = rng.uniform( y_1, y_2 );
@endcode
- We know that **rng** is a *Random number generator* object. In the code above we are
calling **rng.uniform(a,b)**. This generates a randomly uniformed distribution between
the values **a** and **b** (inclusive in **a**, exclusive in **b**).
- From the explanation above, we deduce that the extremes *pt1* and *pt2* will be random
values, so the lines positions will be quite impredictable, giving a nice visual effect
(check out the Result section below).
- As another observation, we notice that in the @ref cv::line arguments, for the *color*
input we enter:
@code{.cpp}
randomColor(rng)
@endcode
Let's check the function implementation:
@code{.cpp}
static Scalar randomColor( RNG& rng )
{
int icolor = (unsigned) rng;
return Scalar( icolor&255, (icolor>>8)&255, (icolor>>16)&255 );
}
@endcode
As we can see, the return value is an *Scalar* with 3 randomly initialized values, which
are used as the *R*, *G* and *B* parameters for the line color. Hence, the color of the
lines will be random too!
@ref cv::getTextSize measures the text before drawing so the sample can position the message near
the center of the image. Each frame subtracts the same value from all three color channels,
clamping them at zero so the background fades toward black.
-# The explanation above applies for the other functions generating circles, ellipses, polygons,
etc. The parameters such as *center* and *vertices* are also generated randomly.
-# Before finishing, we also should take a look at the functions *Display_Random_Text* and
*Displaying_Big_End*, since they both have a few interesting features:
-# **Display_Random_Text:**
@code{.cpp}
int Displaying_Random_Text( Mat image, char* window_name, RNG rng )
{
int lineType = 8;
@add_toggle_cpp
@snippet cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp final_text
@end_toggle
for ( int i = 1; i < NUMBER; i++ )
{
Point org;
org.x = rng.uniform(x_1, x_2);
org.y = rng.uniform(y_1, y_2);
putText( image, "Testing text rendering", org, rng.uniform(0,8),
rng.uniform(0,100)*0.05+0.1, randomColor(rng), rng.uniform(1, 10), lineType);
imshow( window_name, image );
if( waitKey(DELAY) >= 0 )
{ return -1; }
}
return 0;
}
@endcode
Everything looks familiar but the expression:
@code{.cpp}
putText( image, "Testing text rendering", org, rng.uniform(0,8),
rng.uniform(0,100)*0.05+0.1, randomColor(rng), rng.uniform(1, 10), lineType);
@endcode
So, what does the function @ref cv::putText do? In our example:
- Draws the text **"Testing text rendering"** in **image**
- The bottom-left corner of the text will be located in the Point **org**
- The font type is a random integer value in the range: \f$[0, 8>\f$.
- The scale of the font is denoted by the expression **rng.uniform(0, 100)x0.05 + 0.1**
(meaning its range is: \f$[0.1, 5.1>\f$)
- The text color is random (denoted by **randomColor(rng)**)
- The text thickness ranges between 1 and 10, as specified by **rng.uniform(1,10)**
As a result, we will get (analagously to the other drawing functions) **NUMBER** texts over our
image, in random locations.
-# **Displaying_Big_End**
@code{.cpp}
int Displaying_Big_End( Mat image, char* window_name, RNG rng )
{
Size textsize = getTextSize("OpenCV forever!", FONT_HERSHEY_COMPLEX, 3, 5, 0);
Point org((window_width - textsize.width)/2, (window_height - textsize.height)/2);
int lineType = 8;
Mat image2;
for( int i = 0; i < 255; i += 2 )
{
image2 = image - Scalar::all(i);
putText( image2, "OpenCV forever!", org, FONT_HERSHEY_COMPLEX, 3,
Scalar(i, i, 255), 5, lineType );
imshow( window_name, image2 );
if( waitKey(DELAY) >= 0 )
{ return -1; }
}
return 0;
}
@endcode
Besides the function **getTextSize** (which gets the size of the argument text), the new
operation we can observe is inside the *foor* loop:
@code{.cpp}
image2 = image - Scalar::all(i)
@endcode
So, **image2** is the subtraction of **image** and **Scalar::all(i)**. In fact, what happens
here is that every pixel of **image2** will be the result of subtracting every pixel of
**image** minus the value of **i** (remember that for each pixel we are considering three values
such as R, G and B, so each of them will be affected)
Also remember that the subtraction operation *always* performs internally a **saturate**
operation, which means that the result obtained will always be inside the allowed range (no
negative and between 0 and 255 for our example).
@add_toggle_python
@snippet python/drawing.py final_text
@end_toggle
Result
------
As you just saw in the Code section, the program will sequentially execute diverse drawing
functions, which will produce:
The C++ sample produces the following sequence. The Python sample draws a similar sequence with
arrows and markers among its shapes.
-# First a random set of *NUMBER* lines will appear on screen such as it can be seen in this
screenshot:

View File

@@ -44,6 +44,7 @@ int main( void )
/// Start creating a window
char window_name[] = "Drawing_2 Tutorial";
//! [setup]
/// Also create a random object (RNG)
RNG rng( 0xFFFFFFFF );
@@ -52,6 +53,7 @@ int main( void )
/// Show it in a window during DELAY ms
imshow( window_name, image );
waitKey( DELAY );
//! [setup]
/// Now, let's draw some lines
c = Drawing_Random_Lines(image, window_name, rng);
@@ -105,6 +107,7 @@ static Scalar randomColor( RNG& rng )
/**
* @function Drawing_Random_Lines
*/
//! [lines]
int Drawing_Random_Lines( Mat image, char* window_name, RNG rng )
{
Point pt1, pt2;
@@ -124,6 +127,7 @@ int Drawing_Random_Lines( Mat image, char* window_name, RNG rng )
return 0;
}
//! [lines]
/**
* @function Drawing_Rectangles
@@ -279,6 +283,7 @@ int Drawing_Random_Circles( Mat image, char* window_name, RNG rng )
/**
* @function Displaying_Random_Text
*/
//! [random_text]
int Displaying_Random_Text( Mat image, char* window_name, RNG rng )
{
int lineType = 8;
@@ -299,10 +304,12 @@ int Displaying_Random_Text( Mat image, char* window_name, RNG rng )
return 0;
}
//! [random_text]
/**
* @function Displaying_Big_End
*/
//! [final_text]
int Displaying_Big_End( Mat image, char* window_name, RNG )
{
Size textsize = getTextSize("OpenCV forever!", FONT_HERSHEY_COMPLEX, 3, 5, 0);
@@ -324,3 +331,4 @@ int Displaying_Big_End( Mat image, char* window_name, RNG )
return 0;
}
//! [final_text]

View File

@@ -13,6 +13,7 @@ import numpy as np
import cv2 as cv
# Drawing Lines
# [lines]
def lines():
for i in range(NUMBER*2):
pt1, pt2 = [], []
@@ -30,6 +31,7 @@ def lines():
cv.imshow(wndname, image)
if cv.waitKey(DELAY)>=0:
return
# [lines]
# Drawing Rectangle
def rectangle():
@@ -145,6 +147,7 @@ def circles():
return
# Draws a text string
# [random_text]
def string():
for i in range(NUMBER):
org = []
@@ -156,17 +159,20 @@ def string():
cv.imshow(wndname, image)
if cv.waitKey(DELAY) >= 0:
return
# [random_text]
# [final_text]
def string1():
textsize = cv.getTextSize("OpenCV forever!", cv.FONT_HERSHEY_COMPLEX, 3, 5)
org = (int((width - textsize[0][0])/2), int((height - textsize[0][1])/2))
for i in range(0, 255, 2):
image2 = np.array(image) - i
image2 = cv.subtract(image, (i, i, i, 0))
cv.putText(image2, "OpenCV forever!", org, cv.FONT_HERSHEY_COMPLEX, 3, (i, i, 255), 5, lineType)
cv.imshow(wndname, image2)
if cv.waitKey(DELAY) >= 0:
return
# [final_text]
if __name__ == '__main__':
print(__doc__)
@@ -176,9 +182,11 @@ if __name__ == '__main__':
width, height = 1000, 700
lineType = cv.LINE_AA # change it to LINE_8 to see non-antialiased graphics
x1, x2, y1, y2 = -width/2, width*3/2, -height/2, height*3/2
# [setup]
image = np.zeros((height, width, 3), dtype = np.uint8)
cv.imshow(wndname, image)
cv.waitKey(DELAY)
# [setup]
lines()
rectangle()
ellipse()