import cv2
import os
import numpy as np
def get_frame_name(no, fps):
"""
以时分秒的形式给视频的帧命名。
Args:
no (int): 帧在视频中的顺序排位。
fps (int): 帧率(frames per second)。
"""
time_hour = no // (60 * 60 * fps)
time_min = no % (60 * 60 * fps) // (60 * fps)
time_sec = round(no % (60 * 60 * fps) % (60 * fps) / fps * 100)
name = str(time_hour).zfill(2) + str(time_min).zfill(2) + str(time_sec).zfill(4)
return name
def extract_frames(file, interval=5):
"""
从视频文件中抽帧。
Args:
file: 视频路径。
interval: 隔interval帧抽一帧。
Returns:
frames: 图片数组list。
names: 图片名list。
"""
video = cv2.VideoCapture(file) # 打开视频文件
fps = int(video.get(cv2.CAP_PROP_FPS)) # 获取帧率
names = []
frames = []
count = 0
while True:
exist, frame = video.read() # 读取一帧数据
if not exist:
break
if count % (interval + 1) == 0:
names.append(get_frame_name(count, fps))
frames.append(frame)
count += 1
video.release() # 关闭视频
return frames, names
cv2视频转图片
最新推荐文章于 2024-04-30 11:11:45 发布