What is the most efficient way to capture screen in python using modules eg PIL or cv2? because It takes up a lot of ram

99封情书 提交于 2021-02-08 06:56:23

问题


What is the most efficient way to capture screen in python using modules eg PIL or cv2? Because It takes up a lot of ram.

I wanted to teach AI to play dino game of Chrome through screen scraping and neat but it is way to slow...

I have tried:

import numpy as np
from PIL import ImageGrab
import cv2
import time

last_time = time.time()
while True:
    printscreen_pil = ImageGrab.grab(bbox= (0, 40, 800, 640))

    printscreen_numpy = np.array(printscreen_pil.getdata(), dtype = 'uint8').reshape((printscreen_pil.size[1], printscreen_pil.size[0], 3))
    
    print(f'the loop took {time.time() - last_time} seconds')
    last_time = time.time()
 
     cv2.imshow('window', printscreen_numpy)
     if cv2.waitKey(25) & 0xFF == ord('q'):
         cv2.destroyAllWindows()
         break

> 
    # average time = the loop took 2.068769931793213 seconds 

回答1:


You can use mss which is an "An ultra fast cross-platform multiple screenshots module in pure python".

For example:

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

start_time = time.time()
mon = {'top': 200, 'left': 200, 'width': 200, 'height': 200}
with mss() as sct:
    while True:
        last_time = time.time()
        img = sct.grab(mon)
        print('The loop took: {0}'.format(time.time()-last_time))
        cv2.imshow('test', np.array(img))
        if cv2.waitKey(25) & 0xFF == ord('q'):
            cv2.destroyAllWindows()
            break

Result:

The loop took: 0.024120092391967773

Output:

The result is faster 100x than your current result.



来源:https://stackoverflow.com/questions/63722447/what-is-the-most-efficient-way-to-capture-screen-in-python-using-modules-eg-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!