Triangle Filling in opencv

Hariprasad picture Hariprasad · Aug 16, 2018 · Viewed 11.9k times · Source

We have Rectangle fillings , circle and ellipse filling in opencv, but can anyone say how to fill a triangle in an image using opencv ,python.

Answer

Howard GENG picture Howard GENG · Aug 16, 2018

The simplest solution of filling a triangle shape is using draw contour function in OpenCV. Assuming we know the three points of the triangle as "pt1", "pt2" and "pt3":

import cv2
import numpy as np

image = np.ones((300, 300, 3), np.uint8) * 255

pt1 = (150, 100)
pt2 = (100, 200)
pt3 = (200, 200)

cv2.circle(image, pt1, 2, (0,0,255), -1)
cv2.circle(image, pt2, 2, (0,0,255), -1)
cv2.circle(image, pt3, 2, (0,0,255), -1)

We can put the three points into an array and draw as a contour:

triangle_cnt = np.array( [pt1, pt2, pt3] )

cv2.drawContours(image, [triangle_cnt], 0, (0,255,0), -1)

cv2.imshow("image", image)
cv2.waitKey()

Here is the output image. Cheers. Triangle Filling