Python opencv 读取视频中的图片

文章目录

  • 0 前言
  • 1 对取视频对象,并获取基本信息
  • 2 按照fps读取视频帧
  • 3 Experiment Result
  • 参考

0 前言

视频是按照一定规则组织的图像序列,我们按照规则获取即可

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))

Note: 获取的fpstotal_slice 为浮点数,这里转化为整型

2 按照fps读取视频帧

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 为间隔帧

3 Experiment Result

  • 视频资料请自行下载 https://www.bilibili.com/video/BV1td4y1T7CB

  • clip_num = 2

Python opencv 读取视频中的图片_第1张图片

  • clip_num=1

Python opencv 读取视频中的图片_第2张图片


参考

python实现读取和保存视频: https://blog.csdn.net/weixin_52777510/article/details/119872183

你可能感兴趣的:(Python,opencv,python,音视频)