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 a Specific Window in Python - The Python Code

Step up your coding game with AI-powered Code Explainer. Get insights like never before!

In the recording screen tutorial, we have built a working Python code for recording the entire screen using OpenCV and pyautogui libraries. In this tutorial, you will learn how to record a specific window on your Windows machine using the pygetwindow library and the mentioned libraries.

pygetwindow will provide us with the location, width, and height of the window of our choice, we simply provide a string to the getWindowsWithTitle() method, and it'll return a list of matched windows.

Unfortunately, the code of this tutorial will only work on Windows, as pygetwindow is a library for Windows environment for now.

A lot of the code of this tutorial is explained in the original screen recorder tutorial, make sure to open it up for detailed information.

To get started, let's install the required libraries:

$ pip install numpy opencv-python pyautogui pygetwindow

Open up a new Python file and import the libraries:

import cv2
import numpy as np
import pyautogui
import pygetwindow as gw
import sys

We are going to get the window name from the command-line arguments:

# the window name, e.g "notepad", "Chrome", etc.
window_name = sys.argv[1]

Defining some of our variables:

# define the codec
fourcc = cv2.VideoWriter_fourcc(*"XVID")
# frames per second
fps = 12.0
# the time you want to record in seconds
record_seconds = 10

We want to use an FPS of 12, and record for 10 seconds. Feel free to change record_seconds on your needs. fourcc is the video codec library. Again, check the screen recorder tutorial for detailed info.

Next, we search for the specified window:

# search for the window, getting the first matched window with the title
w = gw.getWindowsWithTitle(window_name)[0]
# activate the window
w.activate()

To search for a window by string, we use the getWindowWithTitle() method, which accepts a string and returns a list of matched windows, we simply take the first one. We use the activate() method to show and focus the window, so if it's minimized, it will be shown on the screen immediately after calling this method.

Finally, the rest of the code is the same as the recording screen tutorial:

# create the video write object
out = cv2.VideoWriter("output.avi", fourcc, fps, tuple(w.size))

for i in range(int(record_seconds * fps)):
    # make a screenshot
    img = pyautogui.screenshot(region=(w.left, w.top, w.width, w.height))
    # 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()

This time, we specify the size of the screen as the window size by passing tuple(w.size). We also specify the region keyword argument in the pyautogui.screenshot() method, the region is a tuple of left position, the top position, width, and height of the window, we simply get those from our window we extracted earlier.

Trying to record notepad for 10 seconds:

$ python record_specific_window.py notepad

This will activate the notepad window (if it is open in your system of course, otherwise it'll raise an IndexError) and start recording for the specified seconds. Here is the output video:

 

The nice thing about this is that the window location automatically changes when you move the window during the recording. However, do not change the size of the window when recording, as it'll corrupt the output video file.

Conclusion

Alright, I think this tutorial will certainly help you if you wanted to record a window in your Windows environment and not the whole screen.

It is worth mentioning that this method only works on the primary screen, if the window happens to be in other monitors, it will simply be recorded as a black screen, so you have to move it into the primary screen of your machine.

You can also comment out the cv2.imshow() method in the loop to remove showing the record in real-time.

Check the full code here.

Learn also: How to Play and Record Audio in Python

Happy coding ♥

Save time and energy with our Python Code Generator. Why start from scratch when you can generate? Give it a try!

View Full Code Explain The Code for Me
Sharing is caring!

Read also

How to Record your Screen in Python

Using pyautogui and OpenCV to record display screen video and save it to a file in Python.

How to Concatenate Video Files in Python

Learn how to join two or more video files using MoviePy library in Python

How to Combine a Static Image with Audio in Python

Learn how to add a static photo to an audio file to form a video file using MoviePy library 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.