0

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. I have looked into garbage collection, with no luck.

Python version 3.7.0
MSS version 4.0.1
Tiger-222
  • 6,677
  • 3
  • 47
  • 60
Gaberocksall
  • 359
  • 2
  • 13

1 Answers1

0

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

Gaberocksall
  • 359
  • 2
  • 13
  • You are right, using the context manager will free allocated resources. The documentation is pointing to those misuses: https://python-mss.readthedocs.io/usage.html#instance – Tiger-222 Feb 24 '19 at 16:49
  • 1
    You could do even better by moving the `while` inside the `mss` context manager. This way, you will avoid useless allocation/deacollcation each time you call `GetFrame`. – Tiger-222 Feb 24 '19 at 16:51