视频是按照一定规则组织的图像序列,我们按照规则获取即可
cap = cv2.VideoCapture(video_filepath)
# 读取视频的基本信息
# 获取FPS
fps = int(cap.get(cv2.CAP_PROP_FPS))
# 获取总共帧的个数
total_slice = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 获取视频的宽和高
height, width = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
Note: 获取的fps
与 total_slice
为浮点数,这里转化为整型
import cv2
import numpy as np
def extract_frame(video_filepath, save_image_filepath, start_time, end_time, clip_num=1, log=False, dsize=None, image_count=0, direction=1):
cap = cv2.VideoCapture(video_filepath)
# 读取视频的基本信息
# 获取FPS
fps = int(cap.get(cv2.CAP_PROP_FPS))
# 获取总共帧的个数
total_slice = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 获取视频的宽和高
height, width = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)), int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
if log:
print(f"video info: fps: {fps}, slice sum: {total_slice}, height: {height}, width: {width}")
images = []
frames = [fps * clip_num * j + image_count for j in range(start_time, end_time)]
if cap.isOpened():
for i in range(int(total_slice)):
ret, frame = cap.read()
image = frame
if dsize is not None:
image = cv2.resize(src=frame, dsize=dsize, interpolation=cv2.INTER_LINEAR)
if i in frames:
images.append(image)
# 释放内存
cap.release()
images = np.concatenate(images, axis=direction)
cv2.imwrite(filename=save_image_filepath, img=images)
if __name__ == '__main__':
video_filepath = "/sharefiles1/hanliqiang/pythonProject/Pyhton_movie/CTRL.mp4"
save_image_filepath = "./test_extract_images.png"
extract_frame(video_filepath=video_filepath, save_image_filepath=save_image_filepath, start_time=15,end_time=25)
pass
image_count=15
来获取中间帧resize
,指定图像大小即可,这里为tuple
类型direction=0
水平拼接, direction=1
垂直拼接clip_num
为间隔帧视频资料请自行下载 https://www.bilibili.com/video/BV1td4y1T7CB
clip_num = 2
clip_num=1
python实现读取和保存视频: https://blog.csdn.net/weixin_52777510/article/details/119872183