代码之家  ›  专栏  ›  技术社区  ›  Sindri Ingolfsson

使用region加速pyautogui屏幕截图()

  •  9
  • Sindri Ingolfsson  · 技术社区  · 7 年前

    我正在尝试加快pyautogui中的屏幕截图功能,因为我只需要屏幕的一小部分。区域变量应该是实现这一点的方法。 pyautogui.screenshot(region=(0,0,400,300)) . 然而,在做了一些测试之后,我发现无论区域大小,截图所需的时间总是相同的(大约250ms)。

    将屏幕截图保存到文件时也是如此 pyautogui.screenshot('dummy.png', region=(0,0,400,300)) region变量似乎无关紧要,整个屏幕都会被保存。有什么想法可以解释为什么这不能正常工作?

    在OS X上运行此功能

    2 回复  |  直到 4 年前
        1
  •  11
  •   Tiger-222    7 年前

    在macOS上,PyAutoGUI只调用 screencapture 公用事业所以速度很慢。 你可以试试看 MSS ,它将非常快速,不需要其他工具/模块。这是一个您可以尝试的示例(从 documentation ):

    import mss
    import mss.tools
    
    
    with mss.mss() as sct:
        # The screen part to capture
        region = {'top': 0, 'left': 0, 'width': 400, 'height': 300}
    
        # Grab the data
        img = sct.grab(region)
    
        # Save to the picture file
        mss.tools.to_png(img.rgb, img.size, output='dummy.png')
    
        2
  •  1
  •   JustAnotherPyGuy    3 年前
    import pyautogui
    
    get1 = input('\nPlace cursor at the top left of the region you want to capture, and then press enter \n')
    pos1 = pyautogui.position()
    
    get2 = input('Now place your cursor at the bottom right of the region you want to capture, and press enter \n')
    pos2 = pyautogui.position()
    
    width = pos2[0] - pos1[0]
    height = pos2[1] - pos1[1]
    
    print('Your region is... \n')
    
    print('region=('+str(pos1[0])+','+str(pos1[1])+','+str(width)+','+str(height)+') \n')
    

    这是我为帮助人们创建区域而编写的脚本!

    首先,将光标放在要捕获的区域的左上角,然后按enter键。

    下一步移动到要查找的区域的右下角,然后再次按enter键。

    它将打印出您的区域坐标,继续并将其与以下代码一起使用

    pyautogui.locateOnScreen('example.png', region=(0,0,0,0)) 
    
    #Fill in your region co-ords there
    

    希望这有帮助!