user70
user70

Reputation: 955

How to fill a polygon in OpenCV?

The Python code given below draws a triangle, how can I fill it with a color inside? Or another easier way to draw a triangle in OpenCV?

pts = np.array([[100,350],[165,350],[165,240]], np.int32)
cv2.polylines(img,[pts],True,(0,255,255),2)

Upvotes: 23

Views: 29100

Answers (1)

Jeru Luke
Jeru Luke

Reputation: 21203

You have to use cv2.fillPoly().

Illustration for 2-channeled image

Change the second line to:

cv2.fillPoly(img, [pts], 255)

Code:

img = np.zeros([400, 400],dtype=np.uint8)
pts = np.array([[100,350],[165,350],[165,240]], np.int32)
cv2.fillPoly(img, [pts], 255)
cv2.imshow('Original', img)

Result:

enter image description here

Illustration for 3-channeled color image

img = cv2.imread('image_path')
pts = np.array([[170,50],[240, 40],[240, 150], [210, 100], [130, 130]], np.int32)
cv2.fillPoly(img, [pts], (255,150,255))

Result:

enter image description here

Upvotes: 39

Related Questions