YOLOv8 是一种先进的实时目标检测算法,它具有极高的检测速度和准确性。以下是对 YOLOv8 的简要介绍和一些重要概念。

安装

要使用 YOLOv8,您需要安装以下依赖项:

  • Python 3.7 或更高版本
  • PyTorch 1.8 或更高版本
  • OpenCV 4.5.1.48 或更高版本

您可以使用以下命令安装这些依赖项:

pip install torch torchvision opencv-python

快速开始

以下是一个简单的示例,展示了如何使用 YOLOv8 进行目标检测:

import torch
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import check_img_size, non_max_suppression, scale_coords
from utils.torch_utils import select_device, time_synchronized

# 加载模型
model = attempt_load('yolov8.pt')

# 设置设备
device = select_device('')

# 加载图像
img = LoadImages('data/images', img_size=640).load()

# 检测
for path, img, im0s, vid_cap in img:
    img = torch.from_numpy(img).to(device)
    img = img.float()  # uint8 to fp16/32
    img /= 255.0  # 归一化
    if img.ndimension() == 3:
        img = img.unsqueeze(0)

    # 检测
    pred = model(img, augment=False)[0]

    # 非极大值抑制
    pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)

    # 处理检测结果
    for i, det in enumerate(pred):  # 检测到的图像
        p, s, im0 = path, '', im0s

        s += '%gx%g ' % img.shape[2:]  # 打印图像尺寸
        if len(det):
            # 筛选检测结果
            det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

            # 打印检测结果
            for c in det[:, -1].unique():
                n = (det[:, -1] == c).sum()  # 类别数量
                s += f'{n} {model.names[int(c)]}s, '  # 打印类别和数量

            # 绘制检测结果
            for *xyxy, conf, cls in reversed(det):
                label = f'{model.names[int(cls)]} {conf:.2f}'
                plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)

        # 显示图像
        cv2.imshow(s, im0)
        cv2.waitKey(1)  # 等待键盘中断

# 查看更多示例:[YOLOv8 示例](/ai_tools_open_source_tutorial/yolov8_examples)