在python中使用带有多线程的mss会给出错误



我正在使用python中的mss模块来截取整个屏幕的屏幕截图。我已经将屏幕分成单独的块,我正在截取这些特定块的屏幕截图。在循环中执行此操作需要很长时间,并且时间随着块数量的增加而增加。

这些是 5 块 1920x1080 屏幕:

[{'top': 0, 'left': 0, 'width': 1920, 'height': 216}, {'top': 216, 'left': 0, 'width': 1920, 'height': 216}, {'top': 432, 'left': 0, 'width': 1920, 'height': 216}, {'top': 648, 'left': 0, 'width': 1920, 'height': 216}, {'top': 864, 'left': 0, 'width': 1920, 'height': 216}]

我使用多线程来做到这一点,但它会产生一个模糊的图像,并且只截取一些块的屏幕截图,而不是全部(比如有些是清晰的,有些是黑色的(。

我在无限循环中执行所有这些操作,并将图像发送到服务器。

def main(block):
image = sct.grab(block).rgb
# send image to server
with mss.mss() as sct:
with concurrent.futures.ThreadPoolExecutor() as executor:
executor.map(main, blocks) 

上面的代码产生了错误的图像(图像的某些块只是黑色的(,所以我尝试这样做:

def threaded(func, args):
threads = []
for arg in args:
thread = threading.Thread(target=func, args=(arg[0],arg[1],))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
def main(block, sct):
with threading.Lock():
image = sct.grab(block).rgb
image = sct.grab(block).rgb
# send image to server
with mss.mss() as sct:
threaded(main, zip(blocks, [sct for i in range(len(blocks))]))

上面的代码给出了这个错误:

Exception in thread Thread-165:
Traceback (most recent call last):
File "C:UsersuserAppDataLocalProgramsPythonPython37libthreading.py", line 926, in _bootstrap_inner
self.run()
File "C:UsersuserAppDataLocalProgramsPythonPython37libthreading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "client.py", line 31, in main
image = sct.grab(block).rgb
File "C:UsersuserAppDataLocalProgramsPythonPython37libsite-packagesmsswindows.py", line 301, in grab
raise ScreenShotError("gdi32.GetDIBits() failed.")
mss.exception.ScreenShotError: gdi32.GetDIBits() failed.

(这是一个无限循环,这就是为什么线程计数超过 165(

请帮助我如何使用多线程截取屏幕截图。

我刚刚发布了修复几个内存泄漏的 5.0.0 版本。你能试试那个版本吗?

最新更新