Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Draw a filled polygon using the OpenCV function fillPoly()
In this tutorial, we will learn how to draw a filled polygon using OpenCV's fillPoly() function. This function fills a polygon defined by a set of vertices with a specified color.
Syntax
cv2.fillPoly(image, pts, color)
Parameters
The fillPoly() function accepts the following parameters ?
- image ? The input image on which to draw the polygon
- pts ? Array of polygon vertices (points)
- color ? Fill color of the polygon in BGR format
Algorithm
Step 1: Import cv2 and numpy Step 2: Define the polygon vertices (endpoints) Step 3: Create a blank image using zeros Step 4: Draw the filled polygon using fillPoly() Step 5: Display the result
Example
Let's create a filled rectangle using fillPoly() ?
import cv2
import numpy as np
# Define polygon vertices (rectangle)
vertices = np.array([[50,50], [50,150], [150,150], [150,50]])
# Create blank image (height=200, width=200, 3-channel for color)
image = np.zeros((200, 200, 3), dtype=np.uint8)
# Fill the polygon with white color
cv2.fillPoly(image, pts=[vertices], color=(255, 255, 255))
# Display the image
cv2.imshow("Filled Polygon", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Creating Complex Polygons
You can create more complex shapes by defining different vertices ?
import cv2
import numpy as np
# Create a blank image
image = np.zeros((300, 300, 3), dtype=np.uint8)
# Define triangle vertices
triangle = np.array([[150, 50], [100, 150], [200, 150]])
# Define pentagon vertices
pentagon = np.array([[150, 180], [120, 200], [130, 240], [170, 240], [180, 200]])
# Fill triangle with red color
cv2.fillPoly(image, [triangle], color=(0, 0, 255))
# Fill pentagon with green color
cv2.fillPoly(image, [pentagon], color=(0, 255, 0))
cv2.imshow("Multiple Polygons", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Key Points
- Vertices must be defined as NumPy arrays
- Use 3-channel images (height, width, 3) for colored polygons
- Colors are specified in BGR format (Blue, Green, Red)
- Multiple polygons can be drawn by passing a list of vertex arrays
Conclusion
The fillPoly() function is useful for creating filled geometric shapes in computer vision applications. Define vertices as NumPy arrays and specify BGR colors to create various polygon shapes.
Advertisements
