在python中使用带有多线程的mss

2024-03-28 16:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\threading.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:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\mss\windows.py", line 301, in grab
    raise ScreenShotError("gdi32.GetDIBits() failed.")
mss.exception.ScreenShotError: gdi32.GetDIBits() failed.

(这是一个无限循环,这就是线程数超过165的原因)

请帮助我如何使用多线程截图。你知道吗


Tags: in图像image屏幕maintoprgbwidth