본문 바로가기
Lecture/OpenCV Master with Python (Beginner)

OpenCV + Python Angle Measuring Instrument (Practical)

by codingwalks.en 2024. 10. 23.
728x90
반응형

Hello. This is codingwalks.

In this article, we will create a program that measures the angle between two lines on an image using Python and the OpenCV library based on what we have learned previously. We will explain in detail the process of defining two lines by clicking the mouse and calculating the angle using simple mathematical calculations, and provide examples with actual code.

 

1. Project Preparation

1.1. Required Libraries

import cv2
import math
cv2: Image processing with the OpenCV library
math: Standard library for mathematical calculations such as trigonometric functions

1.2. Loading images

image = cv2.imread('test.jpg')

Load the image to be measured using the cv2.imread() function. 'test.jpg' is a test image file, so you should change it to the path to the image you will actually use. 

For more information, please refer to the article below.

 

OpenCV + Python Processing images, videos, webcams, RTSP and RTMP streams

Hello. This is codingwalks.This article explains how to process images, videos, webcams, and streaming URLs such as RTSP/RTMP using OpenCV. It covers everything from basic code for reading image files and displaying them on the screen, to processing video

en.codingwalks.com

 

2. Handling the mouse click event

Now, let's implement the function to save the coordinates that define the two lines by clicking the mouse.

2.1. Defining the mouse callback function

Whenever the mouse is clicked, a red circle is drawn at the corresponding coordinates and the coordinates are saved in points_list.

def mouse_points(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(image, (x, y), 5, (0, 0, 255), -1)
        points_list.append((x, y))

2.2. Setting up mouse events

Connect the function that defines the mouse click event to the OpenCV window.

cv2.setMouseCallback('Image', mouse_points)

Please see the article below for more details.

 

OpenCV + Python Handling mouse and keyboard events and utilizing the trackbar

Hello. This is codingwalks.Event handling is an important element that enables interaction between users and programs. OpenCV also provides this event handling function to allow more intuitive manipulation of images and videos. It is possible to perform ce

en.codingwalks.com

 

3. Calculating the angle

You need three point coordinates, and use the three points you clicked to find the slope of the two lines, and then calculate the angle.

3.1. Calculating the angle formula

We use the formula tan(θ) = (m2 - m1) / (1 + m1 * m2) to calculate the angle between the two lines. At this time, the math.atan2() function calculates the angle from -π to π, and converts it to degrees.

angle calculation

3.2. Checking for sufficient number of points

Once three points are clicked, you are ready to calculate the angle.

if len(points_list) % 3 == 0 and len(points_list) != 0:
	# angle calculation

3.3. Extract Coordinates

The last three clicked points are saved as the first, second, and third points respectively.

points_1 = points_list[-3]
points_2 = points_list[-2]
points_3 = points_list[-1]

3.4. Calculating the slope

Calculate the slope of two lines.

m1 = (points_2[1] - points_1[1]) / (points_2[0] - points_1[0])
m2 = (points_3[1] - points_2[1]) / (points_3[0] - points_2[0])

3.5. Calculating the angle

Using the slope, find the angle between the two lines in radians, then convert it to degrees.

angle_radians = math.atan2(m2 - m1, 1 + m1 * m2)
angle_degrees = round(math.degrees(angle_radians))

 

4. Full source code

4.1. Mouse click method

Click the mouse three times to specify the starting point of the first line, the intersection point of the two lines, and the end point of the second line.

4.2. Error

There may be some errors depending on the image resolution and the accuracy of the click, but it provides sufficient accuracy for simple practice. For more accurate measurements, we recommend using a more complex algorithm.

4.3. Source code

import cv2
import math

points_list = []

def mouse_points(event, x, y, flags, params):
    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(image, (x, y), 5, (0, 0, 255), -1)
        points_list.append((x, y))

image = cv2.imread('angle_finder.jpg')
cv2.imshow('Image', image)
cv2.setMouseCallback('Image', mouse_points)

while True:
    if len(points_list) % 3 == 0 and len(points_list) != 0:
        points_1 = points_list[-3]
        points_2 = points_list[-2]
        points_3 = points_list[-1]

        m1 = (points_2[1] - points_1[1]) / (points_2[0] - points_1[0])
        m2 = (points_3[1] - points_2[1]) / (points_3[0] - points_2[0])

        angle_radians = math.atan2(m2 - m1, 1 + m1 * m2)
        angle_degrees = round(math.degrees(angle_radians))

        cv2.line(image, points_1, points_2, (0, 0, 255), 2)
        cv2.line(image, points_2, points_3, (0, 0, 255), 2)
        cv2.putText(image, f"Angle: {angle_degrees} degrees", (points_2[0] - 40, points_1[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 2)

    cv2.imshow('Image', image)
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()

result image

 

5. Conclusion

In this article, we implemented a program that measures the angle between two lines on an image using Python and OpenCV. Through this, you can understand how to develop a practical program that combines image processing and mathematical calculations.

 

If you found this post useful, please like and subscribe below. ^^

Buy me a coffee

 

[Codingwalks]에게 송금하기 - AQR

[Codingwalks]에게 송금하기 - AQR

aq.gy

★ All contents are referenced from the link below. ★

 

OpenCV: OpenCV-Python Tutorials

Core Operations In this section you will learn basic operations on image like pixel editing, geometric transformations, code optimization, some mathematical tools etc.

docs.opencv.org

728x90
반응형