Master Angle Detection in Images Using OpenCV – A Python Tutorial You’ll Love

Learn how to measure angles interactively on images using OpenCV in Python. This tutorial walks you through a step-by-step guide with code examples and visuals.

Ever Wanted to Measure Angles from an Image? Whether you’re into sports analytics, medical imaging, or computer vision experiments, angle detection is a valuable tool in your AI toolkit. In this guide, we’ll explore how to use OpenCV in Python to measure angles on any image interactively — with just a few mouse clicks.

In this guide, I’ll show you exactly how to do it using OpenCV, a powerful open-source computer vision library in Python. You’ll be able to:

  • Click on 3 points in an image
  • Automatically draw lines between them
  • Instantly calculate and display the angle at the middle point

Let’s dive in and build this interactive tool — step by step.


🧰 Step 1: Import the Required Libraries

First, let’s bring in the Python modules we’ll be using.

import cv2
import math
  • cv2: This is the heart of OpenCV for Python.
  • math: To calculate trigonometric values and angles.

🖼 Step 2: Load the Image

You’ll need an image where you want to measure the angle. Replace 'test.jpg' with your image’s path.

path = 'test.jpg'
img = cv2.imread(path)
pointsList = []

👉 Tip: Make sure the image is in the same folder or provide a full path.


👆 Step 3: Create a Mouse Click Event to Select Points

This function tracks every left-click on the image. It draws a red circle and connects it with a line if it’s part of a group of 3.

def mousePoints(event, x, y, flags, params):
if event == cv2.EVENT_LBUTTONDOWN:
size = len(pointsList)
if size != 0 and size % 3 != 0:
cv2.line(img, tuple(pointsList[round((size - 1) / 3) * 3]), (x, y), (0, 0, 255), 2)
cv2.circle(img, (x, y), 5, (0, 0, 255), cv2.FILLED)
pointsList.append([x, y])

💡 Why groups of 3? Because a single angle is formed by 3 points: the vertex and two ends of the arms.


📐 Step 4: Define the Gradient (Slope) Function

To calculate angles, we need the slope (gradient) between two points.

def gradient(pt1, pt2):
return (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])

🔢 Step 5: Calculate the Angle Using Trigonometry

Now comes the magic — compute the angle between the two lines using the tangent formula.

def getAngle(pointsList):
pt1, pt2, pt3 = pointsList[-3:]
m1 = gradient(pt1, pt2)
m2 = gradient(pt1, pt3)
angR = math.atan((m2 - m1) / (1 + (m2 * m1)))
angD = round(math.degrees(angR))

cv2.putText(img, str(angD), (pt1[0] - 40, pt1[1] - 20),
cv2.FONT_HERSHEY_COMPLEX, 1.5, (0, 0, 255), 2)

🧠 Heads up: The math.atan() function returns the angle in radians, which we convert to degrees.


🔁 Step 6: Show the Image and Run the Loop

We use OpenCV’s imshow() and waitKey() to continuously display the image and respond to mouse clicks.

while True:
if len(pointsList) % 3 == 0 and len(pointsList) != 0:
getAngle(pointsList)

cv2.imshow('Image', img)
cv2.setMouseCallback('Image', mousePoints)
if cv2.waitKey(1) & 0xFF == ord('q'):
pointsList = []
img = cv2.imread(path)

🖱️ How It Works:

  • Click 3 times to define an angle.
  • The angle is automatically calculated and shown on the image.
  • Press q to reset and measure again.

📊 Example Use Cases

Use CaseDescription
Sports AnalysisMeasure joint angles of athletes in training videos.
Medical ImagingEvaluate posture or limb alignment from X-rays.
RoboticsDetect joint positions and turning angles from camera feeds.

🖼 Screenshots


🛠 Optional Enhancements

Feeling adventurous? You can:

  • Add error handling for vertical lines (divide-by-zero case)
  • Measure multiple angles and store them
  • Create a GUI wrapper using Tkinter or PyQt

🏁 Conclusion

With just a few lines of Python and the power of OpenCV, you’ve built a real-time angle measurement tool that’s both simple and powerful. It’s perfect for any project involving geometry, posture, motion tracking, or visual analytics.


💬 Ready to Try It?

Have an idea where to use this tool? Let us know in the comments!

Looking to integrate AI-powered vision systems into your business? Explore our Computer Vision Solutions at Ossels AI

Posted by Ananya Rajeev

Ananya Rajeev is a Kerala-born data scientist and AI enthusiast who simplifies generative and agentic AI for curious minds. B.Tech grad, code lover, and storyteller at heart.