Bắt đầu

Tính toán khoảng cách bằng Ultralytics YOLO26

Tính toán khoảng cách là gì?#

Tính khoảng cách là quá trình đo khoảng cách giữa hai đối tượng được phát hiện trong ảnh hoặc khung hình video. Với Ultralytics YOLO26, giải pháp đo khoảng cách giữa centroid của hai hộp giới hạn do người dùng chọn.



Xem: Cách ước tính khoảng cách giữa các đối tượng được phát hiện bằng Ultralytics YOLO theo pixel 🚀

Hình ảnh minh họa#

Tính toán khoảng cách bằng Ultralytics YOLO26
Tính toán khoảng cách bằng Ultralytics YOLO26

Ưu điểm của tính toán khoảng cách#

  • Độ chính xác định vị: Cải thiện độ chính xác của việc xác định vị trí không gian trong các tác vụ thị giác máy tính.
  • Ước tính kích thước: Cho phép ước tính kích thước đối tượng để hiểu rõ hơn ngữ cảnh.
  • Hiểu cảnh: Cải thiện khả năng hiểu cảnh 3D để đưa ra quyết định tốt hơn trong các ứng dụng như xe tự hành và hệ thống giám sát.
  • Tránh va chạm: Cho phép hệ thống phát hiện nguy cơ va chạm bằng cách theo dõi khoảng cách giữa các đối tượng đang chuyển động.
  • Phân tích không gian: Hỗ trợ phân tích mối quan hệ và tương tác giữa các đối tượng trong môi trường được giám sát.
Tính toán khoảng cách
  • Nhấp chuột trái vào hai bounding box bất kỳ để tính khoảng cách.
  • Nhấp chuột phải để xóa tất cả các điểm đã vẽ.
Khoảng cách chỉ là giá trị ước tính

Khoảng cách chỉ là giá trị ước tính và có thể không hoàn toàn chính xác vì được tính từ dữ liệu 2D, vốn không có thông tin chiều sâu. Để có độ sâu theo từng pixel, hãy dùng model ước tính độ sâu.

Tính khoảng cách bằng YOLO26#

Giải pháp DistanceCalculation theo dõi các đối tượng qua nhiều khung hình và đo khoảng cách Euclid, tính bằng pixel, giữa tâm của hai bounding box bất kỳ mà bạn chọn bằng chuột. Chạy ví dụ bên dưới, sau đó nhấp chuột trái vào hai đối tượng để vẽ đường nối và xem khoảng cách; nhấp chuột phải để xóa lựa chọn.

Tính toán khoảng cách bằng Ultralytics YOLO
import cv2

from ultralytics import solutions

cap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"

# Bộ ghi video
w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
video_writer = cv2.VideoWriter("distance_output.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))

# Khởi tạo đối tượng tính toán khoảng cách
distancecalculator = solutions.DistanceCalculation(
    model="yolo26n.pt",  # đường dẫn đến tệp model YOLO26.
    show=True,  # hiển thị đầu ra
)

# Xử lý video
while cap.isOpened():
    success, im0 = cap.read()

    if not success:
        print("Video frame is empty or processing is complete.")
        break

    results = distancecalculator(im0)

    print(results)  # truy cập đầu ra

    video_writer.write(results.plot_im)  # ghi khung hình đã xử lý.

cap.release()
video_writer.release()
cv2.destroyAllWindows()  # đóng tất cả cửa sổ đang mở

Các đối số của DistanceCalculation()#

Dưới đây là bảng các đối số của DistanceCalculation:

Đối sốKiểuMặc địnhMô tả
modelstrNoneĐường dẫn đến tệp model Ultralytics YOLO.
line_widthint2Độ dày đường viền của box, keypoint và số đếm mà giải pháp vẽ.
verboseboolTrueBật nhật ký theo từng frame của giải pháp, gồm shape đầu vào, số lượng class và tốc độ xử lý. Bản thân lệnh gọi tracking luôn không ghi nhật ký.

Bạn cũng có thể sử dụng các đối số track trong giải pháp DistanceCalculation.

Đối sốKiểuMặc địnhMô tả
trackerstr'tracktrack.yaml'Chỉ định thuật toán theo dõi cần sử dụng. Các tùy chọn tích hợp sẵn: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25Đặt ngưỡng confidence cho các đối tượng được phát hiện; giá trị thấp hơn cho phép theo dõi nhiều đối tượng hơn nhưng có thể bao gồm cả kết quả dương tính giả.
ioufloat0.5Đặt ngưỡng Intersection over Union (IoU) để lọc các đối tượng phát hiện bị chồng lấn.
classeslistNoneLọc kết quả theo chỉ mục class. Ví dụ: classes=[0, 2, 3] chỉ theo dõi các class được chỉ định.
devicestrNoneChỉ định thiết bị dùng để suy luận (ví dụ: cpu, cuda:0 hoặc 0). Cho phép người dùng chọn CPU, một GPU cụ thể hoặc thiết bị tính toán khác để chạy model.
imgszint or tuple640Kích thước ảnh suy luận mục tiêu: số nguyên cho ảnh vuông hoặc cặp (height, width). Kích thước sẽ được điều chỉnh theo stride của model.
max_detint300Số lượng đối tượng phát hiện tối đa được giữ lại trong mỗi khung hình trước khi theo dõi, giới hạn số đối tượng mà một giải pháp xử lý trong các cảnh dày đặc.
quantizeint or strNoneĐộ chính xác suy luận: 16 (FP16) hoặc 32/unset (FP32) cho model PyTorch và TorchScript khi chạy ngoài CPU; các định dạng khác sử dụng độ chính xác do artifact và runtime của chúng lựa chọn. Thay thế đối số half đã lỗi thời.

Ngoài ra, có thể sử dụng các đối số trực quan hóa sau:

Đối sốKiểuMặc địnhMô tả
showboolFalseNếu True, hiển thị ảnh hoặc video đã được chú thích trong một cửa sổ. Hữu ích để nhận phản hồi trực quan ngay lập tức trong quá trình phát triển hoặc kiểm thử.
show_confboolTrueHiển thị điểm confidence bên cạnh nhãn của mỗi detection. Cho biết mức độ chắc chắn của model đối với từng detection.
show_labelsboolTrueHiển thị nhãn cho mỗi detection trong đầu ra trực quan. Giúp nhận biết ngay các đối tượng được phát hiện.

Chi tiết triển khai#

Lớp DistanceCalculation hoạt động bằng cách theo dõi các đối tượng qua các khung hình video và tính khoảng cách Euclid giữa tâm của các bounding box được chọn. Khi bạn nhấp vào hai đối tượng, giải pháp sẽ:

  1. Trích xuất tâm (điểm trung tâm) của các bounding box được chọn
  2. Tính khoảng cách Euclid giữa các tâm này theo đơn vị pixel
  3. Hiển thị khoảng cách trên khung hình bằng một đường nối giữa các đối tượng

Triển khai sử dụng phương thức mouse_event_for_distance để xử lý tương tác chuột, cho phép người dùng chọn đối tượng và xóa lựa chọn khi cần. Phương thức process xử lý từng khung hình, theo dõi đối tượng và tính khoảng cách.

Ứng dụng#

Tính khoảng cách bằng YOLO26 có nhiều ứng dụng thực tiễn:

  • Phân tích bán lẻ: Đo khoảng cách giữa khách hàng và sản phẩm, đồng thời phân tích hiệu quả bố trí cửa hàng
  • An toàn công nghiệp: Giám sát khoảng cách an toàn giữa người lao động và máy móc
  • Quản lý giao thông: Phân tích khoảng cách giữa các phương tiện và phát hiện hành vi bám đuôi
  • Phân tích thể thao: Tính khoảng cách giữa các cầu thủ, bóng và những vị trí quan trọng trên sân
  • Chăm sóc sức khỏe: Đảm bảo khoảng cách phù hợp trong khu vực chờ và theo dõi di chuyển của bệnh nhân
  • Robot học: Giúp robot duy trì khoảng cách phù hợp với chướng ngại vật và con người

Câu hỏi thường gặp#

  • Để tính khoảng cách giữa các đối tượng bằng Ultralytics YOLO26, bạn cần xác định tâm bounding box của các đối tượng được phát hiện. Quy trình này bao gồm việc khởi tạo lớp DistanceCalculation từ module solutions của Ultralytics và sử dụng đầu ra tracking của model để tính khoảng cách.

  • Tính khoảng cách bằng Ultralytics YOLO26 mang lại một số lợi ích:

    • Độ chính xác định vị: Cung cấp vị trí chính xác của các đối tượng trong không gian.
    • Ước tính kích thước: Giúp ước tính kích thước vật lý, góp phần hiểu rõ hơn ngữ cảnh.
    • Hiểu cảnh: Tăng cường khả năng hiểu cảnh 3D, hỗ trợ đưa ra quyết định tốt hơn trong các ứng dụng như lái xe tự hành và giám sát.
    • Xử lý theo thời gian thực: Thực hiện phép tính tức thời, phù hợp cho phân tích video trực tiếp.
    • Khả năng tích hợp: Hoạt động cùng các giải pháp YOLO26 khác như theo dõi đối tượng và ước tính tốc độ.
  • Có, bạn có thể tính khoảng cách trên luồng video thời gian thực bằng Ultralytics YOLO26. Quy trình này bao gồm thu nhận khung hình video bằng OpenCV, chạy phát hiện đối tượng bằng YOLO26 và sử dụng lớp DistanceCalculation để tính khoảng cách giữa các đối tượng trong những khung hình liên tiếp. Để xem hướng dẫn triển khai chi tiết, hãy tham khảo ví dụ về luồng video.

  • Để xóa các điểm đã vẽ trong quá trình tính khoảng cách bằng Ultralytics YOLO26, bạn có thể nhấp chuột phải. Thao tác này sẽ xóa tất cả các điểm bạn đã vẽ. Để biết thêm chi tiết, hãy xem phần ghi chú trong ví dụ tính toán khoảng cách.

  • Các đối số chính để khởi tạo lớp DistanceCalculation trong Ultralytics YOLO26 bao gồm:

    • model: Đường dẫn đến tệp model YOLO26.
    • tracker: Thuật toán tracking cần sử dụng (các giải pháp mặc định dùng tracktrack.yaml).
    • conf: Ngưỡng confidence cho các đối tượng được phát hiện.
    • show: Cờ hiển thị đầu ra.

    Để xem danh sách đầy đủ và các giá trị mặc định, hãy tham khảo các đối số của DistanceCalculation.

Bình luận195

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. muhammadwildangoniGitHub

    hallo, I am processing a men's 100 meter sprint video using YOLO and SpeedEstimator (Ultralytics) to detect runners, estimate their speed, and track their progress. However, the output statistics are incorrect. My code detects 16 runners, while there should only be 8 (those on the track), and the maximum speed reported is 0.00 m/s, which is clearly not correct for a sprint race. The furthest distance covered is about 96.7 meters, which seems off.

    1646ed86-3d5e-4074-b5cf-71bbd4da30c4

    import cv2 import math import numpy as np from ultralytics import YOLO from ultralytics.solutions import speed_estimation

    --- SETTINGS ---

    video_path = "WHAT A RACE! _ Men s 100m Final! _ #Paris2024 highlights (online-video-cutter.com).mp4" # Change to your video path model_path = "yolo11n.pt" # Path to your YOLO model (could be yolov11n.pt if available) output_path = "output_sprint.avi" # Output video file name

    meter_per_pixel = 0.05 # Calibration result for track (e.g., 0.05 for a 100m lane) center_point = (0, 720) # Track start point (adjust to your video height)

    --- INITIALIZATION ---

    cap = cv2.VideoCapture(video_path) assert cap.isOpened(), "Error reading video file"

    w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS)) out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*"MJPG"), fps, (w, h))

    model = YOLO(model_path) names = model.model.names if hasattr(model.model, "names") else ["person"]

    speed_obj = speed_estimation.SpeedEstimator( names=names, reg_pts=[(0, int(h/2)), (w, int(h/2))], # Speed estimation line (across track, adjust as needed) view_img=False, meter_per_pixel=meter_per_pixel # Convert pixel to meters )

    frame_count = 0 speed_over_time, distance_over_time = {}, {}

    while cap.isOpened(): success, frame = cap.read() if not success: break frame_count += 1

    # Detect and track runners on each frame
    tracks = model.track(frame, persist=True, show=False)
    
    # Estimate runners' speed and update visualization on frame
    frame = speed_obj.estimate_speed(frame)
    
    # Extract runner IDs, position, speed, and distance
    # Make sure .boxes.id/cls property exists:
    if tracks and hasattr(tracks[0], "boxes") and tracks[0].boxes.id is not None:
        boxes = tracks[0].boxes.xyxy.cpu()
        track_ids = tracks[0].boxes.id.int().cpu().tolist()
        clss = tracks[0].boxes.cls.cpu().tolist()
        for box, track_id, cls in zip(boxes, track_ids, clss):
            if cls == 0:  # 'person' class (runners)
                # Calculate runner's distance from start
                x1, y1 = int((box[0] + box[2]) // 2), int((box[1] + box[3]) // 2)
                distance = (math.sqrt((x1 - center_point[0]) ** 2 + (y1 - center_point[1]) ** 2)) * meter_per_pixel
    
                # Store statistics in dictionary
                if track_id not in distance_over_time:
                    distance_over_time[track_id] = [0] * (frame_count - 1)
                distance_over_time[track_id].append(distance)
    
                speed = speed_obj.speeds.get(track_id, 0) if hasattr(speed_obj, "speeds") else 0
                if track_id not in speed_over_time:
                    speed_over_time[track_id] = [0] * (frame_count - 1)
                speed_over_time[track_id].append(speed)
    
                # Overlay runner's speed and distance information directly on video frame
                text_speed = f"Speed: {speed:.2f} m/s"
                text_dist = f"Distance: {distance:.2f} m"
                cv2.putText(frame, f"ID:{track_id} {text_speed}, {text_dist}", (x1, y1 - 10),
                            cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,0), 2)
    
    # Save frame to output video
    out.write(frame)
    
    # Display real-time video preview
    cv2.imshow("Sprint Runner Detection Preview", frame)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

    cap.release() out.release() cv2.destroyAllWindows()

    --- Final statistics: print results to terminal ---

    best_speed = max((max(speeds) for speeds in speed_over_time.values()), default=0) best_distance = max((max(distances) for distances in distance_over_time.values()), default=0) total_runners = len(distance_over_time)

    print(f"Total runners detected: {total_runners}") print(f"Highest speed: {best_speed:.2f} m/s") print(f"Furthest distance covered: {best_distance:.2f} meters")

  2. maribalkeGitHub(đã chỉnh sửa)

    Hi! I have tried to do a test on the distance calculation on a single image, but I keep getting the attribute error: 'DistanceCalculation' object has no attribute 'start_process'. I have basis in the YOLO11n-model, further trained on images from a different dataset.

    model_path = "../runs/detect/train2/weights/best.pt"
    model = YOLO(model_path)
    
    dist_obj = distance_calculation.DistanceCalculation() 
    
    frame = cv2.imread("../images/s73/raw_images/10.jpg")
    
    # Detect objects
    results = model(frame)
    
    # Run object tracking
    tracks = model.track(frame, persist=True, show = False)
    
    # process the image
    image_with_distances = dist_obj.start_process(frame, tracks)
    
    # Display the frame
    cv2.imshow('Distance Calculation', image_with_distances)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @maribalke thanks for reaching out! start_process() has been removed. DistanceCalculation is now called directly on the frame and returns a results object with the annotated image in plot_im. It also runs tracking itself, so no separate model.track() call is needed. Here's the minimal fix for your single-image case:

      dist_obj = solutions.DistanceCalculation(model=model_path, show=False)
      results = dist_obj(frame)
      cv2.imshow("Distance Calculation", results.plot_im)

      Note that the distance is measured between two objects you select by clicking them in a display window, so a single static image only shows a distance once two boxes have been selected. For full implementation details, see our Distance Calculation Guide. Let us know if you encounter any other issues!

  3. dgnovoGitHub

    Is it possible to know the distance from an object and another object without using mouse?

  4. Muhammad-237GitHub

    How can we find the distance of in the bounding box like from one point to another point in the bounding box to measure the size of object

    1. Glenn JocherUltralytics

      @Muhammad-237 to measure the size of an object within a bounding box using Ultralytics YOLO11, you can calculate the distance between two points (e.g., edges or centroid) within that bounding box. This can be achieved using the DistanceCalculation class, which allows you to click on specific points to measure distances. Keep in mind, these calculations are approximations as they rely on 2D data without depth information. For more details, refer to the Distance Calculation Docs.

  5. gg120wolfGitHub

    Hi, I am using the example code of Distance Calculation using YOLO11 Example, but there is a problem of File "f:\fyp yolo\ultralytics-main\distance test1.py", line 13, in distance = solutions.DistanceCalculation() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: DistanceCalculation.init() missing 1 required positional argument: 'names' So what is this names should i set?

    1. RizwanMunawarGitHub

      @gg120wolf Hi, the correct way to use the Ultralytics distance calculation module is mentioned below.

      import cv2
      
      from ultralytics import solutions
      
      cap = cv2.VideoCapture("Path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))
      
      # Video writer
      video_writer = cv2.VideoWriter("distance_calculation.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
      
      # Init distance-calculation obj
      distance = solutions.DistanceCalculation(model="yolo11n.pt", show=True)
      
      # Process video
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              print("Video frame is empty or video processing has been successfully completed.")
              break
          im0 = distance.calculate(im0)
          video_writer.write(im0)
      
      cap.release()
      video_writer.release()
      cv2.destroyAllWindows()

      Thanks :) The Ultralytics Team!

  6. tylerfrisinger01GitHub

    Hey there, I have a model that is trained for object detection not tracking. We are detecting two animals that are inside a cage. What we want to do is import a mp4 video then calculate the distance between the two objects while also showing the bounding boxes. However when i use the VideoStream code snippet from above, the popup window is larger then my screen. How could i adjust that code to make it a different window size so that I am able to track them in real time.

    Also after this is done and the distances are calculated is there anyway to save the whole video with the bounding boxes and the distance calculations that were done in real time? Or would I have to save the video by doing the results = model.predict(save=true) and also do the VideoStream code snippet from above at the same time? and not have the distances shown in the saved video?

    Get back to me as soon as possible as this is for a project for school! Thank You!!

    1. tylerfrisinger01GitHub

      I am also using YOLOv11, i'm not sure if that will change anything or not. And i have tried creating my own window using cv2 but that didnt work when i attempted it.

    2. Glenn JocherUltralytics

      @tylerfrisinger01 to adjust the window size in OpenCV, you can use cv2.namedWindow() and cv2.resizeWindow() to set a custom size. For saving the video with bounding boxes and distances, you can modify the code to include distance annotations and use cv2.VideoWriter to save the processed frames. Here's a quick example on resizing the window:

      cv2.namedWindow('Video', cv2.WINDOW_NORMAL)
      cv2.resizeWindow('Video', 800, 600)  # Adjust the dimensions as needed

      Regarding saving the video with distances, you can overlay the distance on the frames before writing them out with cv2.VideoWriter. If you need further assistance, feel free to ask!

    3. tylerfrisinger01GitHub

      @glenn-jocher when I do this, it still pops open its own window that I am assuming is built into the solutions.DistanceCalculator function (since that is the name of the window) So then it does not work. Any workaround for this?

    4. Glenn JocherUltralytics(đã chỉnh sửa)

      @tylerfrisinger01 to prevent the DistanceCalculation function from opening its own window, you can set the show parameter to False when initializing it, like so: distance = solutions.DistanceCalculation(model="yolo26n.pt", show=False). This should stop the automatic display window. For saving the video, continue using cv2.VideoWriter. Let me know if you need further assistance!

  7. AbtinzGitHub

    Hello everyone, I want to deploy an yolov8-application on the edge device and estimate the distance through the user's camera without having to click on the detected object, how can I find the distance of the objects to the camera without need to click?

    1. Glenn JocherUltralytics

      @Abtinz to estimate object distances without clicking, you'll need to use depth estimation techniques, as YOLOv8 primarily provides 2D bounding boxes. Consider integrating depth sensors or stereo cameras to obtain depth information. For more details, you can refer to the distance calculation guide.

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @gaodaren47297 the DistanceCalculation solution measures the pixel distance between the centroids of two objects you select in the frame; it does not estimate the distance between the camera and an object. A 2D bounding box has no depth information, so camera-to-object distance needs extra information such as a depth sensor or stereo camera, or a calibration using an object of known size. For measuring between objects, see the distance calculation documentation on our website. If you have further questions, feel free to ask here.

  8. Dmitrii-SmirnovGitHub

    Hi Guys, Guys, I have a video with multiple objects(people) on the video. I need to calculate distance between each detected person on the each frame and to save results to csv file. Can you help me with that task? It will be really cool if you will share documentation=) As I understood relevant method for my task is DistanceCalculation(names=names[0], view_img=True).calculate_distance(obj1, obj2), am I correct?

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      @Dmitrii-Smirnov there is no calculate_distance(obj1, obj2) method on DistanceCalculation in current versions. The solution is called on each frame (results = dist_obj(im0)), you left-click two tracked objects, and it reports the pixel distance in results.pixels_distance. For distances between every pair of people on each frame and a CSV export, compute the centroid distances from the tracking boxes yourself. For details, see our documentation: https://docs.ultralytics.com/guides/distance-calculation/.

    2. Glenn JocherUltralytics(đã chỉnh sửa)

      @Dmitrii-Smirnov to calculate distances between all detected people in each frame and save the results to a CSV file, compute the centroid distances from the tracking results. The DistanceCalculation solution only measures between two objects you click, so for all pairs here's a basic implementation:

      import csv
      import math
      from itertools import combinations
      
      import cv2
      
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")
      
      cap = cv2.VideoCapture("path/to/video/file.mp4")
      assert cap.isOpened(), "Error reading video file"
      
      with open("distances.csv", mode="w", newline="") as file:
          writer = csv.writer(file)
          writer.writerow(["Frame", "Object1", "Object2", "Distance"])
      
          frame_count = 0
          while cap.isOpened():
              success, im0 = cap.read()
              if not success:
                  break
      
              results = model.track(im0, persist=True, show=False, classes=[0])  # class 0 = person
              boxes = results[0].boxes
              if boxes.id is not None:
                  centroids = dict(zip(boxes.id.int().tolist(), boxes.xywh[:, :2].tolist()))
                  for (id1, c1), (id2, c2) in combinations(centroids.items(), 2):
                      writer.writerow([frame_count, id1, id2, math.dist(c1, c2)])
      
              frame_count += 1
      
      cap.release()

      This script captures video frames, calculates pixel distances between detected people, and writes the results to a CSV file. For more details, refer to our documentation: https://docs.ultralytics.com/guides/distance-calculation/.

  9. zgr1446741194GitHub

    Hello author, I would like to propose a scenario similar to this: using monocular distance measurement to calculate the distance from the distant water level line (similar to the shoreline) in the video stream obtained by the camera to my camera (a kind of early warning of the water level), how can I use the solution? At present, the difficulty can be determined that we need to complete distance conversion similar to 3D to 2D, because of perspective space, instead of using fixed linear distance conversion similar to visionEye (from pixels to realistic distance). Another difficulty is that we do not know the true physical properties of the observed water line, which means that we cannot use the traditional method of monocular distance measurement to deduce the distance from the true length or height of the observed object. If you have any viable solutions, thank you very much for adding the code demo in your reply.

    1. Glenn JocherUltralytics

      For calculating distances to a waterline using monocular vision, consider using depth estimation techniques or stereo vision for more accurate results. YOLO models can assist in object detection, but for precise distance measurement, integrating additional sensors or methods might be necessary. For more details, please refer to our distance calculation guide.