yolov10实时检测屏幕python代码
时间: 2024-10-14 17:12:41 浏览: 23
YOLOv10是一种先进的目标检测算法,其全称为You Only Look Once的第十代版本。在Python中,你可以通过开源库如`pytorch-yolov5`来实现YOLOv10的实时屏幕检测,这个库基于PyTorch并简化了YOLO的使用。
下面是一个简单的示例,展示如何在Python环境中使用`pytorch-yolov5`做实时视频目标检测:
```python
# 首先安装所需的库
!pip install pytorch-yolov5
import torch
from PIL import Image
from torchvision.transforms import functional as F
from yolo_v10 import YOLOV10
# 加载预训练模型
model = YOLOV10(weights='yolov10s.pt') # 使用预训练权重
# 打开摄像头或视频文件(这里假设是摄像头)
video_capture = cv2.VideoCapture(0)
while True:
# 读取一帧
ret, frame = video_capture.read()
if not ret:
break
# 转换为Tensor
img = F.to_tensor(frame)
img = img.unsqueeze(0) # 添加batch dimension
# 进行预测
results = model(img)[0]
# 解码并画出边界框
for obj in results.pandas().xyxy[0]:
x1, y1, x2, y2 = obj.tolist()
label, conf = obj[:-1].tolist(), obj[-1]
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
cv2.putText(frame, f'{label}: {conf:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# 显示结果
cv2.imshow('YOLOv10 Detection', frame)
# 按 'q' 键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 清理
video_capture.release()
cv2.destroyAllWindows()
```
阅读全文