Link to this sectionPython 使用#
欢迎阅读 Ultralytics YOLO Python 使用文档!本指南旨在帮助你将 Ultralytics YOLO 无缝集成到你的 Python 项目中,用于目标检测、实例分割、语义分割和分类。在此,你将学习如何加载和使用预训练模型、训练新模型以及对图像进行预测。这个易于使用的 Python 接口对于任何希望将 YOLO 整合到 Python 项目中的人来说都是宝贵的资源,它能让你快速实现高级目标检测功能。让我们开始吧!
Watch: Mastering Ultralytics YOLO: Python
例如,用户只需几行代码即可加载模型、进行训练、在验证集上评估其性能,甚至将其导出为 ONNX 格式。
from ultralytics import YOLO
# Create a new YOLO model from scratch
model = YOLO("yolo26n.yaml")
# Load a pretrained YOLO model (recommended for training)
model = YOLO("yolo26n.pt")
# Train the model using the 'coco8.yaml' dataset for 3 epochs
results = model.train(data="coco8.yaml", epochs=3)
# Evaluate the model's performance on the validation set
results = model.val()
# Perform object detection on an image using the model
results = model("https://ultralytics.com/images/bus.jpg")
# Export the model to ONNX format
success = model.export(format="onnx")Link to this section训练#
训练模式 (Train mode) 用于在自定义数据集上训练 YOLO 模型。在此模式下,模型使用指定的数据集和超参数进行训练。训练过程包括优化模型的参数,以便它能够准确预测图像中对象的类别和位置。
from ultralytics import YOLO
model = YOLO("yolo26n.pt") # pass any model type
results = model.train(epochs=5)Link to this section验证#
验证模式 (Val mode) 用于在训练完成后验证 YOLO 模型。在此模式下,模型会在验证集上进行评估,以衡量其准确率和泛化性能。该模式可用于调整模型的超参数以提高性能。
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo26n.yaml")
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate on training data
model.val()Link to this section预测#
预测模式 (Predict mode) 用于使用训练好的 YOLO 模型对新图像或视频进行预测。在此模式下,模型从检查点文件加载,用户可以提供图像或视频进行推理。模型会预测输入图像或视频中对象的类别和位置。
import cv2
from PIL import Image
from ultralytics import YOLO
model = YOLO("model.pt")
# accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam
results = model.predict(source="0")
results = model.predict(source="folder", show=True) # Display preds. Accepts all YOLO predict arguments
# from PIL
im1 = Image.open("bus.jpg")
results = model.predict(source=im1, save=True) # save plotted images
# from ndarray
im2 = cv2.imread("bus.jpg")
results = model.predict(source=im2, save=True, save_txt=True) # save predictions as labels
# from list of PIL/ndarray
results = model.predict(source=[im1, im2])Link to this section导出#
导出模式 (Export mode) 用于将 YOLO 模型导出为可用于部署的格式。在此模式下,模型会被转换为可供其他软件应用程序或硬件设备使用的格式。此模式在将模型部署到生产环境时非常有用。
将官方 YOLO 模型导出为带有动态 batch-size 和 image-size 的 ONNX 格式。
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.export(format="onnx", dynamic=True)Link to this section追踪#
追踪模式 (Track mode) 用于使用 YOLO 模型实时追踪对象。在此模式下,模型从检查点文件加载,用户可以提供实时视频流进行实时对象追踪。该模式适用于监控系统或自动驾驶汽车等应用。
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.pt") # load an official detection model
model = YOLO("yolo26n-seg.pt") # load an official segmentation model
model = YOLO("path/to/best.pt") # load a custom model
# Track with the model
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")Link to this section基准测试#
基准测试模式 (Benchmark mode) 用于分析各种 YOLO 导出格式的速度和准确性。基准测试提供有关导出格式大小、其 mAP50-95 指标(用于目标检测和分割)或 accuracy_top1 指标(用于分类)以及在 ONNX、OpenVINO、TensorRT 等各种导出格式下每张图像的推理时间(毫秒)的信息。这些信息可以帮助用户根据其对速度和准确性的要求,为特定用例选择最佳的导出格式。
对官方 YOLO 模型进行全导出格式基准测试。
from ultralytics.utils.benchmarks import benchmark
# Benchmark
benchmark(model="yolo26n.pt", data="coco8.yaml", imgsz=640, half=False, device=0)Link to this section使用 Trainer#
YOLO 模型类充当了 Trainer 类的高级封装。每个 YOLO 任务都有其自己的 Trainer,该 Trainer 继承自 BaseTrainer。这种架构允许你在机器学习工作流中获得更大的灵活性和定制空间。
from ultralytics.models.yolo.detect import DetectionPredictor, DetectionTrainer, DetectionValidator
# trainer
trainer = DetectionTrainer(overrides={})
trainer.train()
trained_model = trainer.best
# Validator
val = DetectionValidator(args=...)
val(model=trained_model)
# predictor
pred = DetectionPredictor(overrides={})
pred(source=SOURCE, model=trained_model)
# resume from last weight
overrides["resume"] = trainer.last
trainer = DetectionTrainer(overrides=overrides)你可以轻松定制 Trainer 以支持自定义任务或探索研发想法。Ultralytics YOLO 的模块化设计允许你根据特定需求调整框架,无论你是在从事创新的计算机视觉任务,还是在微调现有模型以获得更好的性能。
Link to this section常见问题解答#
Link to this section我该如何将 YOLO 集成到我的 Python 项目中进行目标检测?#
将 Ultralytics YOLO 集成到你的 Python 项目非常简单。你可以加载预训练模型,也可以从头开始训练一个新模型。以下是入门方法:
from ultralytics import YOLO
# Load a pretrained YOLO model
model = YOLO("yolo26n.pt")
# Perform object detection on an image
results = model("https://ultralytics.com/images/bus.jpg")
# Visualize the results
for result in results:
result.show()在我们的预测模式 (Predict Mode)部分查看更详细的示例。
Link to this sectionYOLO 中有哪些不同的模式?#
Ultralytics YOLO 提供了多种模式来满足不同的机器学习工作流。这些模式包括:
- 训练 (Train):使用自定义数据集训练模型。
- 验证 (Val):在验证集上验证模型性能。
- 预测 (Predict):对新图像或视频流进行预测。
- 导出 (Export):将模型导出为 ONNX 和 TensorRT 等多种格式。
- 追踪 (Track):在视频流中实时对象追踪。
- 基准测试 (Benchmark):在不同配置下评估模型性能。
每种模式都旨在为模型开发和部署的不同阶段提供全面的功能。
Link to this section我该如何使用我的数据集训练自定义 YOLO 模型?#
要训练自定义 YOLO 模型,你需要指定数据集和其他超参数。这是一个快速示例:
from ultralytics import YOLO
# Load the YOLO model
model = YOLO("yolo26n.yaml")
# Train the model with custom dataset
model.train(data="path/to/your/dataset.yaml", epochs=10)有关训练的更多详细信息和使用示例的超链接,请访问我们的训练模式 (Train Mode)页面。
Link to this section我该如何导出 YOLO 模型以便进行部署?#
使用 export 函数可以简单地导出适合部署的 YOLO 模型格式。例如,你可以将模型导出为 ONNX 格式:
from ultralytics import YOLO
# Load the YOLO model
model = YOLO("yolo26n.pt")
# Export the model to ONNX format
model.export(format="onnx")有关各种导出选项,请参阅导出模式 (Export Mode)文档。
Link to this section我可以在不同的数据集上验证我的 YOLO 模型吗?#
是的,可以在不同的数据集上验证 YOLO 模型。训练完成后,你可以使用验证模式来评估其性能:
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo26n.yaml")
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate the model on a different dataset
model.val(data="path/to/separate/data.yaml")查看验证模式 (Val Mode)页面以获取详细示例和用法。