How to draw polylines on an image in OpenCV using Python?
OpenCV is a powerful library for computer vision, and it provides various functionalities to process and manipulate images. Drawing on an image is one of the most common tasks in image processing. In this tutorial, we will learn to draw polylines on an image in OpenCV using Python.
Prerequisites
Before getting started, make sure that you have installed OpenCV in your system. If not, you can install it by running the following command in your terminal.
pip install opencv-python
Once installed, you can import the cv2 module in your Python script.
import cv2
Syntax
The cv2.polylines() method is used to draw polylines on an image.
cv2.polylines(image, pts, isClosed, color, thickness)
- image: The image on which we want to draw the polyline.
- pts: The points through which we want to draw the polyline.
- isClosed: A Boolean value that indicates whether the polyline should be closed or not. A closed polyline forms a polygon.
- color: The color of the polyline.
- thickness: The thickness of the polyline.
Example
Let’s create a simple example to demonstrate how to draw polylines on an image.
import cv2
import numpy as np
# Create a black image
img = np.zeros((512,512,3), np.uint8)
# Define the points
pts = np.array([[10,10],[100,100],[200,50],[300,300],[400,200]], np.int32)
# Draw the polyline
cv2.polylines(img,[pts],True,(0,255,255),5)
# Display the image
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this example, we first create a black image of size 512×512. Next, we define the points through which we want to draw the polyline using a NumPy array. We then use the cv2.polylines() method to draw the polyline on the image. Finally, we display the image using the cv2.imshow() method.
The color of the polyline is (0,255,255) which is yellow, and the thickness is 5.
Conclusion
In this tutorial, we learned how to draw polylines on an image in OpenCV using Python. Drawing on an image is a crucial part of image processing and OpenCV provides various methods to accomplish this task. By using cv2.polylines() method, we can easily draw polylines on an image.