遍历指定目录下所有的视频,按照指定时间间隔截取视频帧
import os
import cv2
import sys
import time
def save_frame(time_in_sec, file_path):
# 打开视频文件
cap = cv2.VideoCapture(file_path)
# 获取视频的帧率
fps = cap.get(cv2.CAP_PROP_FPS)
# 获取视频的总帧数
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = total_frames / fps
num = 0
while(num < duration):
num = num + time_in_sec
# 计算指定时间对应的帧数
frame_number = int(num * fps)
# 设置视频的当前帧
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
# 读取当前帧
ret, frame = cap.read()
if ret:
timestamp = int(time.time()) # 获取当前时间戳
save_path = f"img\\frame_{frame_number}_{timestamp}.jpg"
# 保存当前帧为图片
cv2.imwrite(save_path, frame)
print("保存成功:" + save_path)
else:
print("读取视频帧失败")
# 关闭视频文件
cap.release()
def traverse_directory(directory):
for root, dirs, files in os.walk(directory):
for file in files:
video_path = os.path.join(root, file)
print(video_path)
save_frame(int(sys.argv[1]), video_path)
# 遍历当前目录
traverse_directory('E:\pro_2_jianke\现场视频数据')
print("运行成功")
执行方式
python3 文件名.py 时间间隔
固定视频,手动输入指定时间点截取视频帧
import os
import cv2
import sys
import time
def save_frame(time_in_sec, file_path):
# 打开视频文件
cap = cv2.VideoCapture(file_path)
# 检查视频文件是否成功打开
if not cap.isOpened():
print("无法打开视频文件")
return
# 获取视频的帧率
fps = cap.get(cv2.CAP_PROP_FPS)
# 计算指定时间对应的帧数
frame_number = int(time_in_sec * fps)
# 设置视频的当前帧
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_number)
# 读取当前帧
ret, frame = cap.read()
if ret:
timestamp = int(time.time()) # 获取当前时间戳
save_path = f"img/1_{frame_number}.jpg"
# 保存当前帧为图片
cv2.imwrite(save_path, frame)
print("保存成功:" + save_path)
else:
print("读取视频帧失败")
# 关闭视频文件
cap.release()
# 遍历当前目录
file_path = 'E:\pro_2_jianke\\vedio\FullScreen_0_20231229T084812Z_20231229T095535Z.mp4'
arr = [2, 115, 125, 853, 915, 972, 1076, 1111, 1200, 1319, 1430, 1453, 1800,
200, 302, 304, 306, 308, 360, 430, 450, 457, 478, 660, 690, 797]
for item in arr:
save_frame(item, file_path)
print("运行成功")
直接执行文件