How to capture a particular portion of a screen in Python

Here we will learn about how to capture a particular portion of a screen in Python. We need to take a screenshot of a particular portion, for most of the applications in many cases.

We can solve this problem in different ways. Here we will show two easy ways to solve this. First, using ‘pyscreenshot module’ and the second, using ‘pillow module’.

To capture a particular portion of a screen

Before moving forward, if you do not have a pillow or pyscreenshot package, you need to install it first.
Note: We must install the pillow (PIL) package first, before installing the pyscreenshot.

To install pillow (PIL):

pip install Pillow

To install pyscreenshot:

pip install pyscreenshot

You can check: How to install pyscreenshot on Linux – Python


Using pyscreenshot

To capture a particular portion of a screen in Python, we need to import the pyscreenshot package. We will use the grab() function to take a screenshot. we must set pixel positions in the grab() function, to take a part of the screen. show() uses to display the screenshot image. And save() uses to save the image In PIL memory in local storage.

In the grab() function, the entire screen is the default. bbox represents ‘what region to copy’ where we set the pixel positions. The region has a tuple of four coordinates. The coordinates are in order of left, upper, right, lower.

import pyscreenshot
pic = pyscreenshot.grab(bbox=(81, 135, 500, 300))"ss.png")


take part of a screen as screenshot in Python


Using Pillow module

Another way to capture a part of the screen is using the Pillow module (PIL). We cannot import the ImageGrab module directly. So, we need to type like this – from PIL import ImageGrab. Same as the above code, we will use the grab() function and set the coordinates in it. Then we can show and save the screenshot image in PIL format.

from PIL import ImageGrab

pic = ImageGrab.grab(bbox=(81,135,500,300))"ss.png")


How to capture a particular portion of a screen in Python


You can also read:
Taking full screenshots in Python
Convert image from PIL to OpenCV

Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *