Python脚本数据目标检测YOLO如何调用

wen 实用脚本 1

本文目录导读:

Python脚本数据目标检测YOLO如何调用

  1. 使用Ultralytics YOLOv8(推荐)
  2. 使用YOLOv5 (官方实现)
  3. 使用YOLOv3/v4 (Darknet)
  4. 完整示例:YOLOv8摄像头实时检测
  5. 自定义模型训练后的调用

我来详细介绍Python中使用YOLO进行目标检测的几种主流方法:

使用Ultralytics YOLOv8(推荐)

这是最现代的YOLO实现,安装和使用都很简单:

# 安装
# pip install ultralytics
from ultralytics import YOLO
# 加载预训练模型
model = YOLO('yolov8n.pt')  # 可选: yolov8n/s/m/l/x
# 对图片进行检测
results = model('image.jpg')
# 对视频进行检测
results = model('video.mp4', stream=True)
# 实时摄像头检测
results = model(0)  # 0代表第一个摄像头
# 处理检测结果
for r in results:
    boxes = r.boxes  # 边界框
    for box in boxes:
        x1, y1, x2, y2 = box.xyxy[0]  # 坐标
        conf = box.conf[0]  # 置信度
        cls = box.cls[0]  # 类别ID
        print(f"检测到: {model.names[int(cls)]}, 置信度: {conf:.2f}")

使用YOLOv5 (官方实现)

# 安装
# pip install yolov5
import torch
from PIL import Image
# 加载模型
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
# 检测图片
img = 'image.jpg'
results = model(img)
# 显示结果
results.show()
# 获取检测信息
results.print()  # 打印检测结果
print(results.pandas().xyxy[0])  # 以DataFrame格式输出

使用YOLOv3/v4 (Darknet)

# 使用OpenCV DNN模块加载
import cv2
import numpy as np
# 加载模型
net = cv2.dnn.readNet('yolov3.weights', 'yolov3.cfg')
with open('coco.names', 'r') as f:
    classes = [line.strip() for line in f.readlines()]
# 加载图片
image = cv2.imread('image.jpg')
height, width = image.shape[:2]
# 预处理
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
# 前向传播
outputs = net.forward(net.getUnconnectedOutLayersNames())
# 解析结果
boxes, confidences, class_ids = [], [], []
for output in outputs:
    for detection in output:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > 0.5:
            center_x = int(detection[0] * width)
            center_y = int(detection[1] * height)
            w = int(detection[2] * width)
            h = int(detection[3] * height)
            x = int(center_x - w / 2)
            y = int(center_y - h / 2)
            boxes.append([x, y, w, h])
            confidences.append(float(confidence))
            class_ids.append(class_id)

完整示例:YOLOv8摄像头实时检测

import cv2
from ultralytics import YOLO
# 加载模型
model = YOLO('yolov8n.pt')
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    if not ret:
        break
    # 检测
    results = model(frame)
    # 绘制结果
    annotated_frame = results[0].plot()
    # 显示
    cv2.imshow('YOLOv8 Detection', annotated_frame)
    # 按键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

自定义模型训练后的调用

from ultralytics import YOLO
# 加载自定义训练模型
model = YOLO('path/to/your/best.pt')
# 预测
results = model('test.jpg')
# 提取特定类别
for r in results:
    for box in r.boxes:
        cls = int(box.cls[0])
        if cls == 0:  # 假设类别0是person
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
  1. 推荐使用Ultralytics YOLOv8 - 最简单、功能最全

  2. 模型选择:

    • yolov8n.pt (最轻量)
    • yolov8s.pt (小型)
    • yolov8m.pt (中型)
    • yolov8l.pt (大型)
    • yolov8x.pt (最准确但最慢)
  3. 硬件要求:

    • GPU推荐:CUDA支持的NVIDIA显卡
    • CPU也可运行,但速度较慢
  4. 安装命令:

    pip install ultralytics

这样你就可以快速开始使用YOLO进行目标检测了!

抱歉,评论功能暂时关闭!