Ultralytics YOLO26을 사용한 속도 추정

속도 추정이란 무엇인가요?#

속도 추정은 주어진 맥락에서 객체의 이동 속도를 계산하는 과정으로, 컴퓨터 비전 애플리케이션에서 자주 사용됩니다. Ultralytics YOLO26을 사용하면 객체 추적과 거리 및 시간 데이터를 활용해 객체의 속도를 계산할 수 있어 교통 모니터링 및 감시와 같은 작업에 유용합니다.



시청: Ultralytics YOLO26을 사용한 속도 추정

속도 추정의 장점#

  • 효율적인 교통 제어: 정확한 속도 추정은 교통 흐름을 관리하고 안전을 높이며 도로 혼잡을 줄이는 데 도움이 됩니다.
  • 정밀한 자율 주행: 자율주행차와 같은 자율 시스템에서 신뢰할 수 있는 속도 추정은 안전하고 정확한 차량 주행을 보장합니다.
  • 감시 보안 강화: 감시 분석에서 속도 추정을 활용하면 비정상적인 행동이나 잠재적 위협을 식별하여 보안 조치의 효과를 높일 수 있습니다.

실제 애플리케이션#

교통교통
Ultralytics YOLO26을 사용한 도로 속도 추정Ultralytics YOLO26을 사용한 다리 위 속도 추정
Ultralytics YOLO26을 사용한 도로 속도 추정Ultralytics YOLO26을 사용한 다리 위 속도 추정
속도는 추정치입니다

속도는 추정치이며 완전히 정확하지 않을 수 있습니다. 결과는 카메라 사양과 관련 요인에 따라서도 달라집니다.

YOLO26으로 속도 추정하기#

SpeedEstimator 솔루션은 프레임 간 각 객체를 추적하고, 비디오 프레임 속도(fps)와 실제 크기 기준(meter_per_pixel)을 사용해 픽셀 변위를 속도로 변환합니다. 카메라 설정에 맞게 meter_per_pixel을 조정하고, 노이즈가 있는 추적 결과의 이상치를 제한하려면 max_speed를 사용하세요.

Ultralytics YOLO를 사용한 속도 추정
# Run a speed example
yolo solutions speed show=True

# Pass a source video
yolo solutions speed source="path/to/video.mp4"

# Adjust meter per pixel value based on camera configuration
yolo solutions speed meter_per_pixel=0.05

SpeedEstimator 인수#

다음은 SpeedEstimator 인수 표입니다:

인수유형기본값설명
modelstrNoneUltralytics YOLO 모델 파일의 경로입니다.
fpsfloat30.0속도 계산에 사용하는 초당 프레임 수입니다.
max_histint5속도 및 방향 계산을 위해 객체별로 추적할 최대 과거 지점 수입니다.
meter_per_pixelfloat0.05픽셀 거리를 실제 단위로 변환하는 데 사용하는 스케일링 계수입니다.
max_speedint120최대 속도(km/h)입니다. 추정 속도가 이를 초과하면 이 값으로 제한됩니다.
line_widthint2Solution에서 그리는 상자, 키포인트 및 개수 표시의 선 두께입니다.
verboseboolTrue프레임별 입력 형태, 클래스 개수 및 처리 속도 로그를 활성화합니다. 추적 호출 자체는 항상 로그를 출력하지 않습니다.

SpeedEstimator 솔루션에서는 다음 track 매개변수를 사용할 수 있습니다:

인수유형기본값설명
trackerstr'tracktrack.yaml'사용할 추적 알고리즘을 지정합니다. 기본 제공 옵션: botsort.yaml, bytetrack.yaml, ocsort.yaml, deepocsort.yaml, fasttrack.yaml, tracktrack.yaml.
conffloat0.25탐지에 대한 신뢰도 임계값을 설정합니다. 값을 낮추면 추적할 수 있는 객체가 늘어나지만 오탐이 포함될 수 있습니다.
ioufloat0.5중복 탐지를 필터링하기 위한 교집합 대비 합집합 (IoU) 임계값을 설정합니다.
classeslistNone클래스 인덱스로 결과를 필터링합니다. 예를 들어 classes=[0, 2, 3]은 지정된 클래스만 추적합니다.
devicestrNone추론에 사용할 장치를 지정합니다(예: cpu, cuda:0 또는 0). 사용자는 모델 실행에 사용할 CPU, 특정 GPU 또는 기타 연산 장치를 선택할 수 있습니다.
imgszint or tuple640추론 대상 이미지 크기입니다. 정사각형을 나타내는 정수 또는 (height, width) 쌍을 지정합니다. 모델 stride에 맞춰 형태가 조정됩니다.
max_detint300추적 전에 프레임별로 유지할 최대 탐지 수를 지정하여 밀집된 장면에서 솔루션이 처리하는 객체 수를 제한합니다.
quantizeint or strNone추론 정밀도: CPU 이외의 환경에서 PyTorch 및 TorchScript 모델은 16(FP16) 또는 32/unset(FP32)을 사용하며, 다른 형식은 아티팩트와 런타임이 선택하는 정밀도를 사용합니다. 더 이상 사용되지 않는 half 인수를 대체합니다.

또한 다음 시각화 옵션을 지원합니다:

인수유형기본값설명
showboolFalseTrue이면 주석이 추가된 이미지나 비디오를 창에 표시합니다. 개발 또는 테스트 중 즉각적인 시각적 피드백을 얻는 데 유용합니다.
show_labelsboolTrue시각화 출력에 각 감지 결과의 레이블을 표시합니다. 감지된 객체를 즉시 파악할 수 있습니다.

자주 묻는 질문#

  • Ultralytics YOLO26으로 객체 속도를 추정하려면 객체 감지와 추적을 결합합니다. 모델은 각 프레임에서 객체를 감지하고 프레임 간 객체를 추적한 다음, 프레임 속도와 meter_per_pixel 스케일을 사용해 프레임 사이의 이동 거리를 속도로 변환합니다. 위의 Python 예제는 전체 파이프라인을 실행하며, 비디오를 전달하고 카메라에 맞게 meter_per_pixel을 조정하면 됩니다. 자세한 배경 정보는 공식 블로그 게시물을 참조하세요.

  • 속도 추정에 Ultralytics YOLO26을 사용하면 교통 관리 측면에서 상당한 이점을 얻을 수 있습니다:

    • 안전 강화: 차량 속도를 정확하게 추정하여 과속을 감지하고 도로 안전을 높입니다.
    • 실시간 모니터링: YOLO26의 실시간 객체 감지 기능을 활용해 교통 흐름과 혼잡을 효과적으로 모니터링합니다.
    • 확장성: 엣지 디바이스부터 서버까지 다양한 하드웨어 환경에 모델을 배포하여 대규모 구현을 위한 유연하고 확장 가능한 솔루션을 제공합니다.

    더 많은 애플리케이션은 속도 추정의 장점을 참조하세요.

  • 예. YOLO26은 PyTorch를 기반으로 하며, Ultralytics는 다른 ML 프레임워크와의 상호 운용성을 위해 YOLO26 모델을 ONNX, TensorRT, CoreML, TensorFlow SavedModel 등의 형식으로 내보내는 기능을 지원합니다.

    YOLO26 모델을 ONNX 형식으로 내보내려면 다음을 수행하세요:

    yolo export model=yolo26n.pt format=onnx

    모델 내보내기에 대한 자세한 내용은 내보내기 가이드를 참조하세요.

  • Ultralytics YOLO26을 사용한 속도 추정의 정확도는 객체 추적의 품질, 비디오의 해상도 및 프레임 속도, 환경 변수 등 여러 요소에 따라 달라집니다. 속도 추정기는 신뢰할 수 있는 추정값을 제공하지만, 프레임 처리 속도의 차이와 객체 가림 현상으로 인해 100% 정확하지 않을 수 있습니다.

    참고: 가능한 경우 항상 오차 범위를 고려하고 추정값을 실측 데이터로 검증하세요.

댓글109

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  1. zwxdlutGitHub

    For estimating the speed of passing through a region, I set the "region" parameter while initializing the speed estimator , as follow:

    region_points = [(20, int(h / 2)), (w - 20, int(h / 2))]                      # line points
    # Initialize speed estimation object
    speedestimator = solutions.SpeedEstimator(
        show=True,  # display the output
        model="runs/detect/train/weights/best.pt",  # path to the model file
        fps=fps,  # adjust speed based on frame per second
        # max_speed=120,  # cap speed to a max value (km/h) to avoid outliers
        # max_hist=5,  # minimum frames object tracked before computing speed
        # meter_per_pixel=0.05,  # highly depends on the camera configuration
        classes=[3, 4, 5],  # estimate speed of specific classes.
        # line_width=2,  # adjust the line width for bounding boxes
        region=region_points,
    )
    ```python
    
    The model was customized trained with the VisDrone dataset.
    The speed estimator estimates each object speed whether it is within the region or not. The parameter "region" doesn't take effect at all.
    
    Has the function "estimating speed in regions" not been implemented yet?
  2. t47352GitHub

    I keep getting this error, whether I use reg_pts or line_pts to define the crossing line:

    "ValueError: reg_pts is not a valid solution argument"

    I was initially using Yolo11 with the code in the "Speed Estimation using Ultralytics YOLO" section on this webpage. Then I noticed that the Youtube video on the webpage was with Yolo8, so I changed the model to yolov8m.pt. Everything works with either model as long as I don't add "reg_points" or "line_pts".

    So I tried to use "region=[(200,0), (200,720)]" instead but that didn't seem to do anything. My goal here is to only record speeds of people moving through a certain area/region of the video, not the speed of everyone in the frame. Could this be achieved?

    (FYI, I do not know how to code at all... I've just been copy/pasting things together and then getting Gemini to help me fix stuff where it can.) Thank you!

    1. Glenn JocherUltralytics

      @t47352 reg_pts/line_pts aren’t valid for YOLO11’s solutions.SpeedEstimator; use the documented args (model, fps, meter_per_pixel, etc.) and call it directly, then read per-ID speeds from speed.spd as shown in the guide and API reference.

      import cv2, numpy as np
      from ultralytics import solutions
      
      cap = cv2.VideoCapture("video.mp4")
      fps = cap.get(cv2.CAP_PROP_FPS)
      
      speed = solutions.SpeedEstimator(model="yolo11n.pt", fps=fps, meter_per_pixel=0.05, show=True)
      
      # Optional ROI filter (only keep speeds for boxes whose centroid is inside this polygon)
      roi = np.array([(200,0),(200,720),(400,720),(400,0)], dtype=np.int32)
      
      while cap.isOpened():
          ok, im0 = cap.read()
          if not ok:
              break
          res = speed(im0)  # processes and annotates frame
          speeds_in_roi = {}
          for box, tid in zip(speed.boxes, speed.track_ids):  # xyxy and track ids from last frame
              x1,y1,x2,y2 = map(float, box)
              cx, cy = (x1+x2)/2, (y1+y2)/2
              if cv2.pointPolygonTest(roi, (cx, cy), False) >= 0 and tid in speed.spd:
                  speeds_in_roi[tid] = speed.spd[tid]  # km/h for objects in your area
      • CLI (no ROI filtering):
      yolo solutions speed source="video.mp4" model=yolo11n.pt meter_per_pixel=0.05 show=True

      For supported arguments and examples see the Speed Estimation guide and the SpeedEstimator API reference: Speed Estimation using Ultralytics YOLO11 and SpeedEstimator class reference. If an error persists, please share the exact command and the output of yolo checks.

  3. NawzHGitHub

    If I were to provide a live video feed from a moving vehicle, with the camera facing out the front window, could the speed estimator track the speeds of vehicles approaching and receding?

    I understand this is possible with a stationary setup, but I am curious if the system can handle the added complexity of movement from the capturing vehicle itself?

    1. Glenn JocherUltralytics

      @NawzH the current Ultralytics YOLO11 Speed Estimator assumes a stationary camera setup for accurate speed estimation. For a moving vehicle, additional considerations such as compensating for the camera's motion using GPS or IMU data would be required. This functionality is not natively supported in our implementation but could potentially be developed with custom modifications.

    2. NawzHGitHub

      Hello Glenn, thank you for your response. I plan to use an OBD reader to capture the speed of the recording vehicle and am also now considering incorporating GPS data to aid in the estimation process.

      Since I am exploring the route of custom modifications, could you kindly point me to any guidance or documentation that might assist with integrating GPS and OBD data into the YOLO speed estimator? Any advice or resources would be greatly appreciated!

    3. Glenn JocherUltralytics

      Thank you for your interest! While we don't have direct documentation on integrating GPS and OBD data into the YOLO speed estimator, a possible approach would involve synchronizing GPS/OBD speed data with object tracking outputs to adjust for the capturing vehicle's motion. You may start by modifying the SpeedEstimator class in ultralytics/solutions/speed_estimation.py to incorporate this additional data.

    1. Glenn JocherUltralytics

      @SourceOfNootmite to use speed estimation for other objects like people, trains, or animals, you can specify the desired object classes by setting the classes argument in the SpeedEstimator. For example, classes=[0] for people or classes=[1, 2] for specific vehicles. Refer to Speed Estimation Documentation for detailed examples. Let me know if you need further clarification!

  4. 1024-ZhangGitHub

    Hello, I want to get the speed of each vehicle detected in the speed estimation method and write the vehicle ID and corresponding speed into a csv file. The speed written in the code below is not the speed of each vehicle detected, but the time taken to reason without a frame in the video. I'm using version 8.1.0 of YOLO.

    speeds = [] tracks = model.track(im0, persist=True, show=False) for track in tracks: speed = speed_obj.estimate_speed(im0, track) if speed is not None: speeds.append(track.speed) im0 = speed_obj.estimate_speed(im0, tracks) video_writer.write(im0)

    1. Glenn JocherUltralytics(수정됨)

      @1024-Zhang to write the detected vehicle ID and speed into a CSV file, use the speeds returned by the current SpeedEstimator in results.speed_dict ({track_id: km/h}) after each frame:

      import csv
      import time
      
      with open("speeds.csv", "w", newline="") as f:
          writer = csv.writer(f)
          writer.writerow(["timestamp", "id", "speed_kmh"])
          # inside your frame loop
          results = speed_obj(im0)
          for track_id, speed in results.speed_dict.items():
              writer.writerow([time.time(), track_id, speed])

      See the Speed Estimation guide for the full setup. Let me know if you need further clarification!

  5. samkitshah18GitHub

    I believe for the code provided in the guide, we get object speed once it enters the region which is not updated further. For my use case, I have a video of a road with cars and for all the cars in the video I want to continuously track/detect speed throughout the video. Is this feasible using solutions.SpeedEstimator ? If yes, can you provide the code snippet/idea behind this ?

    1. Glenn JocherUltralytics(수정됨)

      @samkitshah18 the current solutions.SpeedEstimator computes each tracked object's speed once it has been tracked for max_hist frames, then keeps that speed for the object's ID rather than updating it continuously. If you need continuously updated speeds, you can modify the SpeedEstimator source (ultralytics/solutions/speed_estimation.py) to not lock IDs, or compute speeds yourself from the track history. Keep persist=True tracking so IDs stay consistent. See the Speed Estimation guide for the current arguments. Let us know if you need further clarification!

    2. samkitshah18GitHub(수정됨)

      Thank you for your response ! I tried to implement it.

      My code:

      from ultralytics.solutions import speed_estimation
      import cv2
      
      model = YOLO("yolo11n.pt")
      
      video_path = 'Path'
      cap = cv2.VideoCapture(video_path)
      assert cap.isOpened(), "Error opening video file"
      
      fps = int(cap.get(cv2.CAP_PROP_FPS))
      w, h = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
      video_writer = cv2.VideoWriter("speed_estimation8.mp4", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
      
      speed_obj = speed_estimation.SpeedEstimator(
          region=[(0, 0), (w, 0), (w, h), (0, h)],
          names=model.names,
          show=True,
      )
      
      object_speeds = {}
      
      while cap.isOpened():
          success, img = cap.read()
          if not success:
              break
      
          tracks = model.track(img, persist=True, show=True, tracker="bytetrack.yaml") 
      
          if tracks is not None:
              updated_tracks = []
              for track in tracks:
                  obj_id = track.id if hasattr(track, 'id') else None
                  if obj_id is not None:
                      if obj_id not in object_speeds:
                          object_speeds[obj_id] = []
      
                      if hasattr(track, 'speed'):
                          object_speeds[obj_id].append(track.speed)
      
                      updated_tracks.append(track)
      
              img = speed_obj.estimate_speed(img)
      
          video_writer.write(img)
      
      cap.release()
      video_writer.release()
      cv2.destroyAllWindows()```
      
      Now it detects 0 speed for all the cars even though it tracks and detects cars.
      
      After Speed Detection: https://streamable.com/67n3f4
      
      Can you please point me what am I missing here ?
    3. Glenn JocherUltralytics(수정됨)

      The current SpeedEstimator no longer has a reg_pts argument or a speed region: it estimates the speed of every tracked object across the whole frame, so you don't need to define one. If speeds look wrong, check fps, meter_per_pixel and max_hist against the Speed Estimation guide, and make sure tracking IDs are consistent. Let me know how it goes!

    4. samkitshah18GitHub

      Thank you ! In my use case, I've several videos from varied camera angles so defining the reg_pts is not feasible and I want to track the objects in the entire video and not just a region. Even when I try to narrow down the region, using the persist=True in the above code does not update the speed of vehicles in the above code. Can you please provide any suggestions on how to resolve this ?

    5. Glenn JocherUltralytics(수정됨)

      @samkitshah18 the current SpeedEstimator already tracks speeds across the entire frame without a region, and reg_pts is no longer an argument, so there is nothing to disable. If the speed doesn't update, note that each object's speed is calculated after it has been tracked for max_hist frames and then kept for that ID. Verify that frame-to-frame object IDs are consistent, and tune meter_per_pixel and fps for your video. Let us know if you have further issues!

  6. moshiourGitHub

    Hi,

    I would like to write speed using label box. However, the above script for speed estimation does not work. Even, I have already updated yolo11. Please check the above script in examples and here in discussion not same at all.

    In the example above no tracking : speed_obj = solutions.SpeedEstimator( region=[(0, 360), (1280, 360)], model="yolo11n.pt", show=True, )

    while cap.isOpened(): success, im0 = cap.read() if not success: break im0 = speed_obj.estimate_speed(im0) video_writer.write(im0)

    And in the discussion:

    Init speed-estimation obj

    speed_obj = solutions.SpeedEstimator( reg_pts=line_pts, names=names, view_img=True, )

    while cap.isOpened(): success, im0 = cap.read() if not success: print("Video frame is empty or video processing has been successfully completed.") break

    tracks = model.track(im0, persist=True, show=False)
    
    im0 = speed_obj.estimate_speed(im0, tracks)
    video_writer.write(im0)

    ==============================================

    Thank you in advance!

  7. hardsluggerGitHub

    Hi! I am very glad that you introduced Yolov11 speed estimation module. I am very excited to start working with it. I have a question: Can I estimate speed of the vehicle without drawing the horizontal or vertical line? I am working on speed estimation of vehicles from the images captured by a camera mounted on an autonomous vehicle. Let me know how I can work this out?

    1. Glenn JocherUltralytics(수정됨)

      @hardslugger yes, the current SpeedEstimator doesn't require you to draw lines or regions: reg_pts is no longer an argument. It estimates the speed of every tracked object in the frame, so just set fps and a meter_per_pixel scale that fits your camera's perspective. For more details, visit our speed estimation guide.

  8. eps1lonlineGitHub(수정됨)

    Hi everyone, how can i add to array the speed of the car that passed the line? here is the code

    import os
    import cv2
    import time
    
    from ultralytics import YOLO, solutions
    
    # Запуск таймера
    start_time = time.time()
    
    # Путь, где будет сохранятся файл
    current_directory = os.getcwd()
    print("The resulting file is saved to the path:", current_directory)
    
    # Загрузка модели YOLOv8
    model = YOLO("yolov8n.pt")
    names = model.model.names
    
    # Открытие видеофайла
    videoFile = "car7.mp4"
    cap = cv2.VideoCapture(videoFile)
    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 = cv2.VideoWriter(
        "speed_estimation.avi",
        cv2.VideoWriter_fourcc(*"mp4v"),
        fps, (w, h))
    
    # Определение линии
    line_pts = [(0, int(h/2)), (int(w), int(h/2))]
    
    # Инициализация объекта оценки скорости
    speed_obj = solutions.SpeedEstimator(reg_pts=line_pts,
                                          names=names,
                                          view_img=True,)
    
    speeds = []
    
    while cap.isOpened():
        success, im0 = cap.read()
        if not success:
            break
        tracks = model.track(im0, persist=True, show=False)
        im0 = speed_obj.estimate_speed(im0, tracks)
        video_writer.write(im0)
        
        print(speed_obj.spdl)
            
    
    # Освобождение ресурсов
    cap.release()
    video_writer.release()
    cv2.destroyAllWindows()
    
    # Время работы программы
    end_time = time.time()
    execution_time = end_time - start_time
    print("Program running time:", int(execution_time//60), " min ", int(execution_time%60), " sec")
    1. Glenn JocherUltralytics(수정됨)

      @eps1lonline to add the speed of the car to an array, use the speeds returned by the current SpeedEstimator in results.speed_dict ({track_id: km/h}). Here's a minimal example:

      speeds = {}
      
      while cap.isOpened():
          success, im0 = cap.read()
          if not success:
              break
          results = speed_obj(im0)
          speeds.update(results.speed_dict)  # last known speed per track ID
          video_writer.write(results.plot_im)
      
      print(list(speeds.values()))

      This stores one speed per tracked car.

      -1
    2. eps1lonlineGitHub

      @glenn-jocher, good day.

      I wanted to know the speed of each car in km/h and put it in an array, but after looking at the code, I realized that this is not necessary, because all the speeds of cars can be obtained by accessing the Speed_obj object like this: Speed_obj.spd, we get a dictionary, where the index is the car number, and the value is the speed itself.

      Now I have a couple of other questions:

      1. For movement, we use the formula: U=S/t, where U is the speed of the car; S is the distance traveled by the car; t is time. My object: Speed_obj stores the coordinates along which each car moved, in order to get these coordinates, we must access the object like this: Speed_obj.trk_history. The distance itself is the Euclidean distance, i.e. we find the distance from the starting point to the next point, from this point to another point and so on until we reach the final one. So here's the question, I got that the distance = 600 pixels, how does your model convert pixels into meters, kilometers in order to calculate the speed?

      2. What is Speed_obj.spdl, it stores an array of several dozens that are constantly changing (10, 10, 10, 10, 10, 10...)

      Thank you for your attention!

    3. Glenn JocherUltralytics(수정됨)

      @eps1lonline 1. The solution uses a calibration factor, meter_per_pixel, to convert pixels to real-world meters. You'll need to measure a known distance in the video to set this factor accurately.

      1. speed_obj.spdl belonged to an older version and no longer exists. In the current SpeedEstimator, the speeds are returned in results.speed_dict ({track_id: km/h}) each time you call it on a frame. See the speed estimation guide for details.