在Python中录制视频,你可以使用多种第三方库,例如`pillow`、`opencv-python`、`numpy`和`pynput`。以下是一个使用`pillow`和`opencv-python`进行屏幕录制的示例代码:
```python
import time
from datetime import datetime
from PIL import ImageGrab
import cv2
import numpy as np
def video_record():
录入视频
name = datetime.now().strftime('%Y-%m-%d %H-%M-%S') 当前的时间(用作文件名)
screen = ImageGrab.grab() 获取当前屏幕
width, height = screen.size 获取当前屏幕的大小
fourcc = cv2.VideoWriter_fourcc(*'XVID') MPEG-4编码,文件后缀可为.avi等
video = cv2.VideoWriter(f'{name}.avi', fourcc, 15, (width, height)) (文件名,编码器,帧率,视频宽高)
print('3秒后开始录制 - 可选')
time.sleep(3)
print('开始录制!')
global start_time
start_time = time.time()
while True:
获取屏幕截图
img = ImageGrab.grab()
将截图转换为OpenCV格式
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) OpenCV使用BGR格式
写入视频
video.write(frame)
按下q键退出录屏
if cv2.waitKey(1) & 0xFF == ord('q'):
break
释放资源
video.release()
cv2.destroyAllWindows()
video_record()
这段代码会创建一个名为`当前时间.avi`的视频文件,其中包含屏幕的录像。你可以根据需要调整帧率、视频大小等参数。