python实现录屏功能

发布于:2024-10-17 ⋅ 阅读:(26) ⋅ 点赞:(0)

python实现录屏功能
将生成的avi文件转为mp4格式后删掉avi文件
参考感谢:https://www.cnblogs.com/peachh/p/16549254.html

import os
import cv2
import time
import threading
import numpy as np
from PIL import ImageGrab
from pynput import keyboard
from datetime import datetime
from moviepy.editor import VideoFileClip

flag = False


def video_record():
    global name, start_time, final_time
    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 .asf .mov等
    video = cv2.VideoWriter(f'{name}.avi', fourcc, 20, (width, height))  # (文件名,编码器,帧率,视频宽高)

    print('开始录制!')
    start_time = time.time()
    while True:
        if flag:
            print("录制结束!")
            final_time = time.time()
            video.release()  # 释放
            break
        im = ImageGrab.grab()  # 图片为RGB模式
        imm = cv2.cvtColor(np.array(im), cv2.COLOR_RGB2BGR)  # 转为OpenCV的BGR模式
        video.write(imm)  # 写入


def on_press(key):
    global flag
    if key == keyboard.KeyCode.from_char('1') or key == keyboard.KeyCode.from_char('q'):
        flag = True  # 改变
        return False  # 返回False,键盘监听结束!


def video_info():
    video = cv2.VideoCapture(f'{name}.avi')  # 记得文件名加格式不要错!
    fps = video.get(cv2.CAP_PROP_FPS)
    count = video.get(cv2.CAP_PROP_FRAME_COUNT)
    size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))

    print('帧率=%.1f' % fps)
    print('帧数=%.1f' % count)
    print('分辨率', size)
    print('视频时间=%.3f秒' % (count / fps))
    print('录制时间=%.3f秒' % (final_time - start_time))
    print('推荐帧率=%.2f' % (fps * ((count / fps) / (final_time - start_time))))


def avi_2_mp4():
    # 指定输入文件路径
    avi_file = f'{name}.avi'
    # 指定输出文件路径
    mp4_file = f'{name}.mp4'
    # 使用 VideoFileClip 加载 AVI 文件
    video = VideoFileClip(avi_file)
    # 将视频写入 MP4 文件
    video.write_videofile(mp4_file, codec="libx264")
    # 完成后释放资源
    video.close()
    # 删除原始的AVI文件
    os.remove(avi_file)


def run():
    th = threading.Thread(target=video_record)
    th.start()
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()
    time.sleep(1)  # 等待视频释放过后
    video_info()
    avi_2_mp4()


if __name__ == '__main__':
    run()

效果图

在这里插入图片描述