'Speeding up pyautogui screenshot() with region

I'm trying to speed up the screenshot function in pyautogui since I only need a small portion of the screen. The region variable is supposedly the way to this a.k.a. pyautogui.screenshot(region=(0,0,400,300)). However after doing some testing I found that no matter the size of the region it always takes the same amount of time to take the screenshot (~250ms).

Also when saving the screenshot to a file pyautogui.screenshot('dummy.png', region=(0,0,400,300)) the region variable does not seem to matter and the whole screen is saved regardless. Any ideas on why this is not working properly?

Running this on OS X



Solution 1:[1]

On macOS, PyAutoGUI just calls the screencapture utility. So it is slow. You can give it a try to MSS, it will be blazing fast and requires not other tools/modules. This is an example you could try (copied from the 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')

Solution 2:[2]

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

This is a script I made to help people create a region!

Start by putting the cursor at the top left of the region you'd like to capture, then press enter.

Next move to the bottom right of the region you're looking for, and again, press enter.

It will print out your region co-ordinates, go ahead and use that along with the following code

pyautogui.locateOnScreen('example.png', region=(0,0,0,0)) 

#Fill in your region co-ords there

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 JustAnotherPyGuy