GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • The Python Code
  • Tutorials
  • Ethical Hacking
  • Machine Learning
  • General Python Tutorials
  • Web Scraping
  • Finance
  • Computer Vision
  • Python Standard Library
  • Application Programming Interfaces
  • Database
  • Game Development
  • Web Programming
  • Digital Forensics

This view

  • Original page
  • New address

GeezerVison is showing thepythoncode.com — How to Record your Screen in Python - The Python Code

Ready to take Python coding to a new level? Explore our Python Code Generator. The perfect tool to get your code up and running in no time. Start now!

Screen recording enables you to create demonstration videos, record gaming achievements, and create videos that can be shared online on social media. Many industrial software exist 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 further extend to your own needs.

This tutorial is about recording your whole screen. If you want to record a specific window, then check this tutorial, as it's exactly what you need.

Related: How to Use Steganography to Hide Secret Data in Images in Python.

Let's get started, first, install the required dependencies for this tutorial:

pip3 install numpy opencv-python pyautogui

The process of this tutorial is as follows:

  • Capture a screenshot using pyautogui.
  • Convert that screenshot to a numpy array.
  • Write that numpy array to a file with the proper format using a video writer in OpenCV.

Importing necessary modules:

import cv2
import numpy as np
import pyautogui

Let's initialize the format we gonna use to write our video file ( named "output.avi" ):

# display screen resolution, get it using pyautogui itself
SCREEN_SIZE = tuple(pyautogui.size())
# define the codec
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# frames per second
fps = 12.0
# create the video write object
out = cv2.VideoWriter("output.avi", fourcc, fps, (SCREEN_SIZE))
# the time you want to record in seconds
record_seconds = 10

We're getting the screen resolution from the pyautogui.size() function, which returns the height and the width of the screen as a two-integer tuple.

fourcc is the video codec library that OpenCV will use to write the video file, we specified XVID here. We also set the FPS to 12.0 and pass these parameters to the cv2.VideoWriter() object.

The record_seconds is the number of seconds you want to record, if you want to record until pressing the "q" button, then simply set this to a large value.

Now we need to keep capturing screenshots and writing to the file in a loop until the seconds are passed or the user clicks the "q" button, here is the main loop for that:

for i in range(int(record_seconds * fps)):
    # 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()

First, we use the screenshot() function, which returns an image object, so we need to convert it to a proper numpy array. After that, we need to convert that frame into RGB, that's because OpenCV uses BGR by default.

The loop will finish once the seconds are passed or if you hit the "q" button. Note that if you increase the FPS, you may see the video is a bit sped up because your CPU can't handle that speed.

If you don't want to see your record in real time, simply comment out the cv2.imshow() line and it won't show anything until the recording is finished.

As mentioned in the pyautogui's official documentation, you can also record only regions of your screen by passing the region keyword argument, which is a four-integer tuple representing the top, left, width, and height of the region to capture; here is how it's done:

img = pyautogui.screenshot(region=(0, 0, 300, 400))

After you are done with recording, just click "q", it will destroy the window and finish writing to the file, try it out!

Alright, there are endless ideas you can use to extend this. For example, you can combine this with an audio recorder, and you'll come up with a Python tool that records your screen and voice simultaneously; you will need to use a thread that records audio and another for the screen recorder. Or you can add an audio file to your video recording.

You can also create keyboard shortcuts that start, pause, and stop the recording, this tutorial can help you.

Learn also: How to Extract Frames from Video in Python

Happy Coding ♥

Loved the article? You'll love our Code Converter even more! It's your secret weapon for effortless coding. Give it a whirl!

View Full Code Generate Python Code
Sharing is caring!

Read also

How to Extract Frames from Video in Python

Making two different methods to extract frames from videos with the timestamp with OpenCV or MoviePy libraries in Python.

How to Generate and Read QR Code in Python

Learning how you can generate and read QR Code in Python using qrcode and OpenCV libraries.

How to Play and Record Audio in Python

Learn how to play and record sound files using different libraries such as playsound, Pydub and PyAudio in Python.

Comments

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!




    Get our free Python guides

    Join 50,000+ Python programmers and enthusiasts like you!

    Topics
    Ethical Hacking Machine Learning General Python Tutorials Web Scraping Finance Computer Vision Python Standard Library Application Programming Interfaces Database Game Development Web Programming Digital Forensics Natural Language Processing Healthcare PDF File Handling Python for Multimedia GUI Programming Cryptography Packet Manipulation Using Scapy
    New tutorials View all
    • How AI Text Detection Works: The Technology Behind Modern AI Detectors
    • Beyond Guesswork: How Python Helps Identify AI-Generated Text
    • Discover the Possibilities of Python Programming
    • How to Track Your AI Visibility with Python
    • How to Automate Excel Reports in Python using Openpyxl
    Popular tutorials View all
    • How to Convert Speech to Text in Python
    • How to Read Emails in Python
    • How to Extract Tables from PDF in Python
    • How to Control your Mouse in Python
    • How to Make a Keylogger in Python
    Practical Python PDF Processing EBook - Topic - Bottom CodingFleet - Topic - Bottom
    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.