【Opencv】使用 opencv-python 提取视频每一帧的图片

如何使用 opencv-python 提取视频每一帧的图片?

编程语言:Python

所需库:cv2

获取视频(创建 VideoCapture 对象)

使用 cv2.VideoCapture 类

Args:

  • filename – 文件路径;
  • device – 视频设备id ,若只有一个摄像头可以填 0,表示打开默认摄像头;
vc = cv2.VideoCapture(filename)

检验 VideoCapture 对象是否创境成功

使用 VideoCapture 对象的 isOpened 方法

# determine whether to open normally
if vc.isOpened():
    ret, frame = vc.read()
else:
    ret = False

若成功,返回 True。

按帧读取视频

使用 VideoCapture 对象的 read 方法

使用 VideoCapture 对象的 read 方法按帧读取视频,ret, frame 是 read 方法的两个返回值 ,其中 ret 是布尔值,如果能正确读取帧,则返回 True;如果文件读取到结尾,它的返回值就为 False。frame 就是每一帧的图像,是一个三维矩阵。

# loop read video frame
while ret:
    ret, frame = vc.read()

保存图片

使用 cv2.imwrite() 函数

第一个参数是文件名,第二个参数是图片资源。

cv2.imwrite(image_path, image)

播放每一帧时适当持续时间

使用 cv2.waitKey() 函数

cv2.waitKey(1)

参数 1 表示延时 1ms 切换到下一帧图像,对于视频而言;

参数 0 表示只显示当前帧图像,相当于视频暂停;

参数过大会因为延时过久而卡顿感觉到卡顿。

关闭视频文件

使用 VideoCapture 对象的 release 方法vc.release()

测试代码

"""
-------------------------------------
# -*- coding: utf-8 -*-
# @Time    : 2020/10/1 15:44:12
# @Author  : Giyn
# @Email   : giyn.jy@gmail.com
# @File    : video_processing.py
# @Software: PyCharm
-------------------------------------
"""

import cv2
import logging

# log information settings
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')


def save_image(num, image):
    """Save the images.

    Args:
        num: serial number
        image: image resource

    Returns:
        None
    """
    image_path = '../raw_pictures/{}.jpg'.format(str(num))
    cv2.imwrite(image_path, image)


file_path = '../videos/video_1.mp4'

vc = cv2.VideoCapture(file_path)  # import video files

# determine whether to open normally
if vc.isOpened():
    ret, frame = vc.read()
else:
    ret = False

count = 0  # count the number of pictures
frame_interval = 30  # video frame count interval frequency
frame_interval_count = 0

# loop read video frame
while ret:
    ret, frame = vc.read()
    # store operation every time f frame
    if frame_interval_count % frame_interval == 0:
        save_image(count, frame)
        logging.info("num:" + str(count) + ", frame: " +
                     str(frame_interval_count))
        count += 1
    frame_interval_count += 1
    cv2.waitKey(1)

vc.release()

运行结果

 

 

  • 2
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值