23

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)
Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
user70
  • 597
  • 2
  • 7
  • 24

1 Answers1

37

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

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
  • 1
    Just a small detail, the last parameter in fillPoly must be (255,255,255) to fill the polygon with white color, instead it will represent only Blue channel. – Diroallu Sep 29 '21 at 07:45