How to Draw Polygon in OpenCV Python

You can draw a polygon in OpenCV Python by following the given steps. I highly recommend you get the “Computer Vision: Models, Learning, and Inference Book” to learn Computer Vision.

How to Draw Polygon in OpenCV Python
How to Draw Polygon in OpenCV Python

Step 1

Import the OpenCV library. If OpenCV is not installed in your system then first install it using This Method.

import cv2 
#cv2 is used for OpenCV library

Step 2

Now read the image from the location. In my case “C:\\AiHints” is the location and “black2.jpg” is the name of the image. Change it according to your image location and name.

image = cv2.imread("C:\\AiHints\\black2.jpg")
#imread is use to read an image from a location

Step 3

In the following code, make a NumPy array having five points that will help to make a pentagon(5 lines, closed shape).

penta_points = np.array([[[50,150],[130,100],[190,150],[170,270],[90,250]]], np.int32)

Step 4

Now use the function polylines that will join all the points to make a pentagon. The first parameter is the image on which we want to make a pentagon, second is five points in the form of a NumPy array. The third parameter is for closed shape. The fourth parameter is the color combination i.e. green. The last parameter is the thickness of the boundary.

polygon = cv2.polylines(image, [penta_points], True, (0,255,0), 5)

Step 5

To display the image in a specified window use ”imshow” function.

cv2.imshow("Polygon",polygon)

Step 6

“waitKey(0)” will display a window until any key is pressed. “destroyAllWindows()” will destroy all the windows that we created.

cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Draw Polygon using OpenCV

Leave a Comment

Your email address will not be published.