In this tutorial, we will introduce you how to create a screen recorder using python opencv, it is very useful if you want record something.
We should install python opencv and pillow library.
How to create a screen recorder?
We will take the snapshot of the screen using python pillow, then write these images to a video file using python opencv.
How to create a screen recorder using python opencv?
We will tell you how to do step by step.
# coding: utf-8 from PIL import ImageGrab import numpy as np import cv2
Set some options
fps = 20 start = 3 end = 15
We will set the fps of video is 20, and record 12 seconds.
Get the size of the screen
We will use python pillow ImageGrab to get the size of screen.
curScreen = ImageGrab.grab() height, width = curScreen.size
You also can get the size of screen using pyautogui, here is an example:
Create a video object using opencv
video = cv2.VideoWriter('video.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, (height, width))
We will use fps, the size of screen to create a video object.
Start to record the screen
imageNum = 0 while True: imageNum += 1 captureImage = ImageGrab.grab() frame = cv2.cvtColor(np.array(captureImage), cv2.COLOR_RGB2BGR) if imageNum > fps * start: video.write(frame) if cv2.waitKey(50) == ord('q') or imageNum > fps * end: break video.release() cv2.destroyAllWindows()
We will use a while loop to take each frame of video, then write these frames to video file.
Run this code, you will get a video.avi file.