使用 PIL 或 cv2 等模块在 python 中捕获屏幕的最有效方法是什么?因为它占用了很多内存
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
使用 PIL 或 cv2 等模块在 python 中捕获屏幕的最有效方法是什么?因为它占用了很多内存。
我想通过屏幕抓取和整洁来教 AI 玩 Chrome 的恐龙游戏,但这样会很慢...
我试过:
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
您可以使用 mss
,这是一个“超快 cross-platform 纯 python 多屏幕截图模块”。
例如:
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
结果:
The loop took: 0.024120092391967773
输出:
结果比您当前的结果快 100 倍。
使用 PIL 或 cv2 等模块在 python 中捕获屏幕的最有效方法是什么?因为它占用了很多内存。
我想通过屏幕抓取和整洁来教 AI 玩 Chrome 的恐龙游戏,但这样会很慢...
我试过:
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
您可以使用 mss
,这是一个“超快 cross-platform 纯 python 多屏幕截图模块”。
例如:
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
结果:
The loop took: 0.024120092391967773
输出:
结果比您当前的结果快 100 倍。