当前位置:   article > 正文

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

yolo v8使用文档
commentsdescriptionkeywords

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 格式。

  1. ```python
  2. from ultralytics import YOLO
  3. # Create a new YOLO model from scratch
  4. model = YOLO('yolov8n.yaml')
  5. # Load a pretrained YOLO model (recommended for training)
  6. model = YOLO('yolov8n.pt')
  7. # Train the model using the 'coco128.yaml' dataset for 3 epochs
  8. results = model.train(data='coco128.yaml', epochs=3)
  9. # Evaluate the model's performance on the validation set
  10. results = model.val()
  11. # Perform object detection on an image using the model
  12. results = model('https://ultralytics.com/images/bus.jpg')
  13. # Export the model to ONNX format
  14. success = model.export(format='onnx')
  15. ```

二、Train

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

  1. === "From pretrained(recommended)"
  2. ```python
  3. from ultralytics import YOLO
  4. model = YOLO('yolov8n.pt') # pass any model type
  5. results = model.train(epochs=5)
  6. ```
  7. === "From scratch"
  8. ```python
  9. from ultralytics import YOLO
  10. model = YOLO('yolov8n.yaml')
  11. results = model.train(data='coco128.yaml', epochs=5)
  12. ```
  13. === "Resume"
  14. ```python
  15. model = YOLO("last.pt")
  16. results = model.train(resume=True)
  17. ```

三、Val

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

  1. === "Val after training"
  2. ```python
  3. from ultralytics import YOLO
  4. model = YOLO('yolov8n.yaml')
  5. model.train(data='coco128.yaml', epochs=5)
  6. model.val() # It'll automatically evaluate the data you trained.
  7. ```
  8. === "Val independently"
  9. ```python
  10. from ultralytics import YOLO
  11. model = YOLO("model.pt")
  12. # It'll use the data YAML file in model.pt if you don't set data.
  13. model.val()
  14. # or you can set the data you want to val
  15. model.val(data='coco128.yaml')
  16. ```

四、Predict

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

  1. === "From source"
  2. ```python
  3. from ultralytics import YOLO
  4. from PIL import Image
  5. import cv2
  6. model = YOLO("model.pt")
  7. # accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam
  8. results = model.predict(source="0")
  9. results = model.predict(source="folder", show=True) # Display preds. Accepts all YOLO predict arguments
  10. # from PIL
  11. im1 = Image.open("bus.jpg")
  12. results = model.predict(source=im1, save=True) # save plotted images
  13. # from ndarray
  14. im2 = cv2.imread("bus.jpg")
  15. results = model.predict(source=im2, save=True, save_txt=True) # save predictions as labels
  16. # from list of PIL/ndarray
  17. results = model.predict(source=[im1, im2])
  18. ```
  19. === "Results usage"
  20. ```python
  21. # results would be a list of Results object including all the predictions by default
  22. # but be careful as it could occupy a lot memory when there're many images,
  23. # especially the task is segmentation.
  24. # 1. return as a list
  25. results = model.predict(source="folder")
  26. # results would be a generator which is more friendly to memory by setting stream=True
  27. # 2. return as a generator
  28. results = model.predict(source=0, stream=True)
  29. for result in results:
  30. # Detection
  31. result.boxes.xyxy # box with xyxy format, (N, 4)
  32. result.boxes.xywh # box with xywh format, (N, 4)
  33. result.boxes.xyxyn # box with xyxy format but normalized, (N, 4)
  34. result.boxes.xywhn # box with xywh format but normalized, (N, 4)
  35. result.boxes.conf # confidence score, (N, 1)
  36. result.boxes.cls # cls, (N, 1)
  37. # Segmentation
  38. result.masks.data # masks, (N, H, W)
  39. result.masks.xy # x,y segments (pixels), List[segment] * N
  40. result.masks.xyn # x,y segments (normalized), List[segment] * N
  41. # Classification
  42. result.probs # cls prob, (num_class, )
  43. # Each result is composed of torch.Tensor by default,
  44. # in which you can easily use following functionality:
  45. result = result.cuda()
  46. result = result.cpu()
  47. result = result.to("cpu")
  48. result = result.numpy()
  49. ```

五、Export

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

  1. === "Export to ONNX"
  2. Export an official YOLOv8n model to ONNX with dynamic batch-size and image-size.
  3. ```python
  4. from ultralytics import YOLO
  5. model = YOLO('yolov8n.pt')
  6. model.export(format='onnx', dynamic=True)
  7. ```
  8. === "Export to TensorRT"
  9. Export an official YOLOv8n model to TensorRT on `device=0` for acceleration on CUDA devices.
  10. ```python
  11. from ultralytics import YOLO
  12. model = YOLO('yolov8n.pt')
  13. model.export(format='onnx', device=0)
  14. ```

六、Track

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

  1. === "Python"
  2. ```python
  3. from ultralytics import YOLO
  4. # Load a model
  5. model = YOLO('yolov8n.pt') # load an official detection model
  6. model = YOLO('yolov8n-seg.pt') # load an official segmentation model
  7. model = YOLO('path/to/best.pt') # load a custom model
  8. # Track with the model
  9. results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True)
  10. results = model.track(source="https://youtu.be/LNwODJXcvt4", show=True, tracker="bytetrack.yaml")
  11. ```

七、Benchmark

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

  1. === "Python"
  2. Benchmark an official YOLOv8n model across all export formats.
  3. ```python
  4. from ultralytics.utils.benchmarks import benchmark
  5. # Benchmark
  6. benchmark(model='yolov8n.pt', data='coco8.yaml', imgsz=640, half=False, device=0)
  7. ```

八、Using Trainers

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

  1. ```python
  2. from ultralytics.models.yolo import DetectionTrainer, DetectionValidator, DetectionPredictor
  3. # trainer
  4. trainer = DetectionTrainer(overrides={})
  5. trainer.train()
  6. trained_model = trainer.best
  7. # Validator
  8. val = DetectionValidator(args=...)
  9. val(model=trained_model)
  10. # predictor
  11. pred = DetectionPredictor(overrides={})
  12. pred(source=SOURCE, model=trained_model)
  13. # resume from last weight
  14. overrides["resume"] = trainer.last
  15. trainer = detect.DetectionTrainer(overrides=overrides)
  16. ```

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/130940
推荐阅读
相关标签
  

闽ICP备14008679号