Movatterモバイル変換


[0]ホーム

URL:


How to Record a Specific Window in Python

Learn how to record a specific opened window in your Windows machine using pyautogui and pygetwindow libraries in Python.
  · 4 min read · Updated dec 2021 ·Python for Multimedia

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

In therecording screen tutorial, we have built a working Python code for recording the entire screen using OpenCV andpyautogui libraries. In this tutorial, you will learn how to record a specific window on your Windows machine using thepygetwindow 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 thegetWindowsWithTitle() method, and it'll return a list of matched windows.

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

A lot of the code of this tutorial is explained in the originalscreen 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 cv2import numpy as npimport pyautoguiimport pygetwindow as gwimport 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 codecfourcc = cv2.VideoWriter_fourcc(*"XVID")# frames per secondfps = 12.0# the time you want to record in secondsrecord_seconds = 10

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

Next, we search for the specified window:

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

To search for a window by string, we use thegetWindowWithTitle() method, which accepts a string and returns a list of matched windows, we simply take the first one. We use theactivate() 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 objectout = 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 exitedcv2.destroyAllWindows()out.release()

This time, we specify the size of the screen as the window size by passingtuple(w.size). We also specify theregion keyword argument in thepyautogui.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 anIndexError) 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 thecv2.imshow() method in the loop to remove showing the record in real-time.

Check the full codehere.

Learn also:How to Play and Record Audio in Python

Happy coding ♥

Ready for more? Dive deeper into coding with ourAI-powered Code Explainer. Don't miss it!

View Full Code Explain My Code
Sharing is caring!



Read Also


How to Record your Screen in Python
How to Concatenate Video Files in Python
How to Combine a Static Image with Audio in Python

Comment panel

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





    Practical Python PDF Processing EBook - Topic - Top


    Join 50,000+ Python Programmers & Enthusiasts like you!



    Tags


    New Tutorials

    Popular Tutorials


    Practical Python PDF Processing EBook - Topic - Bottom

    CodingFleet - Topic - Bottom






    Claim your Free Chapter!

    Download a Completely Free Practical Python PDF Processing Chapter.

    See how the book can help you build handy PDF Processing tools!



    [8]ページ先頭

    ©2009-2025 Movatter.jp