python利用opencv保存、播放视频

 更新时间:2020年11月02日 09:52:55   作者:天乔巴夏丶  
这篇文章主要介绍了python利用opencv保存、播放视频,帮助大家更好的利用python处理视频,感兴趣的朋友可以了解下

代码已上传至:https://gitee.com/tqbx/python-opencv/tree/master/Getting_started_videos

目标

学习读取视频,播放视频,保存视频。
学习从相机中捕捉帧并展示。
学习cv2.VideoCapture(),cv2.VideoWriter()的使用

从相机中捕捉视频

通过自带摄像头捕捉视频,并将其转化为灰度视频显示出来。

基本步骤如下:

1.首先创建一个VideoCapture对象,它的参数包含两种:

  • 设备索引,指定摄像机的编号。
  • 视频文件的名称。

2.逐帧捕捉。

3.释放捕捉物。

import numpy as np
import cv2 as cv
cap = cv.VideoCapture(0)
if not cap.isOpened():
  print("Cannot open camera")
  exit()
while True:
  # Capture frame-by-frame
  ret, frame = cap.read()
  # if frame is read correctly ret is True
  if not ret:
    print("Can't receive frame (stream end?). Exiting ...")
    break
  # Our operations on the frame come here
  gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
  # Display the resulting frame
  cv.imshow('frame', gray)
  if cv.waitKey(1) == ord('q'):
    break
# When everything done, release the capture
cap.release()
cv.destroyAllWindows()

其他:

  • cap.read()返回布尔值,如果frame读取正确,为True,可以通过这个值判断视频是否已经结束。
  • 有时,cap可能会初始化捕获失败,可以通过cap.isOpened()来检查其是否被初始化,如果为True那是最好,如果不是,可以使用cap.open()来尝试打开它。
  • 当然,你可以使用cap.get(propId)的方式获取视频的一些属性,如帧的宽度,帧的高度,帧速等。propId是0-18的数字,每个数字代表一个属性,对应关系见底部附录。
  • 既然可以获取,当然也可以尝试设置,假设想要设置帧的宽度和高度为320和240:cap.set(3,320), cap.set(4,240)

从文件中播放视频

代码和从相机中捕获视频基本相同,不同之处在于传入VideoCapture的参数,此时传入视频文件的名称。

在显示每一帧的时候,可以使用cv2.waitKey()设置适当的时间,如果值很小,视频将会很快。正常情况下,25ms就ok。

import numpy as np
import cv2

cap = cv2.VideoCapture('vtest.avi')

while(cap.isOpened()):
  ret, frame = cap.read()

  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  cv2.imshow('frame',gray)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break

cap.release()
cv2.destroyAllWindows()

保存视频

1.创建一个VideoWriter 对象,指定如下参数:

  • 输出的文件名,如output.avi。
  • FourCC code。
  • 每秒的帧数fps。
  • 帧的size。

2.FourCC code传递有两种方式:

  • fourcc = cv2.VideoWriter_fourcc(*'XVID')
  • fourcc = cv2.VideoWriter_fourcc('X','V','I','D')

3.FourCC是一个用于指定视频编解码器的4字节代码。

  • In Fedora: DIVX, XVID, MJPG, X264, WMV1, WMV2. (XVID is more preferable. MJPG results in high size video. X264 gives very small size video)
  • In Windows: DIVX (More to be tested and added)
  • In OSX : (I don't have access to OSX. Can some one fill this?)
import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
  ret, frame = cap.read()
  if ret==True:
    frame = cv2.flip(frame,0)

    # write the flipped frame
    out.write(frame)

    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break
  else:
    break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

附录

  • CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds or video capture timestamp.
  • CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
  • CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.
  • CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
  • CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
  • CV_CAP_PROP_FPS Frame rate.
  • CV_CAP_PROP_FOURCC 4-character code of codec.
  • CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
  • CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
  • CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
  • CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
  • CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
  • CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
  • CV_CAP_PROP_HUE Hue of the image (only for cameras).
  • CV_CAP_PROP_GAIN Gain of the image (only for cameras).
  • CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
  • CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
  • CV_CAP_PROP_WHITE_BALANCE_U The U value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_WHITE_BALANCE_V The V value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_ISO_SPEED The ISO speed of the camera (note: only supported by DC1394 v 2.x backend currently)
  • CV_CAP_PROP_BUFFERSIZE Amount of frames stored in internal buffer memory (note: only supported by DC1394 v 2.x backend currently)

参考阅读

Getting Started with Videos

作者:天乔巴夏丶
出处:https://www.cnblogs.com/summerday152/
本文已收录至Gitee:https://gitee.com/tqbx/JavaBlog
若有兴趣,可以来参观本人的个人小站:https://www.hyhwky.com

以上就是python利用opencv保存、播放视频的详细内容,更多关于python opencv的资料请关注脚本之家其它相关文章!

相关文章

  • Python增量循环删除MySQL表数据的方法

    Python增量循环删除MySQL表数据的方法

    这篇文章主要介绍了Python增量循环删除MySQL表数据的相关资料,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下
    2016-09-09
  • Python学习笔记基本数据结构之序列类型list tuple range用法分析

    Python学习笔记基本数据结构之序列类型list tuple range用法分析

    这篇文章主要介绍了Python学习笔记基本数据结构之序列类型list tuple range用法,结合具体实例形式分析了Python序列类型list tuple range基本概念、定义与使用技巧,需要的朋友可以参考下
    2019-06-06
  • Python数据类型相互转换

    Python数据类型相互转换

    当涉及数据类型转换时,Python提供了多种内置函数来执行不同类型之间的转换,本文主要介绍了Python数据类型相互转换,具有一定的参考价值,感兴趣的可以了解一下
    2023-09-09
  • 利用Python代码制作过年春联

    利用Python代码制作过年春联

    这篇文章主要介绍了如何利用代码编写过年的春联,文中一共介绍了两种方法,一是利用HTML+CSS+JS,二是利用Python,感兴趣的可以试一试
    2022-01-01
  • Python实现绘制自定义形状的词云示例

    Python实现绘制自定义形状的词云示例

    这篇文章主要介绍了Python实现绘制自定义形状的词云示例,通过将一段文本中出现频率高的单词按其出现频率大小以及颜色深浅排列成一个词云图形,从而更好地展示文本中的信息,需要的朋友可以参考下
    2022-10-10
  • 一文学会Python列表list的使用

    一文学会Python列表list的使用

    这篇文章主要为大家介绍了Python列表list的使用全面解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-06-06
  • 如何使用 Poetry 进行 Python 项目管理

    如何使用 Poetry 进行 Python 项目管理

    本文介绍了如何安装、卸载和管理Poetry,以及如何查看其版本和位置,此外,还详细说明了如何使用Poetry安装项目依赖,包括依赖解析、锁定、虚拟环境管理等优势,感兴趣的朋友一起看看吧
    2024-11-11
  • 使用Streamlit和Pandas实现带有可点击链接的数据表格

    使用Streamlit和Pandas实现带有可点击链接的数据表格

    这篇文章主要为大家详细介绍了如何利用 Streamlit 和 Pandas 在 Python 中创建一个带有可点击链接的数据表格,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-11-11
  • 使用国内镜像源优化pip install下载的方法步骤

    使用国内镜像源优化pip install下载的方法步骤

    在Python开发中,pip 是一个不可或缺的工具,用于安装和管理Python包,然而,由于默认的PyPI服务器位于国外,国内用户在安装依赖时可能会遇到下载速度慢、连接不稳定等问题,所以本文将详细介绍如何使用国内镜像源来加速pip install -r requirements.txt的过程
    2025-03-03
  • Python pip更新的两种方式详解

    Python pip更新的两种方式详解

    Pip是用于管理Python软件包的常用命令,Pip命令还用于更新/升级已经安装的Python软件包,下面这篇文章主要给大家介绍了关于Python pip更新的两种方式,需要的朋友可以参考下
    2023-02-02

最新评论