Python截取视频中的图片

安装

1
2
pip install ffmpy -i https://mirrors.aliyun.com/pypi/simple/
pip3 install opencv-python -i https://mirrors.aliyun.com/pypi/simple/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
import uuid
from ffmpy import FFmpeg

# 视频裁剪
def cut_out_video(video_path: str, output_dir: str, start_pix: tuple, size: tuple):
ext = os.path.basename(video_path).strip().split('.')[-1]
if ext not in ['mp4', 'avi', 'flv']:
raise Exception('format error')
result = os.path.join(output_dir, '{}.{}'.format(uuid.uuid1().hex, ext))
ff = FFmpeg(inputs={video_path: None},
outputs={
result: '-vf crop={}:{}:{}:{} -y -threads 5 -preset ultrafast -strict -2'.format(size[0], size[1],
start_pix[0],
start_pix[1])})
print(ff.cmd)
ff.run()
return result


if __name__ == '__main__':
print(cut_out_video(r'C:\Users\huyi\Desktop\test2.mp4', r'C:\Users\huyi\Desktop', (0, 0), (512, 512)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import cv2

vc = cv2.VideoCapture("f:\\Videos\\4K Tokkit\\dbxbqm22\\7257911883674668289.mp4")
# 检查视频是否成功打开
if not vc.isOpened():
print("无法打开视频文件")
exit()
fps = vc.get(cv2.CAP_PROP_FPS)

c = 0
num = round(fps)
while True:
ret, frame = vc.read()
pic_path = 'f:\\Videos\\4K Tokkit\\test/'
if not ret:
break
if (c % round(fps) == 0):
cv2.imwrite(pic_path + '7257911883674668289_' + str(c) + '.jpg', frame)
c = c + 1
vc.release()
cv2.destroyAllWindows()

写入中文路径处理

cv2.imreadcv2.imwrite无法读写含中文的路径。

1
2
3
import cv2
image = cv2.imdecode(np.fromfile('中文图片.png'), cv2.IMREAD_UNCHANGED)
cv2.imencode('.png', image)[1].tofile('保存_中文图片.png')

本文地址: https://github.com/maxzhao-it/blog/post/8ddf92f3/