截图生成视频的Python程序

我十几年前有过一个习惯,会把自己每天电脑屏幕的内容截图生成一个视频,这样每天看视频就知道自己做了什么。

这几天突然又想到了这件事,但是当年开发的程序是 Delphi 写的,已经在 Windows 11 上跑不起来了,于是用 Python 重新写了一个,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import pyautogui
import time
import datetime
import cv2
import os
from moviepy.editor import VideoFileClip, concatenate_videoclips

def create_video(image_folder, video_name):
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'mp4v'), 24, (width, height)) # 24是帧数

for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
os.remove(os.path.join(image_folder, image)) # 删除图片

cv2.destroyAllWindows()
video.release()

def find_videos_of_the_day(directory, date):
videos = []
for file in os.listdir(directory):
if file.endswith(".mp4") and date in file:
videos.append(file)
videos.sort(key=lambda x: os.path.getmtime(os.path.join(directory, x)))
return videos

def merge_videos(videos, output_filename):
clips = [VideoFileClip(video) for video in videos]
final_clip = concatenate_videoclips(clips)
final_clip.write_videofile(output_filename, codec="libx264")

try:
while True:
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
screenshot_filename = f"screenshot_{timestamp}.png"

screenshot = pyautogui.screenshot()
screenshot.save(screenshot_filename)
print(f"截图已保存: {screenshot_filename}")

time.sleep(10)

except KeyboardInterrupt:
today_date = datetime.datetime.now().strftime("%Y%m%d")
existing_videos = find_videos_of_the_day('.', today_date)

choice = input("你要生成视频吗?(是/否): ")
if choice.lower() == '是':
print("正在生成视频...")

# 创建新视频文件
new_video_filename = f"temp_video_{today_date}.mp4"
create_video('.', new_video_filename)

# 合并视频
final_videos = existing_videos + [new_video_filename]
output_filename = f"video_{today_date}.mp4"
merge_videos(final_videos, output_filename)
os.remove(new_video_filename) # 删除临时视频文件

print(f"视频{output_filename}生成完毕,所有截图已删除。")

如果缺什么直接用 pip install 安装一下对应的就可以。

如果需要生成为 exe 文件,可以用 PyInstaller ,用法如下:

1
pyinstaller --onefile yourscript.py

功能就是截图,然后把这一天的所有截图和视频合并为一个视频。