Screen recording enables you to create demonstration videos, record gaming achievements and create videos that can be shared online on social media, many industrial softwares exists out there that can help you do that very easily though. In this tutorial, you will learn how to make your own simple screen recorder in Python that you can extend on your own needs.
Let's get started, first, install the required dependencies for this tutorial:
pip3 install numpy opencv-python pyautogui
The process is as follows:
Importing necessary modules:
import cv2 import numpy as np from time import perf_counter import pyautogui
Let's initialize the format we gonna use to write our video file ( named "output.avi" ):
# display screen resolution, get it from your OS settings SCREEN_SIZE = (1920, 1080) # define the codec fourcc = cv2.VideoWriter_fourcc(*"XVID") # create the video write object out = cv2.VideoWriter("output.avi", fourcc, 20.0, (SCREEN_SIZE))
Note: You need to get the correct SCREEN_SIZE from your operating system, that is the screen resolution, otherwise writing to the file won't work.
The 20.0 float value passed as third parameter to cv2.VideoWriter corresponds to the FPS ( Frame Per Second ).
Now we need to keep capturing screenshots and writing to the file in a loop until the user clicks the "q" button, here is the main loop for that:
while True: # make a screenshot img = pyautogui.screenshot() # convert these pixels to a proper numpy array to work with OpenCV frame = np.array(img) # convert colors from BGR to RGB frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # write the frame out.write(frame) # show the frame cv2.imshow("screenshot", frame) # if the user clicks q, it exits if cv2.waitKey(1) == ord("q"): break # make sure everything is closed when exited cv2.destroyAllWindows() out.release()
After converting the screenshot to a numpy array, I need to mention that you need to convert that frame into RGB, that's because OpenCV uses BGR by default.
After you are done with recording, just click "q", it will destroy the window and finish writing to the file, try it out!
There are endless of ideas you can use to extend this small recipe. For example, you can create keyboard shortcuts that starts, pauses and stops recording. This tutorial may help you: How to Control your Keyboard in Python.
Learn also: How to Download All Images from a Web Page in Python.
Happy Coding ♥View Full Code