用Python从屏幕上捕获视频数据

2024-04-23 19:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

您将需要使用枕头(PIL)库中的ImageGrab并将捕获转换为numpy数组。当你拥有这个数组时,你可以使用opencv做你想做的事情。我将捕获转换为灰色,并使用imshow()作为演示。

下面是一个快速启动代码:

from PIL import ImageGrab
import numpy as np
import cv2

img = ImageGrab.grab(bbox=(100,10,400,780)) #bbox specifies specific region (bbox= x,y,width,height *starts top-left)
img_np = np.array(img) #this is the array obtained from conversion
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
cv2.imshow("test", frame)
cv2.waitKey(0)
cv2.destroyAllWindows()

你可以用你想要的频率在那里插入一个阵列来继续捕捉帧。在那之后你只需解码帧。不要忘记在循环之前添加:

fourcc = cv2.VideoWriter_fourcc(*'XVID')
vid = cv2.VideoWriter('output.avi', fourcc, 6, (640,480))

在循环中,您可以添加:

vid.write(frame) #the edited frame or the original img_np as you please

更新
最终的结果是这样的(如果你想实现一个帧流的话)。作为视频存储,只是在截取的屏幕上演示如何使用opencv):

from PIL import ImageGrab
import numpy as np
import cv2
while(True):
    img = ImageGrab.grab(bbox=(100,10,400,780)) #bbox specifies specific region (bbox= x,y,width,height)
    img_np = np.array(img)
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    cv2.imshow("test", frame)
    cv2.waitKey(0)
cv2.destroyAllWindows()

希望能帮上忙

您可以尝试此操作=>

import mss
import numpy

with mss.mss() as sct:
    monitor = {'top': 40, 'left': 0, 'width': 800, 'height': 640}
    img = numpy.array(sct.grab(monitor))
    print(img)

还有另一种解决方案可以提供更好的帧速率。(在带有MacOS Sierra的Macbook Pro上测试)

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

mon = {'top': 160, 'left': 160, 'width': 200, 'height': 200}

sct = mss()

while 1:
    sct.get_pixels(mon)
    img = Image.frombytes('RGB', (sct.width, sct.height), sct.image)
    cv2.imshow('test', np.array(img))
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

相关问题 更多 >