opencv 使用python中的mss进行视频录制

vptzau2j  于 2022-11-24  发布在  Python
关注(0)|答案(1)|浏览(204)

我在Windows上使用OpenCV捕获屏幕。它工作正常,但我听说mss比PIL快得多。我在youtube视频中看到过此代码,但无法弄清楚如何将帧保存到.wav文件或类似文件

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

mon = {'top': 100, 'left':200, 'width':1600, 'height':1024}

sct = mss()

while 1:
    begin_time = time()
    sct_img = sct.grab(mon)
    img = Image.frombytes('RGB', (sct_img.size.width, sct_img.size.height), sct_img.rgb)
    img_bgr = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    cv2.imshow('test', np.array(img_bgr))
    print('This frame takes {} seconds.'.format(time()-begin_time))
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

Credits
我尝试了不同的方法将帧写入数组,但失败了。欢迎任何答案和帮助。

vfh0ocws

vfh0ocws1#

下面是一个基本示例,可以帮助您开始:

import cv2
import numpy as np
import mss
from time import time

width = 640
height = 400
fps = 25
frame_delta = 1 / fps

# part of the screen to capture
monitor = {"top": 10, "left": 10, "width": width, "height": height}

# open video writer
video = cv2.VideoWriter('video.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))

with mss.mss() as sct:
    next_frame = time()

    while True:
        next_frame += frame_delta

        img = np.array(sct.grab(monitor))
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
        video.write(img)
        cv2.imshow("video", img)

        # calculate wait time to meet the defined fps
        wait_ms = max(int((next_frame - time()) * 1000), 1)

        if cv2.waitKey(wait_ms) != -1:
            break

cv2.destroyAllWindows()
video.release()

相关问题