Draw a filled polygon using the OpenCV function fillPoly()
Last Updated :
18 Jan, 2023
fillPoly() function of OpenCV is used to draw filled polygons like rectangle, triangle, pentagon over an image. This function takes inputs of an image and endpoints of Polygon and color.
Syntax: cv2.fillpoly(Image,End_Points,Color)
Parameter:
- Image: This is image on which we want draw filled polygon
- End_Points: Points of polygon(for triangle 3 end points, for rectangle 4 end points will be there)
- Color: It specifies the color of polygon
Example 1: Draw a triangle
In this example we will draw filled polygon triangle by giving 3 endpoints such as [160,130],[350,130],[250,300] to fillPoly() function.
Input Image:
Code:
Python3
import cv2
import numpy as np
img = cv2.imread( "image.png" )
points = np.array([[ 160 , 130 ], [ 350 , 130 ], [ 250 , 300 ]])
cv2.fillPoly(img, pts = [points], color = ( 255 , 0 , 0 ))
cv2.imshow( "Triangle" , img)
cv2.waitKey( 0 )
cv2.destroyAllWindows()
|
Output:
Example 2: Draw a Hexagon
In this example we will draw a hexagon by giving 6 endpoints such as [220,120],[130,200],[130,300],[220,380],[310,300],[310,200] to fillPoly() function.
Input:
Code:
Python3
import cv2
import numpy as np
img = cv2.imread( "image.png" )
points = np.array([[ 220 , 120 ], [ 130 , 200 ], [ 130 , 300 ],
[ 220 , 380 ], [ 310 , 300 ], [ 310 , 200 ]])
cv2.fillPoly(img, pts = [points], color = ( 0 , 255 , 0 ))
cv2.imshow( "Hexagon" , img)
cv2.waitKey( 0 )
cv2.destroyAllWindows()
|
Output:
Example 3: Draw a Rectangle
Sometimes there is a requirement that we need to show photos of someone by hiding their faces. In this case, we can use this function to hide the face of a person.
Input:
Code:
Python3
import cv2
import numpy as np
img = cv2.imread( "Documents/Person_Image.jpg" ,
cv2.IMREAD_COLOR)
points = np.array([[ 300 , 180 ], [ 400 , 180 ],
[ 400 , 280 ], [ 300 , 280 ]])
cv2.fillPoly(img, pts = [points], color = ( 0 , 0 , 255 ))
cv2.imshow( "Rectangle" , img)
cv2.waitKey( 0 )
cv2.destroyAllWindows()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...