概述
Ultralytics提供了一系列的解決方案,利用YOLO11解決現實世界的問題,包括物體計數、模糊處理、熱力圖、安防系統、速度估計、物體追蹤等多個方面的應用。
測量兩個物體之間的間距被稱為特定空間內的距離計算,YOLO11使用兩個邊界框的中心點計算距離。
使用距離計算,可以提供計算機視覺任務中比較精確的空間定位,分析視頻環境中的對象關系,通過監控移動物體之間的距離,使系統能夠檢測到潛在的碰撞,為自動駕駛或者交通監控等應用提供更好的空間場景理解能力。
演示代碼
Ultralytics提供了演示代碼,展示如何使用距離計算解決方案。
import cv2from ultralytics import solutionscap = cv2.VideoCapture("path/to/video.mp4")
assert cap.isOpened(), "Error reading video file"# Video writer
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))# Initialize distance calculation object
distancecalculator = solutions.DistanceCalculation(model="yolo11n.pt", # path to the YOLO11 model file.show=True, # display the output
)# Process video
while cap.isOpened():success, im0 = cap.read()if not success:print("Video frame is empty or processing is complete.")breakresults = distancecalculator(im0)print(results) # access the outputvideo_writer.write(results.plot_im) # write the processed frame.cap.release()
video_writer.release()
cv2.destroyAllWindows() # destroy all opened windows
DistanceCalculation
參數
基本參數
參數 | 類型 | 默認值 | 說明 |
---|---|---|---|
model | str | None | Ultralytics YOLO 模型文件的路徑。 |
DistanceCalculation
支持使用track參數:
參數 | 類型 | 默認值 | 說明 |
---|---|---|---|
tracker | str | 'botsort.yaml' | 指定要使用的跟蹤算法, bytetrack.yaml 或 botsort.yaml . |
conf | float | 0.3 | 設置檢測的置信度閾值;數值越低,跟蹤的物體越多,但可能會出現誤報。 |
iou | float | 0.5 | 設置交叉重疊 (IoU) 閾值,用于過濾重疊檢測。 |
classes | list | None | 按類別索引篩選結果。例如 classes=[0, 2, 3] 只跟蹤指定的類別(class在COCO數據集定義)。 |
verbose | bool | True | 控制跟蹤結果的顯示,提供被跟蹤物體的可視化輸出。 |
device | str | None | 指定用于推理的設備(例如: cpu , cuda:0 或 0 ). 允許用戶選擇CPU 、特定GPU 或其他計算設備運行模型。 |
可視化參數:
參數 | 類型 | 默認值 | 說明 |
---|---|---|---|
show | bool | False | 如果 True 在一個窗口中顯示注釋的圖像或視頻。有助于在開發或測試過程中提供即時視覺反饋。 |
line_width | None or int | None | 指定邊界框的線寬。如果 None 則根據圖像大小自動調整線寬,使圖像更加清晰。 |
show_conf | bool | True | 在標簽旁顯示每次檢測的置信度得分。讓人了解模型對每次檢測的確定性。 |
show_labels | bool | True | 在可視輸出中顯示每次檢測的標簽。讓用戶立即了解檢測到的物體。 |
工作原理
DistanceCalculation
類的工作原理是跟蹤視頻幀中的物體,并計算所選邊界框中心點之間的歐氏距離。演示程序運行時,鼠標點擊斷定兩個邊界框,系統將提取選定邊界框的中心點,以像素為單位計算這些中心點之間的歐氏距離,對象之間用連線連接,并在圖像上顯示距離。
執行時使用 mouse_event_for_distance
方法來處理鼠標交互,允許用戶根據需要選擇對象和清除選擇。 process
方法處理逐幀處理、跟蹤物體和計算距離。
查看DistanceCalculation
類中的mouse_event_for_distance
的代碼:
def mouse_event_for_distance(self, event, x, y, flags, param):"""處理鼠標事件,在實時視頻流中選擇區域計算距離使用左鍵選擇兩個方框點擊右鍵取消選擇"""if event == cv2.EVENT_LBUTTONDOWN:self.left_mouse_count += 1if self.left_mouse_count <= 2:for box, track_id in zip(self.boxes, self.track_ids):if box[0] < x < box[2] and box[1] < y < box[3] and track_id not in self.selected_boxes:self.selected_boxes[track_id] = boxelif event == cv2.EVENT_RBUTTONDOWN:self.selected_boxes = {}self.left_mouse_count = 0
查看DistanceCalculation
類中的process
的代碼:
def process(self, im0):"""處理一個視頻幀,計算兩個選擇的邊界框之間的距離輸出處理過的視頻圖片(疊加了距離數據)、跟蹤物體的數量、像素距離"""self.extract_tracks(im0) # Extract tracksannotator = SolutionAnnotator(im0, line_width=self.line_width) # Initialize annotatorpixels_distance = 0# Iterate over bounding boxes, track ids and classes indexfor box, track_id, cls, conf in zip(self.boxes, self.track_ids, self.clss, self.confs):annotator.box_label(box, color=colors(int(cls), True), label=self.adjust_box_label(cls, conf, track_id))# 如果選定的框是被跟蹤的,則更新if len(self.selected_boxes) == 2:for trk_id in self.selected_boxes.keys():if trk_id == track_id:self.selected_boxes[track_id] = boxif len(self.selected_boxes) == 2:#計算選擇框的中心點坐標self.centroids.extend([[int((box[0] + box[2]) // 2), int((box[1] + box[3]) // 2)] for box in self.selected_boxes.values()])#計算兩點間的歐氏距離pixels_distance = math.sqrt((self.centroids[0][0] - self.centroids[1][0]) ** 2 + (self.centroids[0][1] - self.centroids[1][1]) ** 2)annotator.plot_distance_and_line(pixels_distance, self.centroids)self.centroids = [] # Reset centroids for next frameplot_im = annotator.result()self.display_output(plot_im) # Display output with base class functioncv2.setMouseCallback("Ultralytics Solutions", self.mouse_event_for_distance)# 返回處理過的圖像和計算的指標return SolutionResults(plot_im=plot_im, pixels_distance=pixels_distance, total_tracks=len(self.track_ids))
效果展示
這里使用演示代碼,在測試視頻中,計算兩輛車的距離。
隨著車輛運動,其距離在不斷變化。
需要注意的是,本方案的距離計算并不精確,它只是使用了平面數據,缺少物體間的深度信息(不能計算三維位置關系)。