录屏python代码

#Here is a simple Python code for screen recording using OpenCV library:
# ```python 
# ---- pip install numpy pillow opencv-python pyautogui ----
# cv2 from package of  opencv-python
import cv2
import numpy as np
import pyautogui

# Specify resolution
resolution = (1920, 1080)
#自动获取屏幕分辨率
#screen_width, screen_height = pyautogui.size()
#fourcc = cv2.VideoWriter_fourcc(*"XVID")
#out = cv2.VideoWriter("screen_recording.avi", fourcc, 20.0, (screen_width, screen_height))

# Specify video codec
codec = cv2.VideoWriter_fourcc(*"XVID")

# Specify name of Output file
filename = "Recording.avi"

fps = 60.0
out = cv2.VideoWriter(filename, codec, fps, resolution)
print("开始录制……文件名:" + filename)
print("Ctrl+停止录制......")
while True:
    img = pyautogui.screenshot()
    frame = np.array(img)
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    out.write(frame)
    if cv2.waitKey(1) == ord('q'):   #不知为什么,按q键无法退出运行!!!
        print("ctrl+c结束录屏")
        break

out.release()
cv2.destroyAllWindows()