12

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.

Hariprasad
  • 396
  • 1
  • 4
  • 14
  • Well what have you tried? My first thought it to start with a square and work from there, for example, one square can be given then the second square can be rotated on-top of the other to make a right angle triangle, or you could put two rotated triangles to make different angles in your triangle –  Aug 16 '18 at 11:22
  • 1
    We also have functionality of `cv2.fillpoly()`, which can be used to draw any polygon. – ZdaR Aug 16 '18 at 12:10

2 Answers2

22

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

Howard GENG
  • 1,075
  • 7
  • 16
13

You can draw a polygon and then fill it, like @ZdaR said.

# draw a triangle
vertices = np.array([[480, 400], [250, 650], [600, 650]], np.int32)
pts = vertices.reshape((-1, 1, 2))
cv2.polylines(img_rgb, [pts], isClosed=True, color=(0, 0, 255), thickness=20)

# fill it
cv2.fillPoly(img_rgb, [pts], color=(0, 0, 255))
# show it
plt.imshow(img_rgb)
mirkancal
  • 4,762
  • 7
  • 37
  • 75
  • Any idea if there is a way to draw an opaque / semi-transparent triangle? Thanks! – BGG16 Jan 12 '21 at 21:25
  • @GbG I think you can do it on fillPoly method. Not really sure if you can use RGBA as a color but can be good way to start. – mirkancal Jan 13 '21 at 07:27