How to Use cv2.polylines in Python

In this tutorial, you will learn how to draw shapes in Python using cv2.polylines() function of the cv2 module of the OpenCV library.

Installing Required Libraries

To complete this tutorial, you need to install OpenCV library on your system. We assume that you have an idea about how libraries are installed. You can use the following command for installing the required libraries.

 pip install opencv-python 

Python Code To Draw Shapes

Polylines function is used for drawing a different kind of shapes like triangle, rectangle etc on the screen. In this tutorial, we will draw very simple polygons.

First, we import our libraries. By the help of array() method draw an image of size 512*512 of order 3.  Again using the array() method to create array of the shape type int32. In this tutorial, we created two arrays one for a rectangle and another one for a triangle.

Remember that pass the coordinates in clockwise or anticlockwise otherwise, you will get some different shapes. This is because when you pass the set of first coordinates and second coordinates. It will draw a line between these two points. One other thing you should have to remember that points start drawn from the left-topmost position.  

import numpy as np
import cv2

img = np.zeros((512, 512,3), dtype = "uint8")

rectangle = np.array([[10,5],[10,225],[50,225],[50,5]], np.int32)
triangle = np.array([[60,10],[60,200],[150,100]], np.int32)

After the shapes array, we have to show our shapes on the image we already created using polylines() method of cv2 module. To draw shapes using polylines() method we have to pass five arguments are our blank image, coordinates of shape, True( true if you want closed shape otherwise, false for open from the first set of coordinates to last one), the color of shape(in RGB format) and the thickness of the shape.

In the last, we have to show our shapes on-screen using imshow() method by passing two arguments are name and our image.

rectangleImage =cv2.polylines(img, [rectangle], False, (0,255,0), thickness=3)
triangleImage =cv2.polylines(img, [triangle], False, (0,0,255), thickness=3)
cv2.imshow('Shapes', rectangleImage)
cv2.imshow('Shapes', triangleImage)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output :

How to Use cv2.polylines in Python

Also read: cv2.erode() function in OpenCV – Python

Leave a Reply

Your email address will not be published. Required fields are marked *