How to save screenshot to folder using python?

227 Views Asked by At

I am attempting to use a Haar Cascade for object detection, and I need to take screenshots of an object across ~1000 images. Is there a way that I can screenshot a certain part of an image and have it automatically saved to a specific folder using Python?

1

There are 1 best solutions below

0
Ingwersen_erik On

You can use pyautogui for that. If you don't have it already installed on your machine, first you'll have to pip install it:

pip install pyautogui

After you install pyautogui, you can take screenshots using the code as follows:


import os
import pyautogui

save_screenshot_folder = './'

# Call pyautogui.screenshot, specifying the filepath where you want to store the screenshot.
pyautogui.screenshot(
    f'{save_screenshot_folder}{os.path.sep}SCREENSHOT_{datetime.now().strftime("%Y-%m-%d_%H-%M")}.png'
)

Screenshot portion of the screen

To take a screenshot of just a portion of the screen, add the window boundaries as one of the aforementioned function parameters:


import pyautogui

im = pyautogui.screenshot(region=(0, 0, 300, 400))

Hint: to find out the exact x, and y pixel positions of the screen you want to use, pyautogui comes with a function that launches a widget to help you determine the mouse position:


import pyautogui

pyautogui.mouseInfo()

enter image description here

You can find additional information on how to use it here