Python OpenCV: Create a Screen Recorder – A Step Guide

In this tutorial, we will use some steps to introduce how to create a screen recorder using python opencv.

Python OpenCV: Create a Screen Recorder - A Step Guide

1.Install opencv and pyautogui

pip install pyautogui
pip install opencv-python

We will use pyautogui to get the size of screen.

2.Import library

import cv2 as cv
import pyautogui
import numpy as np

3.Get screen size usin pyautogui

#(width,height)
screen_size=pyautogui.size()

4.Initialize the pytho opencv VideoWriter() object

#initialize the object
video = cv.VideoWriter('Recording.avi', 
                        cv.VideoWriter_fourcc(*'MJPG'), 
                        20, 
                        screen_size)

5.Start to record screen

print("Recording.....")
while True:
    #click screen shot
    screen_shot_img = pyautogui.screenshot()

    #convert into array
    frame = np.array(screen_shot_img)

    #change from BGR to RGB
    frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)

    #write frame
    video.write(frame)

    #display the live recording 
    cv.imshow("Recording Frame(Minimize it)", frame)    
    if cv.waitKey(1) == ord("q"):
        break

cv.destroyAllWindows()
video.release()

In this example code, screen video is saved in Recording.avi