Create a Screen Recorder using Python



By using this screen recorder code, the desktop of your computer gets recorded and the recording is then in the form of a video using Python language. This tool uses different libraries such as pyautogui for capturing the screen, cv2 for writing and displaying videos and numpy for image purposes. The conclusion is in form of a raw video file which registers ten seconds of interaction in real screen activity at a frame rate of 60 frames per second.

Required Libraries

  • PyAutoGUI − This library is used for taking screenshots of your screen.
  • OpenCV (cv2) − OpenCV (open computer vision library) is used for processing the image and writing the video file.
  • NumPy − NumPy is used to handle the image data as arrays.

Installing Libraries

To install these librraies, run the following command using PIP −

pip install pyautogui opencv-python-headless numpy

Steps to Create a Screen Recorder

Step 1: Import libraries

The first step is to import the required libraries. Use the following code statements to import the libraries −

import pyautogui
import cv2
import numpy as np

Step 2: Set Screen Resolution and Define Video Properties

Use the following code statements to set screen resolution and define video properties −

screen_resolution = (1920, 1080)
video_codec = cv2.VideoWriter_fourcc(*"XVID")
output_filename = "ScreenCapture.avi"
frame_rate = 60.0
num_frames = int(frame_rate * 10)  # Capturing for 10 seconds

Step 3: Initialize Video Writer

Use the following code statements to initialize video writer −

video_writer = cv2.VideoWriter(output_filename, video_codec, frame_rate, screen_resolution)

Step 4: Create Display Window

Use the following code statement to create display window −

cv2.namedWindow("Screen Capture", cv2.WINDOW_NORMAL)
cv2.resizeWindow("Screen Capture", 480, 270)

Step 5: Start Capturing Frames

Capture the frames by using the loop, use the following code statements −

for _ in range(num_frames):
   screenshot = pyautogui.screenshot()
   frame_array = np.array(screenshot)
   frame_rgb = cv2.cvtColor(frame_array, cv2.COLOR_BGR2RGB)
   video_writer.write(frame_rgb)
   cv2.imshow("Screen Capture", frame_rgb)

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

Step 6: Release Resources and Close Windows

Use the following code to release resources and close windows −

video_writer.release()
cv2.destroyAllWindows()

Python Code to Create a Screen Recorder

import pyautogui
import cv2
import numpy as np

# Set the screen resolution
screen_resolution = (1920, 1080)

# Define the video codec
video_codec = cv2.VideoWriter_fourcc(*"XVID")

# Name the output video file
output_filename = "ScreenCapture.avi"

# Set the frames per second (fps)
frame_rate = 60.0

# Set the number of frames to capture
num_frames = int(frame_rate * 10)  # Capturing for 10 seconds

# Initialize the VideoWriter object
video_writer = cv2.VideoWriter(output_filename, video_codec, frame_rate, screen_resolution)

# Create a window named 'Screen Capture'
cv2.namedWindow("Screen Capture", cv2.WINDOW_NORMAL)

# Adjust the window size
cv2.resizeWindow("Screen Capture", 480, 270)

# Start capturing the screen
for _ in range(num_frames):
   # Capture the screen using PyAutoGUI
   screenshot = pyautogui.screenshot()

   # Convert the captured image to a numpy array
   frame_array = np.array(screenshot)

   # Convert the color from BGR to RGB
   frame_rgb = cv2.cvtColor(frame_array, cv2.COLOR_BGR2RGB)

   # Write the frame to the video file
   video_writer.write(frame_rgb)

   # Display the captured frame in the window
   cv2.imshow("Screen Capture", frame_rgb)

   # Stop the recording if the 'q' key is pressed
   if cv2.waitKey(1) == ord('q'):
      break

# Release the video writer object
video_writer.release()

# Close all OpenCV windows
cv2.destroyAllWindows()

Output

After you run the program, you will see live capturing box

Screen Recorder

After close the tab you will see your AVI file is automatically saved −

Screen Recorder

Now check your file open it your video player we open it window Films & TV application −

Screen Recorder

The output of this code is a video file named ScreenCapture.avi that captures 10 seconds of your screen activity at a frame rate of 60 fps. You can view this file using any video player that supports AVI format.

Code Explanation

1. Captures Your Screen

By its nature, the scripts most important task is to write about the contents of the screen. This is done by taking shots at different instances, of the screen housing the application being considered.

2. Taking Screenshots

The pyautogui library is used to capture the screen shot of given website. It is quite simple to capture the entire screen or a certain part of it using PyAutoGUI.

3. Specified Frame Rate

Screenshots are captured at a frame rate, this is the value stored in the variable frame_rate. In this case it is set at 60 frames per second (fps). This helps to make the video free from shakes and this makes the motion smooth.

4. Saving Screenshots as a Video

As stated, the screenshots are not stored individually but in the form of a video file. This is achieved using the cv2 library (OpenCV) that has functionalities for Video writing as well as processing.

5. Handling Video Writing and Display

The cv2 is then used to create a video file commonly known as the VideoWriter object, which is used to add each and every screenshot as frame in the video. It also regulates the manner the video is displayed within a window in the course of capture.

6. Using NumPy for Image Data

OpenCV fails to read the screenshots captured by PyAutoGUI thus the need to utilize the numpy library to transform the captured format to OpenCV amenable format. This conversion is very essential in the case of image data so that different libraries can share them.

7. Recording and Visualizing Programmatically

By virtual of the script, possibilities of making automatic recording of the activity on the screen without having to record it manually are achieved. The libraries such as PyAutoGUI, NumPy, OpenCV make it easier and automated when it comes to capturing the screen and generating a video.

8. Script Structure

A loop is used to take screenshots for the duration of the script that may be set at 10 seconds and then using the video converter tool, the screenshot is converted into the desired format and then written into the video file.

9. Display During Capture

There is also the facility of a window showing the frame under capture during the course of the script. What this enables users to do is to view what is being recorded in real time.

10. Final Video Output

Once the recording is done, a script stores all the captured frames into the given video file which makes a continuous video of the screen activities over the period of time.

python_reference.htm
Advertisements