Mac M1 Yolo5初步尝试: 从浏览器播放的视频中实时识别人类

227 阅读1分钟

把浏览器播放一个视频放在左上角约屏幕大小的四分之一,启动py文件,把弹出的窗口挪支到右上角来

import torch
import numpy as np
import cv2
import mss
from PIL import Image

# 加载模型
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')

# 创建MSS对象
with mss.mss() as sct:
    # 获取第一个监视器的尺寸
    monitor = sct.monitors[1]
    width, height = monitor["width"], monitor["height"]

    # 计算左上角和左下角窗口的位置和大小
    top_half_height = height // 2
    left_corner = {"top": 0, "left": 0, "width": width // 2, "height": top_half_height}
    left_corner_result = {"top": top_half_height, "left": 0, "width": width // 2, "height": top_half_height}

    while True:
        # 获取左上角窗口的截图
        left_corner_img = np.array(sct.grab(left_corner))
        # 获取左下角窗口的截图
        left_corner_result_img = np.array(sct.grab(left_corner_result))

        # 转换图像格式
        left_corner_image = Image.fromarray(left_corner_img)
        left_corner_result_image = Image.fromarray(left_corner_result_img)

        # 进行检测
        results = model(left_corner_image)

        # 获取人类对象
        human_results = results.pred[0][results.pred[0][:, 5] == 0]

        # 在左上角图像上绘制边界框
        for det in human_results:
            bbox = det[:4]
            x1, y1, x2, y2 = bbox.cpu().numpy().astype(int)
            cv2.rectangle(left_corner_img, (x1, y1), (x2, y2), (255, 0, 0), 2)

        # 在左下角图像上绘制结果
        left_corner_result_img = cv2.cvtColor(left_corner_result_img, cv2.COLOR_BGR2RGB)

        # 将左上角和左下角图像显示在屏幕上
        cv2.imshow('Left Top Corner', left_corner_img)
        # cv2.imshow('Left Bottom Corner', left_corner_result_img)

        # 检测按键,如果按下 'q' 键则退出循环
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

# 关闭窗口
cv2.destroyAllWindows()

屏幕左上角播放视频,屏幕右上角显示实时识别的效果: www.bilibili.com/video/BV1gw…