#!/usr/bin/env python
# -*- coding = utf-8 -*-
# @Time : 2021/10/6 17:43
# @Author : Leuanghing Chen
# @Blog : https://blog.csdn.net/weixin_46153372?spm=1010.2135.3001.5421
# @File : python实现录屏功能.py
# @Software : PyCharm
# 发布程序:pyinstaller -F -w -i F:\python_demo\2.ico F:\python_demo\python实现录屏功能.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
# 录入视频
def video_record():
# 加了global,则可以在函数内部对函数外的对象进行操作了,也可以改变它的值了
global name
name = datetime.now().strftime('%Y-%m-%d %H-%M-%S') # 当前的时间(当文件名)
screen = ImageGrab.grab() # 获取当前屏幕
width, high = screen.size # 获取当前屏幕的大小
fourcc = VideoWriter_fourcc('X', 'V', 'I', 'D') # MPEG-4编码,文件后缀可为.avi .asf .mov等
video = VideoWriter('%s.avi' % name, fourcc, 15, (width, high)) # (文件名,编码器,帧率,视频宽高)
for i in range(3):
time.sleep(1)
print("倒计时:{}".format(3-i))
print('开始录制!')
global start_time
start_time = time.time()
while True:
if flag:
print("录制结束!")
global final_time
final_time = time.time()
video.release() # 释放
break
im = ImageGrab.grab() # 图片为RGB模式
imm = cvtColor(np.array(im), COLOR_RGB2BGR) # 转为opencv的BGR模式
video.write(imm) # 写入
# time.sleep(5) # 等待5秒再次循环
# 结束监听按键,按下esc结束录屏
def on_press(key):
global flag
# esc键
if key == keyboard.Key.esc:
flag = True # 改变
return False # 返回False,键盘监听结束!
# 视频信息
def video_info():
video = VideoCapture('%s.avi' % name) # 记得文件名加格式不要错!
fps = video.get(CAP_PROP_FPS)
count = video.get(CAP_PROP_FRAME_COUNT)
size = (int(video.get(CAP_PROP_FRAME_WIDTH)), int(video.get(CAP_PROP_FRAME_HEIGHT)))
print('帧率=%.1f' % fps)
print('帧数=%.1f' % count)
print('分辨率', size)
print('视频时间=%.3f秒' % (int(count)/fps))
print('录制时间=%.3f秒' % (final_time-start_time))
print('推荐帧率=%.2f' % (fps*((int(count)/fps)/(final_time-start_time))))
if __name__ == '__main__':
flag = False
th = threading.Thread(target=video_record)
th.start()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
time.sleep(1) # 等待视频释放过后
video_info()
|