Ước tính tốc độ bằng Ultralytics YOLO26
Ước tính tốc độ là gì?#
Ước tính tốc độ là quá trình tính tốc độ di chuyển của một đối tượng trong bối cảnh nhất định, thường được sử dụng trong các ứng dụng thị giác máy tính. Với Ultralytics YOLO26, bạn có thể tính tốc độ đối tượng bằng cách kết hợp theo dõi đối tượng với dữ liệu khoảng cách và thời gian, hữu ích cho các tác vụ như giám sát giao thông và an ninh.
Xem: Ước tính tốc độ bằng Ultralytics YOLO26
Ưu điểm của việc ước tính tốc độ#
- Điều khiển giao thông hiệu quả: Ước tính tốc độ chính xác giúp quản lý lưu lượng giao thông, tăng cường an toàn và giảm ùn tắc trên đường.
- Điều hướng tự động chính xác: Trong các hệ thống tự động như ô tô tự lái, việc ước tính tốc độ đáng tin cậy đảm bảo phương tiện điều hướng an toàn và chính xác.
- Tăng cường an ninh giám sát: Ước tính tốc độ trong phân tích giám sát giúp xác định hành vi bất thường hoặc các mối đe dọa tiềm ẩn, nâng cao hiệu quả của các biện pháp an ninh.
Ứng dụng thực tế#
| Giao thông vận tải | Giao thông vận tải |
|---|---|
![]() | ![]() |
| Ước tính tốc độ trên đường bằng Ultralytics YOLO26 | Ước tính tốc độ trên cầu bằng Ultralytics YOLO26 |
Tốc độ chỉ là giá trị ước tính
Tốc độ là giá trị ước tính và có thể không hoàn toàn chính xác. Kết quả cũng thay đổi tùy theo thông số camera và các yếu tố liên quan.
Ước tính tốc độ với YOLO26#
Giải pháp SpeedEstimator theo dõi từng đối tượng qua các frame và chuyển đổi độ dịch chuyển theo pixel thành tốc độ bằng cách sử dụng tốc độ khung hình video (fps) và tỷ lệ theo kích thước thực tế (meter_per_pixel). Điều chỉnh meter_per_pixel cho phù hợp với cấu hình camera của bạn và sử dụng max_speed để giới hạn các giá trị ngoại lai từ những track nhiễu.
# 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.05Các đối số của SpeedEstimator#
Dưới đây là bảng các đối số của SpeedEstimator:
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
model | str | None | Đường dẫn đến tệp model Ultralytics YOLO. |
fps | float | 30.0 | Số khung hình mỗi giây được dùng để tính tốc độ. |
max_hist | int | 5 | Số điểm lịch sử tối đa cần theo dõi cho mỗi đối tượng để tính tốc độ/hướng di chuyển. |
meter_per_pixel | float | 0.05 | Hệ số tỷ lệ dùng để chuyển đổi khoảng cách pixel sang đơn vị thực tế. |
max_speed | int | 120 | Tốc độ tối đa tính bằng km/h; các tốc độ ước tính cao hơn sẽ bị giới hạn ở giá trị này. |
line_width | int | 2 | Độ dày đường viền của box, keypoint và số đếm mà giải pháp vẽ. |
verbose | bool | True | Bậ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ý. |
Giải pháp SpeedEstimator cho phép sử dụng các tham số track:
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
tracker | str | '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. |
conf | float | 0.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ả. |
iou | float | 0.5 | Đặt ngưỡng Intersection over Union (IoU) để lọc các đối tượng phát hiện bị chồng lấn. |
classes | list | None | Lọ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. |
device | str | None | Chỉ đị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. |
imgsz | int or tuple | 640 | Kí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_det | int | 300 | Số 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. |
quantize | int or str | None | Độ 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ác tùy chọn trực quan hóa sau đây cũng được hỗ trợ:
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
show | bool | False | Nế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_labels | bool | True | Hiể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. |
Câu hỏi thường gặp#
Ước tính tốc độ đối tượng bằng Ultralytics YOLO26 kết hợp phát hiện đối tượng và theo dõi. Model phát hiện đối tượng trong từng frame, theo dõi chúng qua các frame và chuyển đổi quãng đường di chuyển giữa các frame thành tốc độ dựa trên tốc độ khung hình và tỷ lệ
meter_per_pixel. Ví dụ Python ở trên chạy toàn bộ quy trình này — truyền video của bạn vào và điều chỉnhmeter_per_pixelcho phù hợp với camera. Để tìm hiểu thêm thông tin nền tảng, hãy tham khảo bài viết chính thức trên blog của chúng tôi.Sử dụng Ultralytics YOLO26 để ước tính tốc độ mang lại những lợi ích đáng kể trong quản lý giao thông:
- Tăng cường an toàn: Ước tính chính xác tốc độ phương tiện để phát hiện tình trạng chạy quá tốc độ và cải thiện an toàn đường bộ.
- Giám sát theo thời gian thực: Tận dụng khả năng phát hiện đối tượng theo thời gian thực của YOLO26 để giám sát hiệu quả lưu lượng giao thông và tình trạng ùn tắc.
- Khả năng mở rộng: Triển khai model trên nhiều cấu hình phần cứng khác nhau, từ thiết bị biên đến máy chủ, đảm bảo các giải pháp linh hoạt và có khả năng mở rộng cho những triển khai quy mô lớn.
Để xem thêm ứng dụng, hãy tham khảo ưu điểm của việc ước tính tốc độ.
Có. YOLO26 được xây dựng trên PyTorch, và Ultralytics hỗ trợ xuất model YOLO26 sang các định dạng như ONNX, TensorRT, CoreML và SavedModel của TensorFlow để tương tác với các framework ML khác.
Để xuất model YOLO26 sang định dạng ONNX:
yolo export model=yolo26n.pt format=onnxTìm hiểu thêm về cách xuất model trong hướng dẫn xuất model của chúng tôi.
Độ chính xác của việc ước tính tốc độ bằng Ultralytics YOLO26 phụ thuộc vào một số yếu tố, bao gồm chất lượng theo dõi đối tượng, độ phân giải và tốc độ khung hình của video, cũng như các biến số môi trường. Mặc dù bộ ước tính tốc độ đưa ra các kết quả đáng tin cậy, nhưng kết quả có thể không chính xác 100% do sự khác biệt về tốc độ xử lý frame và hiện tượng che khuất đối tượng.
Lưu ý: Luôn tính đến biên sai số và xác thực các kết quả ước tính bằng dữ liệu ground truth khi có thể.
Bình luận109
Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.
zwxdlut
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?t47352
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!
Glenn JocherUltralytics@t47352
reg_pts/line_ptsaren’t valid for YOLO11’ssolutions.SpeedEstimator; use the documented args (model,fps,meter_per_pixel, etc.) and call it directly, then read per-ID speeds fromspeed.spdas 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=TrueFor 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.
greviewer-edt
Buen día, podrias compartir por favor los link de los videos que estan en este articulo porfa
NawzH
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?
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.
NawzH
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!
Glenn JocherUltralyticsThank 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
SpeedEstimatorclass inultralytics/solutions/speed_estimation.pyto incorporate this additional data.
SourceOfNootmite
Hi how can I use this for other objects of interest like people, trains, animals, etc. Thanks.
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
classesargument in theSpeedEstimator. For example,classes=[0]for people orclasses=[1, 2]for specific vehicles. Refer to Speed Estimation Documentation for detailed examples. Let me know if you need further clarification!
1024-Zhang
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)
Glenn JocherUltralytics(đã chỉnh sửa)@1024-Zhang to write the detected vehicle ID and speed into a CSV file, use the speeds returned by the current
SpeedEstimatorinresults.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!
samkitshah18
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 ?
Glenn JocherUltralytics(đã chỉnh sửa)@samkitshah18 the current
solutions.SpeedEstimatorcomputes each tracked object's speed once it has been tracked formax_histframes, then keeps that speed for the object's ID rather than updating it continuously. If you need continuously updated speeds, you can modify theSpeedEstimatorsource (ultralytics/solutions/speed_estimation.py) to not lock IDs, or compute speeds yourself from the track history. Keeppersist=Truetracking so IDs stay consistent. See the Speed Estimation guide for the current arguments. Let us know if you need further clarification!samkitshah18(đã chỉnh sửa)
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 ?
Glenn JocherUltralytics(đã chỉnh sửa)The current
SpeedEstimatorno longer has areg_ptsargument 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, checkfps,meter_per_pixelandmax_histagainst the Speed Estimation guide, and make sure tracking IDs are consistent. Let me know how it goes!samkitshah18
Thank you ! In my use case, I've several videos from varied camera angles so defining the
reg_ptsis 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 thepersist=Truein 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 ?
Glenn JocherUltralytics(đã chỉnh sửa)@samkitshah18 the current
SpeedEstimatoralready tracks speeds across the entire frame without a region, andreg_ptsis 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 formax_histframes and then kept for that ID. Verify that frame-to-frame object IDs are consistent, and tunemeter_per_pixelandfpsfor your video. Let us know if you have further issues!
moshiour
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!
Glenn JocherUltralytics@moshiour thank you for your comment. It seems there might be a discrepancy between the examples. Please ensure you're using the correct tracking setup as shown in the discussion. For detailed guidance, refer to our speed estimation documentation at https://docs.ultralytics.com/guides/speed-estimation/. If you have further questions, feel free to ask here.
moshiour
@glenn-jocher Thanks for clearification!
hardslugger
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?
Glenn JocherUltralytics(đã chỉnh sửa)@hardslugger yes, the current
SpeedEstimatordoesn't require you to draw lines or regions:reg_ptsis no longer an argument. It estimates the speed of every tracked object in the frame, so just setfpsand ameter_per_pixelscale that fits your camera's perspective. For more details, visit our speed estimation guide.
eps1lonline(đã chỉnh sửa)
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")
Glenn JocherUltralytics(đã chỉnh sửa)@eps1lonline to add the speed of the car to an array, use the speeds returned by the current
SpeedEstimatorinresults.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.
-1eps1lonline
@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:
-
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?
-
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!
-
Glenn JocherUltralytics(đã chỉnh sửa)@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.speed_obj.spdlbelonged to an older version and no longer exists. In the currentSpeedEstimator, the speeds are returned inresults.speed_dict({track_id: km/h}) each time you call it on a frame. See the speed estimation guide for details.

