Draw a triangle with centroid using OpenCV

The centroid (geometric center) of a triangle is the point where all three medians intersect. It can be calculated by taking the average of the x and y coordinates of all three vertices.

Centroid A B C

Centroid Formula

For a triangle with vertices A(x1, y1), B(x2, y2), and C(x3, y3), the centroid is calculated as ?

Centroid = ((x1+x2+x3)/3, (y1+y2+y3)/3)

In this article, we will draw a triangle with its centroid using OpenCV in Python.

Method 1: Using Predefined Coordinates

We can draw a triangle using predefined coordinates with the drawContours() method ?

Syntax

drawContours(img, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])

Parameters

  • img: Destination image

  • contours: Input contours as a Python list

  • contourIdx: Index of contours (-1 draws all contours)

  • color: Contour color

  • thickness: Line thickness (-1 for filled shape)

Example

import cv2
import numpy as np

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

# Define triangle vertices
pt1 = (150, 100)
pt2 = (100, 200)
pt3 = (200, 200)

# Create triangle contour
triangle_cnt = np.array([pt1, pt2, pt3])

# Draw filled triangle
cv2.drawContours(image, [triangle_cnt], 0, (0, 255, 0), -1)

# Calculate centroid
centroid = ((pt1[0] + pt2[0] + pt3[0]) // 3, 
           (pt1[1] + pt2[1] + pt3[1]) // 3)

# Draw centroid as red circle
cv2.circle(image, centroid, 5, (0, 0, 255), -1)

cv2.imshow("Triangle with Centroid", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Method 2: Using Mouse Clicks

This approach allows users to draw a triangle interactively by clicking three points on the image ?

Key Functions

  • setMouseCallback(): Sets mouse event handler for a window

  • cv2.line(): Draws lines between points

  • cv2.circle(): Draws circles

  • EVENT_LBUTTONDOWN: Left mouse button click event

Example

import numpy as np
import cv2

# Global variables
points = []
image = None

def draw_triangle(event, x, y, flags, param):
    global points, image
    
    if event == cv2.EVENT_LBUTTONDOWN:
        # Add clicked point
        points.append((x, y))
        
        # Draw point
        cv2.circle(image, (x, y), 5, (255, 0, 0), -1)
        
        # Draw lines when we have 2+ points
        if len(points) > 1:
            cv2.line(image, points[-2], points[-1], (0, 255, 0), 2)
        
        # Complete triangle with 3 points
        if len(points) == 3:
            # Draw final line to close triangle
            cv2.line(image, points[-1], points[0], (0, 255, 0), 2)
            
            # Calculate and draw centroid
            x_coords = [p[0] for p in points]
            y_coords = [p[1] for p in points]
            
            centroid_x = sum(x_coords) // 3
            centroid_y = sum(y_coords) // 3
            
            cv2.circle(image, (centroid_x, centroid_y), 8, (0, 0, 255), -1)
            
            print(f"Centroid: ({centroid_x}, {centroid_y})")

# Create blank white image
image = np.ones((400, 400, 3), dtype=np.uint8) * 255

cv2.namedWindow('Triangle Drawing')
cv2.setMouseCallback('Triangle Drawing', draw_triangle)

print("Click 3 points to draw triangle. Press 'q' to quit.")

while True:
    cv2.imshow('Triangle Drawing', image)
    key = cv2.waitKey(1) & 0xFF
    
    if key == ord('q'):
        break
    elif key == ord('r'):  # Reset
        points = []
        image = np.ones((400, 400, 3), dtype=np.uint8) * 255

cv2.destroyAllWindows()

Comparison

Method Use Case Advantages
Predefined Coordinates Fixed triangle shapes Simple, precise positioning
Mouse Clicks Interactive drawing User-defined shapes, flexible

Conclusion

OpenCV provides multiple ways to draw triangles with centroids. Use predefined coordinates for fixed shapes or mouse events for interactive drawing. The centroid is always calculated as the average of the three vertices.

Updated on: 2026-03-27T06:55:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements