以下是关于 Ultralytics 框架中 Predictor
类的作用、参数及使用指南 的详细说明,帮助您高效完成目标检测、分割等任务的推理流程:
Predictor
类的核心作用Predictor
类是 Ultralytics 推理流程的核心模块,负责以下功能:
.pt
、.onnx
、.engine
等格式),并根据任务类型(检测/分割/姿态)初始化对应的网络头。Predictor
类核心参数详解以下为 Predictor
类的主要参数及其配置方法:
参数 | 类型 | 默认值 | 说明 |
---|---|---|---|
source |
str /list |
None |
输入源路径,如 "image.jpg" 、"video.mp4" 、0 (摄像头ID)、URL 或目录路径。 |
conf |
float |
0.25 |
置信度阈值,过滤低于此值的检测框。 |
iou |
float |
0.45 |
NMS 的 IoU 阈值,控制重叠框合并强度。 |
device |
str /list |
None |
推理设备,如 "cpu" 、"cuda:0" 或 [0,1] (多 GPU)。 |
classes |
list[int] |
None |
筛选指定类别,如 [0, 2] 仅检测人和车。 |
imgsz |
int |
640 |
输入图像尺寸,增大可提升小目标检测能力(如 1280 )。 |
half |
bool |
False |
启用 FP16 半精度推理,显存占用减少 40%。 |
stream |
bool |
False |
启用流式处理模式,逐帧处理视频/摄像头输入,减少内存占用。 |
save |
bool |
False |
保存带标注的结果至 runs/detect/predict 目录。 |
show |
bool |
False |
实时显示推理结果(适用于调试)。 |
agnostic_nms |
bool |
False |
跨类别 NMS,合并不同类别重叠框(适用于密集目标)。 |
retina_masks |
bool |
False |
生成高分辨率掩膜(仅实例分割任务有效)。 |
from ultralytics import YOLO
# 加载模型(自动初始化 Predictor)
model = YOLO("yolov8n.pt") # 检测模型
# model = YOLO("yolov8n-seg.pt") # 分割模型
# model = YOLO("yolov8n-pose.pt") # 姿态模型
# 执行推理
results = model.predict(
source="image.jpg",
conf=0.5, # 过滤低置信度检测
iou=0.5, # 调整重叠框合并强度
save=True, # 保存结果
show=True, # 实时显示
device="cuda:0" # 使用 GPU 0
)
# 处理视频文件(启用流式模式)
for result in model.predict(source="video.mp4", stream=True):
# 逐帧访问结果
boxes = result.boxes.xyxy # 检测框坐标
print(f"当前帧检测到 {len(boxes)} 个目标")
result.save("output_frame.jpg") # 保存当前帧结果
import threading
def process_frame(frame):
results = model.predict(frame, device="cuda:0", verbose=False)
return results[0].plot()
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
# 使用多线程加速
thread = threading.Thread(target=process_frame, args=(frame,))
thread.start()
if cv2.waitKey(1) == ord("q"):
break
for result in results:
# 检测框信息
boxes = result.boxes.xyxy # 坐标(左上右下格式)
confs = result.boxes.conf # 置信度列表
cls_ids = result.boxes.cls # 类别ID列表
# 实例分割掩膜
if result.masks:
masks = result.masks.data # 掩膜张量
mask_polygons = result.masks.xy # 多边形坐标
# 姿态估计关键点
if result.keypoints:
keypoints = result.keypoints.xy # 关键点坐标
from ultralytics.engine.results import Results
class CustomResults(Results):
def my_postprocess(self):
# 自定义后处理逻辑(如特殊过滤规则)
return processed_data
# 重写 Predictor 结果类
model.predictor.model.Results = CustomResults
results = model.predict("image.jpg")
# 导出为 TensorRT 格式
model.export(format="engine", device=0, half=True)
# 加载并推理
trt_model = YOLO("yolov8n.engine")
results = trt_model.predict("image.jpg")
# 批量推理多张图像(提升 GPU 利用率)
results = model.predict(["img1.jpg", "img2.jpg"], batch=16)
问题 | 解决方案 |
---|---|
显存不足(OOM) | 减小 batch → 启用 half=True → 降低 imgsz 。 |
视频处理卡顿 | 启用 stream=True → 使用 rect=True 减少填充。 |
检测框漏检 | 降低 conf → 检查数据集标注质量 → 增大 imgsz 。 |
结果保存失败 | 检查输出目录权限 → 使用绝对路径(如 save="/home/output" )。 |
通过灵活配置 Predictor
参数,您可以高效完成从简单图像检测到实时视频分析的复杂任务。更多细节可参考 Ultralytics 官方文档。
参考: