跳至内容

Python 使用方法

欢迎访问YOLOv8 Python 使用文档!本指南旨在帮助您将YOLOv8 无缝集成到您的Python 项目中,用于对象检测、分割和分类。在这里,您将学习如何加载和使用预训练模型、训练新模型以及对图像进行预测。对于任何希望将YOLOv8 整合到其Python 项目中的人来说,易于使用的Python 界面都是宝贵的资源,可让您快速实现高级对象检测功能。让我们开始吧!



观看: 掌握Ultralytics YOLOv8 :Python

例如,用户只需几行代码就能加载模型、对其进行训练、评估其在验证集上的性能,甚至将其导出为ONNX 格式。

Python

from ultralytics import YOLO

# Create a new YOLO model from scratch
model = YOLO('yolov8n.yaml')

# Load a pretrained YOLO model (recommended for training)
model = YOLO('yolov8n.pt')

# Train the model using the 'coco128.yaml' dataset for 3 epochs
results = model.train(data='coco128.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')

火车

训练模式用于在自定义数据集上训练YOLOv8 模型。在该模式下,模型使用指定的数据集和超参数进行训练。训练过程包括优化模型参数,使其能够准确预测图像中物体的类别和位置。

火车

from ultralytics import YOLO

model = YOLO('yolov8n.pt') # pass any model type
results = model.train(epochs=5)
from ultralytics import YOLO

model = YOLO('yolov8n.yaml')
results = model.train(data='coco128.yaml', epochs=5)
model = YOLO("last.pt")
results = model.train(resume=True)

列车示例

瓦尔

Val 模式用于在YOLOv8 模型训练完成后对其进行验证。在该模式下,模型在验证集上进行评估,以衡量其准确性和泛化性能。该模式可用于调整模型的超参数,以提高其性能。

瓦尔

  from ultralytics import YOLO

  model = YOLO('yolov8n.yaml')
  model.train(data='coco128.yaml', epochs=5)
  model.val()  # It'll automatically evaluate the data you trained.
  from ultralytics import YOLO

  model = YOLO("model.pt")
  # It'll use the data YAML file in model.pt if you don't set data.
  model.val()
  # or you can set the data you want to val
  model.val(data='coco128.yaml')

Val 示例

预测

预测模式用于使用训练有素的YOLOv8 模型对新图像或视频进行预测。在该模式下,模型从检查点文件加载,用户可以提供图像或视频来执行推理。模型会预测输入图像或视频中物体的类别和位置。

预测

from ultralytics import YOLO
from PIL import Image
import cv2

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()

预测示例

出口

导出模式用于将YOLOv8 模型导出为可用于部署的格式。在此模式下,模型将转换为其他软件应用程序或硬件设备可以使用的格式。在将模型部署到生产环境时,该模式非常有用。

出口

通过动态批量大小和图像大小,将YOLOv8n 官方模型导出到ONNX 。

  from ultralytics import YOLO

  model = YOLO('yolov8n.pt')
  model.export(format='onnx', dynamic=True)

在TensorRT 上导出官方YOLOv8n 模型 device=0 在 CUDA 设备上进行加速。

  from ultralytics import YOLO

  model = YOLO('yolov8n.pt')
  model.export(format='onnx', device=0)

出口示例

轨道

跟踪模式用于使用YOLOv8 模型实时跟踪物体。在该模式下,模型从检查点文件加载,用户可以提供实时视频流来执行实时物体跟踪。该模式适用于监控系统或自动驾驶汽车等应用。

轨道

from ultralytics import YOLO

# Load a model
model = YOLO('yolov8n.pt')  # load an official detection model
model = YOLO('yolov8n-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")

轨道示例

基准

基准模式用于分析YOLOv8 中各种导出格式的速度和准确性。基准模式提供的信息包括导出格式的大小、其 mAP50-95 指标(用于物体检测和分割)或 accuracy_top5 度量(用于分类),以及不同导出格式(如ONNX,OpenVINO,TensorRT 等)下每幅图像的推理时间(以毫秒为单位)。这些信息可以帮助用户根据自己对速度和准确性的要求,为自己的特定使用情况选择最佳的导出格式。

基准

在所有输出格式中对官方YOLOv8n 模型进行基准测试。

from ultralytics.utils.benchmarks import benchmark

# Benchmark
benchmark(model='yolov8n.pt', data='coco8.yaml', imgsz=640, half=False, device=0)

基准范例

探险家

探索者应用程序接口(Explorer API)可用于探索具有高级语义、矢量相似性和 SQL 搜索等功能的数据集。它还能利用 LLM 的强大功能,根据图像内容使用自然语言搜索图像。探索者应用程序接口允许您编写自己的数据集探索笔记本或脚本,以深入了解您的数据集。

使用资源管理器进行语义搜索

from ultralytics import Explorer

# create an Explorer object
exp = Explorer(data='coco128.yaml', model='yolov8n.pt')
exp.create_embeddings_table()

similar = exp.get_similar(img='https://ultralytics.com/images/bus.jpg', limit=10)
print(similar.head())

# Search using multiple indices
similar = exp.get_similar(
                        img=['https://ultralytics.com/images/bus.jpg',
                             'https://ultralytics.com/images/bus.jpg'],
                        limit=10
                        )
print(similar.head())
from ultralytics import Explorer

# create an Explorer object
exp = Explorer(data='coco128.yaml', model='yolov8n.pt')
exp.create_embeddings_table()

similar = exp.get_similar(idx=1, limit=10)
print(similar.head())

# Search using multiple indices
similar = exp.get_similar(idx=[1,10], limit=10)
print(similar.head())

探险家

使用培训师

YOLO 模型类是对训练器类的高级封装。每个YOLO 任务都有自己的训练器,训练器继承自 BaseTrainer.

检测训练器示例

```python
from ultralytics.models.yolo import DetectionTrainer, DetectionValidator, DetectionPredictor

# 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 = detect.DetectionTrainer(overrides=overrides)
```

您可以轻松定制培训师,以支持自定义任务或探索研发思路。了解有关定制的更多信息 Trainers, ValidatorsPredictors 以满足您在定制部分的项目需求。

定制教程



创建于 2023-11-12,更新于 2024-02-03
作者:glenn-jocher(7),AyushExel(1),chr043416@gmail.com(1),Laughing-q(1),maianumerosky(1)

评论