Python截取视频封面

Python 实现截取指定帧作为视频封面

近期项目中有一批视频需要将第一帧提取出来保存为图片,功能比较简单,核心是使用cv2库加载视频并逐帧读取,判断是需要保存的帧则保存。

1
2
3
4
# 加载视频
video_capture = cv2.VideoCapture(file_path)
# 逐帧读取
cap_info, frame = video_capture.read()

完整代码如下,记录备忘:

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
import os
import cv2

class video:
def __init__(self):
# 文件读取目录 存放视频文件的目录
self.load_dir = ""
# 文件输出目录
self.save_dir = "./output/image/"
# 视频文件后缀
self.video_ext = '.mp4'

def save_image(self, image, file_name, num):
file_name = file_name.replace(self.video_ext, "")
save_path = self.save_dir + file_name + "_" + str(num) + '.jpg'
res = cv2.imencode('.jpg', image)[1].tofile(save_path)
# 使用imwrite直接保存中文文件名会乱码
# res = cv2.imwrite(save_path, image)
print(res)
print("保存文件: %s" % save_path)

def load_video(self, file_name, cap):
file_path = self.load_dir + file_name
if os.path.exists(file_path) == False:
print("文件不存在:%s" % file_path)
return

# 读取视频文件
video_capture = cv2.VideoCapture(file_path)
# 读帧
cap_info, frame = video_capture.read()
i = 0

while cap_info:
if cap == i:
self.save_image(frame, file_name, i)
break
cap_info, frame = video_capture.read()
i = i + 1

def loop_load_video(self, cap):
for filename in os.listdir(self.load_dir):
self.load_video(filename, cap)


if __name__ == '__main__':
print("欢迎来到Video的世界!")
tool = video()
tool.loop_load_video(0)