前言 YOLO(You Only Look Once)是目标检测领域最知名的模型系列。它能在一张图中同时检测出多个物体——人、车、猫、杯子——标出位置并给出类别名称。
这篇文章的目标是让你半小时内从零到跑通第一个 YOLO 检测程序。
一、YOLO 是什么 YOLO 的核心思想很简单:只看一次 。传统检测方法需要对图片反复扫描(滑动窗口),YOLO 把整张图一次性输入神经网络,直接输出”哪个位置有什么物体,置信度多高”。
版本演进
版本
年份
关键变化
YOLOv5
2020
第一个工程化完善的版本,部署友好
YOLOv8
2023
Ultralytics 出品,支持检测/分割/分类/姿态估计/跟踪多任务
YOLOv9
2024
引入 PGI 和 GELAN,精度提升明显
YOLOv10
2024
清华团队出品,NMS-free,推理更快
YOLOv11
2024
当前最新,精度和速度的最佳平衡
YOLOv12
2025
引入注意力机制,小目标检测更好
新手推荐直接用 YOLOv8 或 YOLOv11 ,Ultralytics 库把训练、推理、导出的接口封装得非常统一。
二、安装与环境
验证安装:
1 2 from ultralytics import YOLOprint (YOLO.__doc__[:50 ])
如果安装了 CUDA 版本的 PyTorch,YOLO 会自动使用 GPU 加速。检查是否能用 GPU:
1 2 3 import torchprint (f"CUDA 可用: {torch.cuda.is_available()} " )print (f"设备数量: {torch.cuda.device_count()} " )
三、5 行代码跑检测 1 2 3 4 5 6 7 8 9 10 11 12 13 from ultralytics import YOLOimport cv2model = YOLO("yolo11n.pt" ) results = model("bus.jpg" ) for r in results: r.show() r.save("output.jpg" )
模型大小选择:
后缀
大小
速度
适用场景
n (nano)
~6MB
最快
移动端、实时检测
s (small)
~21MB
快
资源有限的设备
m (medium)
~49MB
中等
通用场景,平衡之选
l (large)
~83MB
慢
精度要求高
x (x-large)
~116MB
最慢
追求最高精度
1 2 3 model = YOLO("yolo11n.pt" ) model = YOLO("yolo11m.pt" ) model = YOLO("yolo11x.pt" )
四、解析检测结果 1 2 3 4 5 6 7 8 9 10 11 12 13 results = model("street.jpg" ) for r in results: boxes = r.boxes if boxes is not None : for box in boxes: x1, y1, x2, y2 = box.xyxy[0 ].tolist() confidence = box.conf[0 ].item() class_id = int (box.cls[0 ].item()) class_name = r.names[class_id] print (f"{class_name} : {confidence:.2 f} @ ({x1:.0 f} ,{y1:.0 f} )-({x2:.0 f} ,{y2:.0 f} )" )
输出示例:
1 2 3 4 person: 0.95 @ (120,50)-(380,450) car: 0.92 @ (30,200)-(280,400) traffic light: 0.88 @ (450,80)-(480,120) car: 0.76 @ (400,210)-(600,380)
results 对象的主要属性:
属性
说明
results[0].boxes
检测框(xyxy 坐标、置信度、类别)
results[0].masks
分割掩码(分割任务)
results[0].keypoints
关键点(姿态估计)
results[0].probs
分类概率(分类任务)
results[0].names
类别名映射 {0: ‘person’, 1: ‘car’, …}
五、视频和摄像头实时检测 1 2 3 4 5 6 7 8 9 10 11 12 model = YOLO("yolo11n.pt" ) results = model("traffic.mp4" , stream=True ) for r in results: annotated_frame = r.plot() cv2.imshow("Detection" , annotated_frame) if cv2.waitKey(1 ) & 0xFF == ord ('q' ): break cv2.destroyAllWindows()
1 2 3 4 5 6 model = YOLO("yolo11n.pt" ) results = model(source=0 , show=True , stream=True ) for r in results: pass
把检测结果写入视频文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from ultralytics import YOLOimport cv2model = YOLO("yolo11n.pt" ) cap = cv2.VideoCapture("input.mp4" ) fps = int (cap.get(cv2.CAP_PROP_FPS)) w = int (cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int (cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) writer = cv2.VideoWriter("output.mp4" , cv2.VideoWriter_fourcc(*'mp4v' ), fps, (w, h)) while cap.isOpened(): ret, frame = cap.read() if not ret: break results = model(frame) annotated = results[0 ].plot() writer.write(annotated) cap.release() writer.release()
六、让 YOLO 只检测特定类别 COCO 数据集(预训练模型默认的类别集)有 80 个类别,如果只关心其中几个:
1 2 3 4 results = model(source="street.jpg" , classes=[0 , 2 ], conf=0.5 )
COCO 常用类别 ID 对照:
ID
类别
ID
类别
0
person
39
bottle
2
car
56
chair
3
motorcycle
63
laptop
5
bus
67
cell phone
7
truck
73
book
15
cat
77
scissors
16
dog
七、模型的导出与部署 训练/选好模型后,需要导出为推理框架可用的格式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 model = YOLO("yolo11n.pt" ) model.export(format ="onnx" ) model.export(format ="engine" , device=0 ) model.export(format ="openvino" ) model.export(format ="ncnn" ) model.export(format ="tflite" )
导出后用对应框架加载推理,不需要 Ultralytics 库:
1 2 3 4 5 6 import onnxruntime as ortimport numpy as npsession = ort.InferenceSession("yolo11n.onnx" )
八、YOLO 还能做什么 Ultralytics 把 YOLO 做成了多任务模型,同一个架构支持多种视觉任务:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 model = YOLO("yolo11n-seg.pt" ) results = model("street.jpg" ) model = YOLO("yolo11n-cls.pt" ) results = model("cat.jpg" ) print (f"类别: {results[0 ].probs.top1} " )model = YOLO("yolo11n-pose.pt" ) results = model("people.jpg" ) model = YOLO("yolo11n.pt" ) results = model.track("traffic.mp4" , persist=True )
九、一些实践经验
预训练模型比你想象的好 :COCO 预训练模型覆盖了 80 个常见类别,很多场景不需要自己训练
根据场景选模型大小 :移动端用 n/s,服务器用 m/l,精度评估用 x
调 conf 参数能大幅减少误检 :默认 0.25,实际场景可以设到 0.4~0.6
GPU 不是必须的 :YOLO11n 在 CPU 上处理一张图片大约 100~300ms,简单的实时场景也能用
先看别人训练好的 :模型仓库(Hugging Face、Roboflow Universe)上有大量针对特定场景训练的 YOLO 模型
以上是 YOLO 的入门操作。下一篇会讲如何用自己的数据训练一个定制的目标检测模型——从数据标注到模型上线。