yolo5图片视频推理demo

yolo5图片、视频推理demo

在这里插入图片描述

图片

import torch

# 加载预训练模型
model = torch.hub.load('./yolo5', 'custom', path='yolov5s.pt', source='local')

# 加载图片
img = '1.jpg'

# 进行推理
results = model(img)

# 解析结果
detections = results.xyxy[0].cpu().numpy()  # [x1, y1, x2, y2, confidence, class]

# 输出结果
for detection in detections:
    x1, y1, x2, y2, confidence, cls = detection
    print(f"Class: {model.names[int(cls)]}, Confidence: {confidence:.2f}, Box: [{x1}, {y1}, {x2}, {y2}]")

# 显示结果
results.show()

视频

import cv2
import torch

# 加载预训练模型
model = torch.hub.load('../yolo5', 'custom', path='yolov5s.pt', source='local')

# 加载视频
video_path = '1.mp4'
cap = cv2.VideoCapture(video_path)

# 获取视频的宽度、高度和帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)

# 定义视频写入对象
output_path = 'output_video.mp4'
fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # 编码格式
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # 将帧转换为RGB格式
    img_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    # 进行推理
    results = model(img_rgb)

    # 解析结果
    detections = results.xyxy[0].cpu().numpy()  # [x1, y1, x2, y2, confidence, class]

    # 在帧上绘制检测结果并打印坐标
    for detection in detections:
        x1, y1, x2, y2, confidence, cls = detection
        label = f"{model.names[int(cls)]} {confidence:.2f}"
        cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 2)
        cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 0), 2)

        # 打印目标的坐标和类别
        print(f"Class: {model.names[int(cls)]}, Confidence: {confidence:.2f}, Box: [{x1}, {y1}, {x2}, {y2}]")

    # 显示结果
    cv2.imshow('YOLOv5 Detection', frame)

    # 写入帧到输出视频
    out.write(frame)

    # 按 'q' 键退出实时显示
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 20:52:04       169 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 20:52:04       185 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 20:52:04       155 阅读
  4. Python语言-面向对象

    2024-07-21 20:52:04       169 阅读

热门阅读

  1. ArduPilot开源代码之AP_DAL研读系列

    2024-07-21 20:52:04       30 阅读
  2. Dockerfile相关命令

    2024-07-21 20:52:04       28 阅读
  3. Lucene 索引文件详解:结构与工作原理

    2024-07-21 20:52:04       31 阅读
  4. go语言的命名规则

    2024-07-21 20:52:04       35 阅读
  5. 基于python的时空地理加权回归(GTWR)模型

    2024-07-21 20:52:04       35 阅读
  6. c++端的类,作为组件在qml端使用

    2024-07-21 20:52:04       30 阅读
  7. Python笔记(3)

    2024-07-21 20:52:04       31 阅读
  8. 生成表的DDL语句没有字段描述和表名描述

    2024-07-21 20:52:04       30 阅读
  9. bitset和set总结

    2024-07-21 20:52:04       23 阅读
  10. Flask校验

    2024-07-21 20:52:04       30 阅读
  11. 基带成型(脉冲成形)

    2024-07-21 20:52:04       33 阅读