from tkinter import filedialog
import os
import cv2
def saveImage(video_name: str,
interval: int = 60,
start: int = 0,
end: int = -1,
output_dir: str = './source/image/',
prefix: str = '',
suffix: str = '.png',
zip_level: int = 9):
"""
video_name: 视频文件名
interval: 抽帧间隔
start: 开始帧
end: 结束帧
output_dir: 输出目录
prefix: 输出文件名前缀
suffix: 输出文件名前缀
zip_level: 压缩比例 0-9
"""
if not video_name:
return
# 输出的文件名前缀
fnhead = os.path.join(output_dir, prefix)
# 输出目录
pathdir = os.path.dirname(fnhead)
print(pathdir)
# 创建输出目录
if not os.path.exists(pathdir):
os.makedirs(pathdir)
# 读取视频文件
videoCapture = cv2.VideoCapture(video_name)
i = 0
sn = 0
success = True
while success:
success, frame = videoCapture.read()
i += 1
if i <= start:
continue
if end > 0 and i >= end:
break
if not success:
break
if i % interval == 0:
sn += 1
tfn = '%s%s%s' % (fnhead, sn, suffix)
cv2.imwrite(tfn, frame, [cv2.IMWRITE_PNG_COMPRESSION, zip_level])
print(sn, i, tfn)
print("end")
if __name__ == "__main__":
fn = filedialog.askopenfilename(initialdir='.')
print(fn)
saveImage(fn, interval=90, prefix='test')