【计算机视觉】YOLOv8如何使用?(含源代码)

comments description keywords

true

Boost your Python projects with object detection, segmentation and classification using YOLOv8. Explore how to load, train, validate, predict, export, track and benchmark models with ease.

YOLOv8, Ultralytics, Python, object detection, segmentation, classification, model training, validation, prediction, model export, benchmark, real-time tracking

一、Python Usage

欢迎来到 YOLOv8 Python 使用文档! 本指南旨在帮助您将 YOLOv8 无缝集成到您的 Python 项目中,以进行对象检测、分割和分类。 在这里,您将学习如何加载和使用预训练模型、训练新模型以及对图像执行预测。 对于任何希望将 YOLOv8 纳入其 Python 项目的人来说,易于使用的 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')
```

二、Train

训练模式用于在自定义数据集上训练 YOLOv8 模型。 在此模式下,使用指定的数据集和超参数来训练模型。 训练过程涉及优化模型的参数,以便它能够准确预测图像中对象的类别和位置。

=== "From pretrained(recommended)"
    ```python
    from ultralytics import YOLO

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

=== "From scratch"
    ```python
    from ultralytics import YOLO

    model = YOLO('yolov8n.yaml')
    results = model.train(data='coco128.yaml', epochs=5)
    ```

=== "Resume"
    ```python
    model = YOLO("last.pt")
    results = model.train(resume=True)
    ```

三、Val

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

=== "Val after training"
    ```python
      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.
    ```

=== "Val independently"
    ```python
      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')
    ```

四、Predict

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

=== "From source"
    ```python
    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 usage"
    ```python
    # 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()
    ```

五、Export

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

=== "Export to ONNX"

    Export an official YOLOv8n model to ONNX with dynamic batch-size and image-size.
    ```python
      from ultralytics import YOLO

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

=== "Export to TensorRT"

    Export an official YOLOv8n model to TensorRT on `device=0` for acceleration on CUDA devices.
    ```python
      from ultralytics import YOLO

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

六、Track

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

=== "Python"

    ```python
    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")
    ```

七、Benchmark

基准模式用于分析 YOLOv8 各种导出格式的速度和准确性。 基准测试提供了有关导出格式的大小、其 mAP50-95 指标(用于对象检测和分割)或 precision_top5 指标(用于分类)以及跨各种导出格式(例如 ONNX、OpenVINO、TensorRT)的每个图像的推理时间(以毫秒为单位)的信息 和别的。 此信息可以帮助用户根据其对速度和准确性的要求,选择适合其特定用例的最佳导出格式。

=== "Python"

    Benchmark an official YOLOv8n model across all export formats.
    ```python
    from ultralytics.utils.benchmarks import benchmark

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

八、Using Trainers

YOLO 模型类是 Trainer 类的高级包装。 每个 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)
    ```

您可以轻松自定义培训师以支持自定义任务或探索研发想法。 在定制部分了解有关定制训练器、验证器和预测器以满足您的项目需求的更多信息。

你可能感兴趣的:(计算机视觉,计算机视觉,YOLO,人工智能,深度学习)