Reference for ultralytics/solutions/distance_calculation.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/solutions/distance_calculation.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.solutions.distance_calculation.DistanceCalculation
Bases: BaseSolution
A class to calculate distance between two objects in a real-time video stream based on their tracks.
This class extends BaseSolution to provide functionality for selecting objects and calculating the distance between them in a video stream using YOLO object detection and tracking.
Attributes:
Name | Type | Description |
---|---|---|
left_mouse_count |
int
|
Counter for left mouse button clicks. |
selected_boxes |
Dict[int, List[float]]
|
Dictionary to store selected bounding boxes and their track IDs. |
centroids |
List[List[int]]
|
List to store centroids of selected bounding boxes. |
Methods:
Name | Description |
---|---|
mouse_event_for_distance |
Handles mouse events for selecting objects in the video stream. |
process |
Processes video frames and calculates the distance between selected objects. |
Examples:
>>> distance_calc = DistanceCalculation()
>>> frame = cv2.imread("frame.jpg")
>>> results = distance_calc.process(frame)
>>> cv2.imshow("Distance Calculation", results.plot_im)
>>> cv2.waitKey(0)
Source code in ultralytics/solutions/distance_calculation.py
mouse_event_for_distance
Handles mouse events to select regions in a real-time video stream for distance calculation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
event
|
int
|
Type of mouse event (e.g., cv2.EVENT_MOUSEMOVE, cv2.EVENT_LBUTTONDOWN). |
required |
x
|
int
|
X-coordinate of the mouse pointer. |
required |
y
|
int
|
Y-coordinate of the mouse pointer. |
required |
flags
|
int
|
Flags associated with the event (e.g., cv2.EVENT_FLAG_CTRLKEY, cv2.EVENT_FLAG_SHIFTKEY). |
required |
param
|
Any
|
Additional parameters passed to the function. |
required |
Examples:
>>> # Assuming 'dc' is an instance of DistanceCalculation
>>> cv2.setMouseCallback("window_name", dc.mouse_event_for_distance)
Source code in ultralytics/solutions/distance_calculation.py
process
Processes a video frame and calculates the distance between two selected bounding boxes.
This method extracts tracks from the input frame, annotates bounding boxes, and calculates the distance between two user-selected objects if they have been chosen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
im0
|
ndarray
|
The input image frame to process. |
required |
Returns:
Type | Description |
---|---|
SolutionResults
|
Contains processed image |
Examples:
>>> import numpy as np
>>> from ultralytics.solutions import DistanceCalculation
>>> dc = DistanceCalculation()
>>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
>>> results = dc.process(frame)
>>> print(f"Distance: {results.pixels_distance:.2f} pixels")