首页 > 解决方案 > 使用 MSS 截取许多屏幕截图时,内存快速填满并导致 python 崩溃

问题描述

这是我的代码:

import time
import cv2
import mss
import numpy as np

Frame = [0, 0, 1920, 1080]

def GetFrame():
    monitor = {"top": Frame[0], "left": Frame[1], "width": Frame[2], "height": Frame[3]}
    sct_img = mss.mss().grab(monitor)
    return np.asarray(sct_img)



while (True):
    inimg = GetFrame()
    cv2.imshow("WHY IS MEMORY SO HIGH???????", inimg)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows() 

当它运行时,它不会抛出任何错误,但是在任务管理器中查看,我的内存很快就会填满(大约 200 次迭代之后),最终导致我的桌面崩溃,然后是 python。我调查了垃圾收集,但没有运气。

Python version 3.7.0
MSS version 4.0.1

标签: pythonmemoryscreenshotpython-mss

解决方案


嗯,我自己修好了,我不知道它为什么会起作用,但确实如此。这是我的高智商解决方案:

import time
import cv2
import mss
import numpy as np

Frame = [0, 0, 1920, 1080]

def GetFrame():
    #########solution here
    with mss.mss() as sct: #<-- thats the solution.... yep
        monitor = {"top": Frame[0], "left": Frame[1], "width": Frame[2], "height": Frame[3]}
        sct_img = sct.grab(monitor)
        return np.asarray(sct_img)



while (True):
    inimg = GetFrame()
    cv2.imshow("Normal memory!!", inimg)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()

如果有人想评论并解释为什么这对我有用,那么我将不胜感激:)


推荐阅读