使用 ultralytics 摄像头yolo推理
官方网站
https://docs.ultralytics.com/
github
https://github.com/ultralytics/ultralytics
搭建环境
bash
# Install the ultralytics package using conda
conda install -c conda-forge ultralytics
linux下摄像头推理
python
import cv2
from ultralytics import YOLO
import time
# 加载轻量级模型,并指定较小的图像尺寸以提高速度
model = YOLO('yolov8n.pt') # 或者根据实际情况选择其他轻量模型
IMG_SIZE = 320 # 调整输入图像尺寸
cap = cv2.VideoCapture(0)
prev_time = 0
curr_time = 0
fps = 0
while True:
ret, frame = cap.read()
if not ret:
print("未能成功获取视频帧,退出...")
break
# 缩放图像以减小推理负担
frame = cv2.resize(frame, (IMG_SIZE, IMG_SIZE))
curr_time = time.time()
fps = 1 / (curr_time - prev_time)
prev_time = curr_time
results = model(frame)
annotated_frame = results[0].plot()
cv2.putText(annotated_frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.imshow('YOLO Real-Time Detection with FPS', annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()