import queue
import cv2
import threading
import time
from ultralytics import YOLO # 确保安装了 ultralytics (pip install ultralytics)
def process_video(video_path, model, window_name, result_queue):
"""
拉取视频帧,输入 YOLO 模型进行检测,并计算处理的 FPS。
:param video_path: 视频路径
:param model: YOLO 模型对象
:param window_name: 显示窗口名称
"""
global boxes
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"无法打开视频: {video_path}")
return
frame_count = 0
start_time = time.time()
while True:
ret, frame = cap.read()
if not ret:
print(f"视频结束: {video_path}")
break
# 使用 YOLO 模型进行检测
results = model.predict(frame, conf=0.5)
# 提取检测结果
for result in results: # 遍历每一帧(如果是视频)
boxes = result.boxes.data # 获取检测框信息
result_queue.put((window_name, frame_count, boxes))
print("Thread results:", result_queue.get())
# YOLO 检测
annotated_frame = results[0].plot() # 获取标注后的帧
# 计算 FPS
elapsed_time = time.time() - start_time
fps = frame_count / elapsed_time if elapsed_time > 0 else 0
text = " FPS:" + f"{fps:.2f}"
cv2.putText(annotated_frame,text, (0,50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), thickness=None, lineType=None, bottomLeftOrigin=None)
# 显示检测结果
cv2.imshow(window_name, annotated_frame)
# 统计帧数
frame_count += 1
# 按下 'q' 键退出播放
if cv2.waitKey(20) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyWindow(window_name)
def main():
# 结果队列
result_queue = queue.Queue()
# 加载 YOLO 模型
model = YOLO("yolov8n.pt") # 使用 YOLOv8 预训练模型
# 视频路径
video1 = r"C:\Users\Administrator\Desktop\1.mp4"
video2 = r"C:\Users\Administrator\Desktop\2.mp4"
# video3 = r"C:\Users\Administrator\Desktop\1.mp4"
# video4 = r"C:\Users\Administrator\Desktop\2.mp4"
# video5 = r"C:\Users\Administrator\Desktop\1.mp4"
# video6 = r"C:\Users\Administrator\Desktop\2.mp4"
# 创建线程
thread1 = threading.Thread(target=process_video, args=(video1, model, "Video 1", result_queue))
thread2 = threading.Thread(target=process_video, args=(video2, model, "Video 2", result_queue))
# thread3 = threading.Thread(target=process_video, args=(video3, model, "Video 3", result_queue))
# thread4 = threading.Thread(target=process_video, args=(video4, model, "Video 4", result_queue))
# thread5 = threading.Thread(target=process_video, args=(video5, model, "Video 5", result_queue))
# thread6 = threading.Thread(target=process_video, args=(video6, model, "Video 6", result_queue))
# 启动线程
thread1.start()
thread2.start()
# thread3.start()
# thread4.start()
# thread5.start()
# thread6.start()
# 等待线程结束
thread1.join()
thread2.join()
# thread3.join()
# thread4.join()
# thread5.join()
# thread6.join()
# 销毁所有窗口
cv2.destroyAllWindows()
if __name__ == "__main__":
main()
yolov8模拟同时推理多路视频,并计算fps,1080ti两路视频基本在15FPS
于 2024-11-22 16:04:20 首次发布