Appearance
模型训练 (使用训练好的模型)
🏞 单张图片推理
python
from ultralytics import YOLO
model = YOLO("runs/train/my_yolo26_exp/weights/best.pt")
results = model("path/to/test_image.jpg")
for result in results:
boxes = result.boxes
for box in boxes:
cls_id = int(box.cls[0]) # 类别 ID
cls_name = result.names[cls_id] # 类别名称
confidence = float(box.conf[0]) # 置信度
x1, y1, x2, y2 = box.xyxy[0].tolist() # 边界框坐标
print(f"检测到: {cls_name}, 置信度: {confidence:.2f}, 坐标: ({x1:.0f},{y1:.0f})-({x2:.0f},{y2:.0f})")
result.show() # 显示结果图片
result.save() # 保存结果到 runs/detect/predict/🗂 批量图片推理
python
from ultralytics import YOLO
model = YOLO("runs/train/my_yolo26_exp/weights/best.pt")
results = model(
source="path/to/test_images/", # 图片目录
conf=0.5, # 置信度阈值
iou=0.45, # IoU 阈值(使用 one-to-many 头部时)
save=True, # 保存结果图片
save_txt=True, # 保存检测结果 txt
)🎞 视频推理
python
from ultralytics import YOLO
model = YOLO("runs/train/my_yolo26_exp/weights/best.pt")
results = model(
source="path/to/video.mp4",
conf=0.5,
save=True, # 保存标注后的视频
stream=True, # 流式处理,节省内存
)
for result in results:
pass # 逐帧处理📹 摄像头实时推理
python
from ultralytics import YOLO
model = YOLO("runs/train/my_yolo26_exp/weights/best.pt")
results = model(
source=0, # 0 表示默认摄像头
conf=0.5,
show=True, # 实时显示窗口
stream=True,
)
for result in results:
pass⌨️ 命令行推理
python
# 单张图片
yolo detect predict model=runs/train/my_yolo26_exp/weights/best.pt source=test.jpg conf=0.5
# 图片目录
yolo detect predict model=runs/train/my_yolo26_exp/weights/best.pt source=test_images/ conf=0.5 save=True
# 视频
yolo detect predict model=runs/train/my_yolo26_exp/weights/best.pt source=video.mp4 conf=0.5 save=True↔️ 双头架构切换
YOLO26 支持两种推理头:
python
model = YOLO("runs/train/my_yolo26_exp/weights/best.pt")
# One-to-One 头(默认):端到端,无需 NMS,速度更快
results = model.predict("image.jpg")
# One-to-Many 头:需要 NMS 后处理,精度略高
results = model.predict("image.jpg", end2end=False)