使用 opencv-python 提取视频每一帧的图片 - Go语言中文社区

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


计算机视觉是指用摄影机和计算机代替人眼对目标进行识别、跟踪和测量等机器视觉,并进一步做图像处理,用计算机处理成为更适合人眼观察或传送给仪器检测的图像,其任务有图像形成、图像处理、图像提取和图像的三维推理,而目标识别和面部识别也是很重要的研究领域。

OpenCV 的全称是 Open Source Computer Vision Library,是一个跨平台的计算机视觉库,其基于C/C++,支持 Linux/Windows/MacOS/Android/iOS,并提供了 Python,Matlab 和 Java 等语言的接口。

如何使用 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()

运行结果:

在这里插入图片描述

在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_45961774/article/details/108900495
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢