首页 文章

使用OpenCV和Python-2.7进行屏幕捕获

提问于
浏览
8

我正在使用Python 2.7和OpenCV 2.4.9 .

我需要捕获正在向用户显示的当前帧并将其作为Python中的cv :: Mat 对象加载 .

你们知道一种递归的快速方法吗?

我需要像下面的示例中所做的那样,以递归方式从网络摄像头捕获 Mat 帧:

import cv2

cap = cv2.VideoCapture(0)
while(cap.isOpened()):
    ret, frame = cap.read()
    cv2.imshow('WindowName', frame)
    if cv2.waitKey(25) & 0xFF == ord('q'):
        cap.release()
        cv2.destroyAllWindows()
        break

在该示例中,它使用VideoCapture类来处理来自网络摄像头的捕获图像 .

使用VideoCapture.read(),新帧始终被重新加载并存储到 Mat 对象中 .

我可以将"printscreens stream"加载到VideoCapture对象中吗?我可以使用Python中的OpenCV创建计算机屏幕流,而不必每秒保存和删除大量.bmp文件吗?

我需要这些帧是 Mat 对象或 NumPy arrays ,所以我可以实时执行这些帧的一些计算机视觉例程 .

2 回答

  • 16

    这是我用@Raoul提示编写的解决方案代码 .

    我使用PIL ImageGrab模块来抓取printscreen帧 .

    import numpy as np
    from PIL import ImageGrab
    import cv2
    
    while(True):
        printscreen_pil =  ImageGrab.grab()
        printscreen_numpy =   np.array(printscreen_pil.getdata(),dtype='uint8')\
        .reshape((printscreen_pil.size[1],printscreen_pil.size[0],3)) 
        cv2.imshow('window',printscreen_numpy)
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break
    
  • 22

    我有其他解决方案的帧速率问题,mss解决它们 .

    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
    

相关问题