Python 使用#
欢迎阅读 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")训练#
训练模式用于在自定义数据集上训练 YOLO 模型。在此模式下,模型使用指定的数据集和超参数进行训练。训练过程涉及优化模型的参数,以便其能够准确预测图像中对象的类别和位置。
from ultralytics import YOLO
model = YOLO("yolo26n.pt") # pass any model type
results = model.train(epochs=5)验证#
验证模式用于在训练完成后验证 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()预测#
预测模式用于使用训练好的 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])导出#
导出模式用于将 YOLO 模型导出为可用于部署的格式。在此模式下,模型被转换为其他软件应用程序或硬件设备可以使用的格式。在将模型部署到生产环境时,此模式非常有用。
将官方的 YOLO 模型导出为支持动态批次大小和图像大小的 ONNX。
from ultralytics import YOLO
model = YOLO("yolo26n.pt")
model.export(format="onnx", dynamic=True)追踪#
跟踪模式用于使用 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")基准测试#
基准测试模式用于剖析 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, device=0)使用 Trainer#
YOLO 模型类用作 Trainer 类的封装。每个 YOLO 任务都有自己的 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)你可以轻松自定义 Trainers 以支持自定义任务或探索研发想法。Ultralytics YOLO 的模块化设计允许你将框架调整为满足特定需求,无论你是在研究新颖的计算机视觉任务还是微调现有模型以获得更好的性能。
常见问题解答#
将 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()请在我们的预测模式部分查看更多详细示例。
使用
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")有关各种导出选项,请参考导出模式文档。
是的,可以在不同的数据集上验证 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")查看验证模式页面以获取详细示例和用法。