Python 用法
欢迎使用 Ultralytics YOLO Python 用法文档!本指南旨在帮助您将 Ultralytics YOLO 无缝集成到您的 Python 项目中,以实现对象检测、分割和分类。在这里,您将学习如何加载和使用预训练模型、训练新模型以及对图像执行预测。易于使用的 Python 界面对于任何希望将 YOLO 纳入其 Python 项目的人来说都是宝贵的资源,使您能够快速实现高级对象检测功能。让我们开始吧!
观看: 掌握 Ultralytics YOLO: python
例如,用户只需几行代码即可加载模型、训练模型、评估其在验证集上的性能,甚至可以将其导出为 ONNX 格式。
Python
from ultralytics import YOLO
# Create a new YOLO model from scratch
model = YOLO("yolo11n.yaml")
# Load a pretrained YOLO model (recommended for training)
model = YOLO("yolo11n.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("yolo11n.pt") # pass any model type
results = model.train(epochs=5)
from ultralytics import YOLO
model = YOLO("yolo11n.yaml")
results = model.train(data="coco8.yaml", epochs=5)
model = YOLO("last.pt")
results = model.train(resume=True)
验证
Val 模式用于在 YOLO 模型训练完成后对其进行验证。在此模式下,模型会在验证集上进行评估,以衡量其准确性和泛化性能。此模式可用于调整模型的超参数,以提高其性能。
验证
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo11n.yaml")
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate on training data
model.val()
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo11n.yaml")
# Train the model
model.train(data="coco8.yaml", epochs=5)
# Validate on separate data
model.val(data="path/to/separate/data.yaml")
预测
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])
# results would be a list of Results object including all the predictions by default
# but be careful as it could occupy a lot memory when there're many images,
# especially the task is segmentation.
# 1. return as a list
results = model.predict(source="folder")
# results would be a generator which is more friendly to memory by setting stream=True
# 2. return as a generator
results = model.predict(source=0, stream=True)
for result in results:
# Detection
result.boxes.xyxy # box with xyxy format, (N, 4)
result.boxes.xywh # box with xywh format, (N, 4)
result.boxes.xyxyn # box with xyxy format but normalized, (N, 4)
result.boxes.xywhn # box with xywh format but normalized, (N, 4)
result.boxes.conf # confidence score, (N, 1)
result.boxes.cls # cls, (N, 1)
# Segmentation
result.masks.data # masks, (N, H, W)
result.masks.xy # x,y segments (pixels), List[segment] * N
result.masks.xyn # x,y segments (normalized), List[segment] * N
# Classification
result.probs # cls prob, (num_class, )
# Each result is composed of torch.Tensor by default,
# in which you can easily use following functionality:
result = result.cuda()
result = result.cpu()
result = result.to("cpu")
result = result.numpy()
导出
导出模式用于将 YOLO 模型导出为可用于部署的格式。在此模式下,模型将转换为可供其他软件应用程序或硬件设备使用的格式。在将模型部署到生产环境时,此模式非常有用。
导出
追踪
追踪模式用于使用 YOLO 模型实时追踪物体。在此模式下,模型从检查点文件加载,用户可以提供实时视频流以执行实时物体追踪。此模式适用于监控系统或自动驾驶汽车等应用。
追踪
from ultralytics import YOLO
# Load a model
model = YOLO("yolo11n.pt") # load an official detection model
model = YOLO("yolo11n-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_top5
指标(用于分类)以及在各种导出格式(如 ONNX、TF)中每张图像的推理时间(以毫秒为单位)。 OpenVINO, TensorRT 等。这些信息可以帮助用户根据他们对速度和准确性的要求,为其特定用例选择最佳导出格式。
基准测试
对官方 YOLO 模型在所有导出格式上进行基准测试。
from ultralytics.utils.benchmarks import benchmark
# Benchmark
benchmark(model="yolo11n.pt", data="coco8.yaml", imgsz=640, half=False, device=0)
使用训练器
字段 YOLO
model 类是 Trainer 类的高级封装器。每个 YOLO 任务都有自己的训练器,它继承自 BaseTrainer
。这种架构允许在您的机器学习工作流程中实现更大的灵活性和定制化。 机器学习工作流程.
检测训练器示例
from ultralytics.models.yolo 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 的模块化设计使您可以根据自己的特定需求调整框架,无论您是从事新的计算机视觉任务还是微调现有模型以获得更好的性能。
常见问题
如何将 YOLO 集成到我的 python 项目中以进行目标检测?
将 Ultralytics YOLO 集成到您的 python 项目中非常简单。您可以加载预训练模型或从头开始训练新模型。以下是如何开始:
from ultralytics import YOLO
# Load a pretrained YOLO model
model = YOLO("yolo11n.pt")
# Perform object detection on an image
results = model("https://ultralytics.com/images/bus.jpg")
# Visualize the results
for result in results:
result.show()
请参阅我们的预测模式部分,获取更详细的示例。
YOLO 中有哪些不同的可用模式?
Ultralytics YOLO 提供了各种模式来满足不同的机器学习工作流程。这些包括:
- Train(训练):使用自定义数据集训练模型。
- Val(验证):验证模型在验证集上的性能。
- Predict(预测):对新的图像或视频流进行预测。
- 导出: 将模型导出为各种格式,如 ONNX 和 TensorRT。
- Track(追踪):在视频流中进行实时对象追踪。
- Benchmark(基准测试):对不同配置下的模型性能进行基准测试。
每种模式都旨在为模型开发和部署的不同阶段提供全面的功能。
如何使用我的数据集训练自定义的 YOLO 模型?
要训练自定义 YOLO 模型,您需要指定数据集和其他超参数。这是一个快速示例:
from ultralytics import YOLO
# Load the YOLO model
model = YOLO("yolo11n.yaml")
# Train the model with custom dataset
model.train(data="path/to/your/dataset.yaml", epochs=10)
有关训练的更多详细信息以及指向示例用法的超链接,请访问我们的Train 模式页面。
如何导出 YOLO 模型以进行部署?
使用以下命令以适合部署的格式导出 YOLO 模型非常简单 export
函数。例如,您可以将模型导出为 ONNX 格式:
from ultralytics import YOLO
# Load the YOLO model
model = YOLO("yolo11n.pt")
# Export the model to ONNX format
model.export(format="onnx")
有关各种导出选项,请参阅导出模式文档。
我可以在不同的数据集上验证我的 YOLO 模型吗?
是的,可以在不同的数据集上验证 YOLO 模型。训练后,您可以使用验证模式来评估性能:
from ultralytics import YOLO
# Load a YOLO model
model = YOLO("yolo11n.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 模式页面,获取详细示例和用法。