yolov5实时检测屏幕python代码
时间: 2023-02-20 14:46:46 浏览: 304
下面是一份使用 YOLOv5 进行实时屏幕检测的 Python 代码示例:
```
import cv2
import numpy as np
import torch
from models import *
from utils.datasets import *
from utils.utils import *
class ObjectDetection:
def __init__(self, model_def, model_weights, class_path, conf_thres=0.5, nms_thres=0.5, img_size=416):
self.device = torch.device("cv2.CAP_PROP_FRAME_WIDTH" if torch.cuda.is_available() else "cpu")
# Set up model
self.model = Darknet(model_def, img_size=img_size).to(self.device)
if model_weights.endswith(".pt"):
self.model.load_state_dict(torch.load(model_weights, map_location=self.device)["model"])
else:
_ = load_darknet_weights(self.model, model_weights)
self.model.eval() # Set in evaluation mode
self.classes = load_classes(class_path)
self.colors = np.random.randint(0, 255, size=(len(self.classes), 3), dtype="uint8")
self.conf_thres = conf_thres
self.nms_thres = nms_thres
self.img_size = img_size
def detect(self, frame):
# Preprocess frame
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = cv2.resize(frame, (self.img_size, self.img_size))
frame = torch.from_numpy(frame).float().div(255.0).unsqueeze(0).to(self.device)
# Inference
with torch.no_grad():
detections = self.model(frame)
detections = non_max_suppression(detections, self.conf_thres, self.nms_thres)
# Process detections
for detection in detections:
detection = detection[0]
box = detection[:4].cpu().numpy()
box[0] *= frame.shape[1]
box[1] *= frame.shape[0]
box[2] *= frame.shape[1]
box[3] *= frame.shape[0]
cls = int(detection[6])
label = f"{self.classes[cls]}: {detection[5]:.2f}"
color = self.colors[cls]
cv2.rectangle(frame, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), color, 2)
cv2.putText(frame, label, (int(box[0]), int(box[1]) - 10), cv2.FONT_
阅读全文