ImageGrab of PIL library offers great skills to capture your screen with Python conveniently.

In this tutorial we will demonstrate how to do that with a few lines of codes.

Holy Python is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Used Where?

  • To capture screen
  • Face Recognition
  • Interacting with games and software
  • Research
  • Security
  • Surveillance

Let’s import ImageGrab from the PIL the library along with opencv library (cv2):

from PIL import ImageGrab
import cv2

Estimated Time

5 mins

Skill Level

Intermediate

Modules

ImageGrab

Libraries

opencv (cv2), PIL

Tutorial Provided by

HolyPython.com

ImageGrab in use

Now let’s create a screen variable which contains ImageGrab.grab object as an array.
(You can adjust the resolution to your liking, in this case it’s 800×600):

screen = np.array(ImageGrab.grab(bbox=(0,0,800,600)))

And we can use imshow function of cv2 to show the screen in a window like this:
(You can give the window whatever name you’d like, in this case it’s “Python Window”)

cv2.imshow('Python Window', screen)

Now, what you wanna do is, put both inside a loop so that screen is grabbed and window is showed continously. While True can be used to create an infinite loop:

while True:
    screen = np.array(ImageGrab.grab(bbox=(0,0,800,600)))
    cv2.imshow('window', screen)

Finally a strategy is needed to escape the infinite loop when you’re done.
Pressing “q” key while the Python Window is active is a common approach.
It can be achieved as below:

    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

Here is the full code:

from PIL import ImageGrab
import cv2

while True:
    screen = np.array(ImageGrab.grab(bbox=(0,0,800,600)))
    cv2.imshow('Python Window', screen)

    if cv2.waitKey(25) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
        break

Conclusion

ImageGrab makes it very powerful to extract visuals from your screen. You don’t have to show it with “im” all the time and it can be used for tasks such as Machine Learning on games, videos and movies.

ImageGrab also makes it very straightforward to capture screenshots and you can check out this tutorial for that.

Pixel positions

Recommended Posts