1. Introduction
In Python, we can use multiple powerful libraries to implement rich functions, such as screen recording and keyboard monitoring. Today, we will implement a simple screen recording tool by combining PIL (Pillow, a branch of Python Imaging Library), OpenCV, pynput, and threading, which can control the beginning and end of recording by listening to keyboard events.
2. Introduction to the required library
- PIL (Pillow): used for screenshots.
- OpenCV: Used for the creation and writing of video files.
- pynput: used to listen for keyboard events.
- threading: used to execute code in parallel, implement screen recording and keyboard monitoring at the same time.
3. Detailed explanation of the code
Import the required library
import time import threading from datetime import datetime from PIL import ImageGrab import numpy as np from cv2.cv2 import cvtColor, VideoWriter_fourcc, VideoWriter, COLOR_RGB2BGR, VideoCapture, \ CAP_PROP_FPS, CAP_PROP_FRAME_COUNT, CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT from pynput import keyboard
Define video recording function
def video_record(): # ... (Some codes are omitted) while True: if flag: # ... (Some codes are omitted) break im = () # screenshot imm = cvtColor((im), COLOR_RGB2BGR) # Convert color mode (imm) # Write to video file
This function first gets the current time as the file name, and then initializes the video writing object. Next, it displays a 3-second countdown before recording the screen begins. During recording, it continuously checks a global variable
flag
,ifflag
BecomeTrue
, then stop recording and release the video writing object.
Define keyboard listening function
def on_press(key): global flag if key == : flag = True return False
This function will listen to keyboard events when pressed
esc
When key, global variables areflag
Set asTrue
and returnFalse
to stop keyboard listening.
Define video information printing function
def video_info(): # ... (Some codes are omitted) print('Frame rate=%.1f' % fps) # ... (Some codes are omitted) print('推荐Frame rate=%.2f' % (fps*((int(count)/fps)/(final_time-start_time))))
This function will read the information of the video file after recording, including frame rate, frame number, resolution, and recording time, and print it out. At the same time, it will calculate and print a recommended frame rate, which is calculated based on the actual recording time and the number of frames in the video file.
Main function
if __name__ == '__main__': flag = False th = (target=video_record) () with (on_press=on_press) as listener: () (1) # Wait for the video to be released video_info()
- In the main function, we first initialize the global variable flag to False, and then create a thread to run the video_record function. Next, we use the pynput library to listen for keyboard events and use the on_press function as a callback function. When the keyboard listening ends (i.e. after pressing the esc key), the main thread will wait 1 second to ensure that the video file is released correctly, and then call the video_info function to print the video information.
4. Complete code
#!/usr/bin/env python # -*- coding = utf-8 -*- # @Time : 2021/10/6 17:43 # @Author : Leuanghing Chen # @Blog : /weixin_46153372?spm=1010.2135.3001.5421 # @File: python implements screen recording function.py# @Software : PyCharm # Publishing program: pyinstaller -F -w -i F:\python_demo\ F:\python_demo\python implements screen recording function.py import time import threading from datetime import datetime from PIL import ImageGrab import numpy as np from cv2.cv2 import cvtColor, VideoWriter_fourcc, VideoWriter, COLOR_RGB2BGR, VideoCapture,\ CAP_PROP_FPS, CAP_PROP_FRAME_COUNT, CAP_PROP_FRAME_WIDTH, CAP_PROP_FRAME_HEIGHT from pynput import keyboard # Enter a videodef video_record(): # Add global, you can operate objects outside the function inside the function, or change its value global name name = ().strftime('%Y-%m-%d %H-%M-%S') # Current time (when file name) screen = () # Get the current screen width, high = # Get the current screen size fourcc = VideoWriter_fourcc('X', 'V', 'I', 'D') # MPEG-4 encoding, file suffix can be .avi .asf .mov, etc. video = VideoWriter('%' % name, fourcc, 15, (width, high)) # (File name, encoder, frame rate, video width and height) for i in range(3): (1) print("Countdown:{}".format(3-i)) print('Start recording!') global start_time start_time = () while True: if flag: print("Recording is over!") global final_time final_time = () () # Release break im = () # The picture is in RGB mode imm = cvtColor((im), COLOR_RGB2BGR) # Convert to opencv BGR mode (imm) # Write # (5) # Wait for 5 seconds to loop again # End the monitor button, press esc to end the screen recordingdef on_press(key): global flag # Esc if key == : flag = True # Change return False # Return to False, the keyboard listening ends! # Video informationdef video_info(): video = VideoCapture('%' % name) # Remember to add the file name and formatting to the file name! fps = (CAP_PROP_FPS) count = (CAP_PROP_FRAME_COUNT) size = (int((CAP_PROP_FRAME_WIDTH)), int((CAP_PROP_FRAME_HEIGHT))) print('Frame rate=%.1f' % fps) print('Number of frames=%.1f' % count) print('Resolution', size) print('Video time=%.3fSecond' % (int(count)/fps)) print('Recording time=%.3fSecond' % (final_time-start_time)) print('推荐Frame rate=%.2f' % (fps*((int(count)/fps)/(final_time-start_time)))) if __name__ == '__main__': flag = False th = (target=video_record) () with (on_press=on_press) as listener: () (1) # Wait for the video to be released video_info()
5. Summary
By combining multiple Python libraries, we implement a simple screen recording tool that can record screens in real time and control the start and end of recording by listening to keyboard events. This tool can not only be used for personal entertainment or learning, but also serves as the basis for developing screen recording functional applications. Hopefully this blog post can help you better understand how to use Python to implement screen recording and keyboard monitoring.
The above is the detailed content of using Python to implement screen recording and keyboard monitoring functions. For more information about Python screen recording and keyboard monitoring, please follow my other related articles!