Last Updated : 14 Aug, 2025
OpenCV is not just for image processing it can also be used for creating and manipulating geometric shapes. we’ll take three vertices of a triangle, draw triangle on a black window, calculate its centroid and mark it visually.
Problem StatementGiven three vertices of a triangle, find its centroid using formula:
(X, Y) = \left( \frac{x_1 + x_2 + x_3}{3},\ \frac{y_1 + y_2 + y_3}{3} \right)
Then, draw the triangle and highlight its centroid using OpenCV.
Refer to this article for Draw geometric shapes on images using OpenCV.
ExampleThe given vertices form a triangle whose centroid is calculated as average of their x and y coordinates, resulting in (150, 116).
Libraries RequiredInput: (100, 200), (50, 50), (300, 100)
Output: (150, 116)
Install them if needed:
Step-by-Step Approachpip install opencv-python numpy
This code creates a triangle on a black canvas using OpenCV, calculates its centroid and marks the centroid with a green dot.
Python
import numpy as np
import cv2
# Canvas dimensions
width = 400
height = 300
# Create a black image
img = np.zeros((height, width, 3), np.uint8)
# Vertices of the triangle
p1 = (100, 200)
p2 = (50, 50)
p3 = (300, 100)
# Draw the triangle using cv2.line()
cv2.line(img, p1, p2, (255, 0, 0), 3) # Blue line
cv2.line(img, p2, p3, (255, 0, 0), 3)
cv2.line(img, p1, p3, (255, 0, 0), 3)
# Calculate centroid
centroid = ( (p1[0] + p2[0] + p3[0]) // 3, (p1[1] + p2[1] + p3[1]) // 3)
print("Centroid:",centroid)
# Draw centroid as a green filled circle
cv2.circle(img, centroid, 4, (0, 255, 0), -1)
# Show the result
cv2.imshow("Triangle with Centroid", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
OutputCentroid: (150, 116)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4