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

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 = detectionprint(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 = detectionlabel = 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()

摄像头

import torch
import cv2
import numpy as np
import time# 加载预训练模型
model = torch.hub.load('../yolov5-master', 'custom', path='yolo_test/yolo_test-gpu7/weights/best.pt', source='local')# 打开摄像头
cap = cv2.VideoCapture(0)# 检查摄像头是否成功打开
if not cap.isOpened():print("Error: Could not open video.")exit()# 初始化计时器
prev_time = time.time()# 进行实时检测
while True:# 读取摄像头帧ret, frame = cap.read()if not ret:print("Error: Failed to capture image")break# 将帧转换为YOLOv5模型需要的格式results = model(frame)# 解析结果detections = results.xyxy[0].cpu().numpy()  # [x1, y1, x2, y2, confidence, class]# 在帧上绘制检测结果for detection in detections:x1, y1, x2, y2, confidence, cls = detectionlabel = f"{model.names[int(cls)]} {confidence:.2f}"cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)cv2.putText(frame, label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)# 计算并显示帧率current_time = time.time()fps = 1 / (current_time - prev_time)prev_time = current_timecv2.putText(frame, f"FPS: {fps:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)# 显示结果cv2.imshow('YOLOv5 Real-Time Detection', frame)# 按 'q' 键退出循环if cv2.waitKey(1) & 0xFF == ord('q'):break# 释放摄像头并关闭所有窗口
cap.release()
cv2.destroyAllWindows()
http://www.lryc.cn/news/404552.html

相关文章:

  • Scala学习笔记19: 隐式转换和隐式参数
  • 用户登录安全是如何保证的?如何保证用户账号、密码安全?
  • Java 写一个可以持续发送消息的socket服务端
  • Ubuntu2204搭建ceph17
  • Druid 面试题及答案整理,最新面试题
  • 数据库基础与安装MYSQL数据库
  • 昇思25天学习打卡营第18天| DCGAN生成漫画头像
  • 【面试八股文】计算机操作系统
  • 宝塔Wordpress 插件 Redis object cache 导致内存很高 80%以上的原因和解决
  • node解析Excel中的考试题并实现在线做题功能
  • 怎么降低美国服务器硬盘故障率?
  • Java---后端事务管理
  • Leetcode 3223. Minimum Length of String After Operations
  • oops使用笔记
  • redistemplate介绍与演示
  • 代谢组数据分析(十五):基于python语言构建PLS-DA算法构建分类模型
  • 任务3 git基础知识(主要是pr的笔记)
  • 三相PWM整流器滞环电流控制仿真matlab simulink
  • AVL树超详解上
  • spring boot 实现token验证登陆状态
  • 【.NET全栈】ASP.NET开发Web应用——用户控件和绘图
  • 一行Python代码实现数据清洗的18种方法
  • Java API练习 (1) (2024.7.20)
  • JavaScript之WebAPIs-BOM
  • Math Reference Notes: 数学思想和方法
  • Spring Cloud GateWay(4.1.4)
  • 基于PHP+MYSQL开发制作的趣味测试网站源码
  • 【微信小程序】wx.navigateTo传参时不能使用const定义的数据类型
  • 【Android studio环境搭建】Android studio连接夜神模拟器
  • Qt:26.Qt项目:贪吃蛇游戏