简体   繁体   English

使用MSS截取许多屏幕截图时,内存会迅速填满并导致python崩溃

[英]When taking many screenshots with MSS, memory fills quickly and crashes python

Here's my code: 这是我的代码:

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() 

When this runs, it doesn't throw any errors, but looking in task manager, my memory fills quickly (after 200 iterations or so), eventually crashing my desktop, then python. 当它运行时,它不会引发任何错误,但是在任务管理器中查看时,我的内存很快就装满了(大约200次迭代后),最终使我的桌面崩溃了,然后是python崩溃了。 I have looked into garbage collection , with no luck. 我调查了垃圾收集 ,没有运气。

Python version 3.7.0
MSS version 4.0.1

Hmm, i fixed it myself, i have no idea why it works, but it does . 嗯,我固定它我自己,我不知道为什么它的工作原理,但它确实 Here's my high IQ solution: 这是我的高智商解决方案:

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()

if someone wants to comment and explain why this works to me, then i'd be thankful :) 如果有人想评论并解释为什么这对我有用,那么我将很感激:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM