Skip to content

[Python] How to use OpenCV to Record screen

Last Updated on 2021-04-01 by Clay

Today I want to share with you how to screen by Python. The goal is to save the video file after the screening finished.

There is a simple sample code. Of course, there are many function you can add: just like a GUI? send a video in real time by Socket?

Maybe you can try it. Nobody can tell you "Hey! Dude, it's so crazy!"

from PIL import ImageGrab
import numpy as np
import cv2

image = ImageGrab.grab()
width, height = image.size

fourcc = cv2.VideoWriter_fourcc(*'XVID')
video = cv2.VideoWriter('test.avi', fourcc, 25, (width, height))

while True:
    img_rgb = ImageGrab.grab()
    img_bgr = cv2.cvtColor(np.array(img_rgb), cv2.COLOR_RGB2BGR)
    video.write(img_bgr)
    cv2.imshow('imm', img_bgr)

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

video.release()
cv2.destroyAllWindows()


First, we need two packages PIL and opencv, if they all not in your computer, maybe you can command to install them:

pip install pillow
pip install opencv-python 

The loop in the middle block is screening. If you want to exit the loop, you can press the "Q" button.

The file we saved in the current folder. It's name is what we set in our code: test.avi.

Anyway, the above is the tutorial to teach you how to screen by Python, I hope it will help you.

Tags:

Leave a ReplyCancel reply

Exit mobile version