当前位置: 首页 > ai >正文

从零开始实现YOLOv8示例

1. YOLOv8环境配置

yolov8官网

# 安装YOLOv8
pip install "ultralytics<=8.3.40"
# 安装 ONNX Runtime
pip install onnxruntime

2. 预训练模型检测图片

# 下载示例图片
wget https://ultralytics.com/images/bus.jpg 
# 使用预训练模型检测图片
yolo detect predict model=yolov8n.pt source=bus.jpg  
#输出结果
# 生成 runs/detect/predict 目录,包含标注后的图片(如 bus.jpg 中检测到车辆、行人等)。

3. 训练模型实时检测

# 下载小型数据集(如 COCO 格式的 coco128):
yolo download data=coco128 
# 训练模型, epochs=10 表示训练 10 轮,训练完成后,模型保存在 runs/detect/train 
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 
# 实时摄像头检测,source=0 表示调用本地摄像头
yolo detect predict model=yolov8n.pt source=0
# 导出模型为 ROS 2 兼容格式
yolo export model=yolov8n.pt format=onnx 

4. 使用 ONNX 模型进行推理

# 
import cv2
import numpy as np
import onnxruntime as ort# 加载 ONNX 模型
session = ort.InferenceSession("yolov8n.onnx")  # <button class="citation-flag" data-index="6"><button class="citation-flag" data-index="8"># 准备输入图像
image = cv2.imread("bus.jpg")  # <button class="citation-flag" data-index="1">
input_blob = cv2.resize(image, (640, 640))  # 固定输入尺寸(YOLOv8 默认要求)<button class="citation-flag" data-index="7">
input_blob = input_blob.transpose(2, 0, 1)  # 转换为 CHW 格式 <button class="citation-flag" data-index="4">
input_blob = input_blob[np.newaxis, ...].astype(np.float32) / 255.0  # 归一化 <button class="citation-flag" data-index="4"># 执行推理
outputs = session.run(None, {"images": input_blob})  # <button class="citation-flag" data-index="6"><button class="citation-flag" data-index="8"># 解析输出(示例简化版)
detections = outputs[0][0]  # 假设输出为检测结果
for detection in detections:class_id, confidence, bbox = detectionprint(f"Class: {class_id}, Confidence: {confidence}, BBox: {bbox}")  # <button class="citation-flag" data-index="7">

5. 部署验证

# 示例:导出为 RKNN 格式(需额外工具)
python3 -m airockchip.export --model yolov8n.onnx --output yolov8n.rknn 
# 验证导出模型
yolo val model=yolov8n.onnx data=coco128.yaml
http://www.xdnf.cn/news/5203.html

相关文章:

  • 线性表-顺序表(Sequential List)
  • 【vue】vuex实现组件间数据共享 vuex模块化编码 网络请求
  • GRU网络详解
  • 解决使用宝塔Linux部署前后端分离项目遇到的问题
  • 第三章 Freertos智能小车遥控控制
  • 【Web】LACTF 2025 wp
  • 虚拟机风格
  • OpenLayers根据任意数量控制点绘制贝塞尔曲线
  • 关于甲骨文(oracle cloud)丢失MFA的解决方案
  • vim的配置
  • C++(6):逻辑运算符
  • AI 驱动的开发工具
  • 中国古代史1
  • 【ML-Agents】ML-Agents示例项目导入unity报错解决
  • 当冲压焊接遇上Canopen到Profinet协议转换网关
  • 4.分布式锁
  • C++进阶--AVL树的实现续
  • HC-SR04超声波测距传感器
  • Doris和Clickhouse对比
  • 视觉革命来袭!ComfyUI-LTXVideo 让视频创作更高效
  • Kotlin知识体系(七) : Flow线程控制、状态管理及异常处理指南
  • 每日脚本学习5.10 - XOR脚本
  • SSH终端登录与网络共享
  • AI与机器人学:从SLAM到导航的未来
  • HTTP/3展望、我应该迁移到HTTP/2吗
  • 【Linux】线程的同步与互斥
  • 物联网之使用Vertx实现MQTT-Server最佳实践【响应式】
  • 互联网大厂Java面试实录:Spring Boot与微服务架构在电商场景中的应用解析
  • MIT XV6 - 1.4 Lab: Xv6 and Unix utilities - find
  • vllm笔记