
Basic shapes – lines, rectangles, and circles
In the next example, we are going to see how to draw basic shapes in OpenCV. These basic shapes include lines, rectangles, and circles, which are the most common and simple shapes to draw. The first step is to create an image where the shapes will be drawn. To this end, a 400 400 image with the 3 channels (to properly display a BGR image) and a uint8 type (8-bit unsigned integers) will be created:
# We create the canvas to draw: 400 x 400 pixels, 3 channels, uint8 (8-bit unsigned integers)
# We set the background to black using np.zeros()
image = np.zeros((400, 400, 3), dtype="uint8")
We set the background to light gray using the colors dictionary:
# If you want another background color, you can do the following:
image[:] = colors['light_gray']
This canvas (or image) is shown in the next screenshot:

Now, we are ready to draw the basic shapes. It should be noted that most drawing functions that OpenCV provides have common parameters. For the sake of simplicity, these parameters are briefly introduced here:
- img: It is the image where the shape will be drawn.
- color: It is the color (BGR triplet) used to draw the shape.
- thickness: If this value is positive, it is the thickness of the shape outline. Otherwise, a filled shape will be drawn.
- lineType: It is the type of the shape boundary. OpenCV provides three types of line:
- cv2.LINE_4: This means four-connected lines
- cv2.LINE_8: This means eight-connected lines
- cv2.LINE_AA: This means an anti-aliased line
- shift: This indicates the number of fractional bits in connection with the coordinates of some points defining the shape.
In connection with the aforementioned parameters, the cv2.LINE_AA option for lineType produces a much better quality drawing (for example, when drawing text), but it is slower to draw. So, this consideration should be taken into account. Both the eight-connected and the four-connected lines, which are non-antialiased lines, are drawn with the Bresenham algorithm. For the anti-aliased line type, the Gaussian filtering algorithm is used. Additionally, the shift parameter is necessary because many drawing functions can't deal with sub-pixel accuracy. For simplicity in our examples, we are going to work with integer coordinates. Therefore, this value will be set to 0 (shift = 0). However to give you a complete understanding, an example of how to use the shift parameter will also be provided.