python利用opencv保存、播放视频


Posted in Python onNovember 02, 2020

代码已上传至: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 相关文章推荐
python实现的防DDoS脚本
Feb 08 Python
python通过自定义isnumber函数判断字符串是否为数字的方法
Apr 23 Python
Python中使用urllib2模块编写爬虫的简单上手示例
Jan 20 Python
Python的净值数据接口调用示例分享
Mar 15 Python
python 获取键盘输入,同时有超时的功能示例
Nov 13 Python
对python xlrd读取datetime类型数据的方法详解
Dec 26 Python
python tkinter实现界面切换的示例代码
Jun 14 Python
python3实现猜数字游戏
Dec 07 Python
jupyter实现重新加载模块
Apr 16 Python
python 使用事件对象asyncio.Event来同步协程的操作
May 04 Python
如何用python反转图片,视频
Apr 24 Python
python中的None与NULL用法说明
May 25 Python
python获得命令行输入的参数的两种方式
Nov 02 #Python
Python+OpenCV检测灯光亮点的实现方法
Nov 02 #Python
python获取命令行参数实例方法讲解
Nov 02 #Python
Windows环境下Python3.6.8 importError: DLLload failed:找不到指定的模块
Nov 01 #Python
详解tensorflow之过拟合问题实战
Nov 01 #Python
python cookie反爬处理的实现
Nov 01 #Python
10个python爬虫入门实例(小结)
Nov 01 #Python
You might like
新浪新闻小偷
2006/10/09 PHP
在普通HTTP上安全地传输密码
2007/07/21 PHP
PHP+jquery实时显示网站在线人数的方法
2015/01/04 PHP
php编写的抽奖程序中奖概率算法
2015/05/14 PHP
php $_SESSION会员登录实例分享
2021/01/19 PHP
PHP 的比较运算与逻辑运算详解
2016/05/12 PHP
php smtp实现发送邮件功能
2017/06/22 PHP
MC Dialog js弹出层 完美兼容多浏览器(5.6更新)
2010/05/06 Javascript
鼠标滚轴控制文本框值的JS代码
2013/11/19 Javascript
利用javascript实现禁用网页上所有文本框,下拉菜单,多行文本域
2013/12/14 Javascript
模拟一个类似百度google的模糊搜索下拉列表
2014/04/15 Javascript
JS修改iframe页面背景颜色的方法
2015/04/01 Javascript
基于vue.js实现侧边菜单栏
2017/03/20 Javascript
vue 表单之通过v-model绑定单选按钮radio
2019/05/13 Javascript
这15个Vue指令,让你的项目开发爽到爆
2019/10/11 Javascript
浅谈vue 多个变量同时赋相同值互相影响
2020/08/05 Javascript
分享一个常用的Python模拟登陆类
2015/03/29 Python
Python中的列表生成式与生成器学习教程
2016/03/13 Python
Python从零开始创建区块链
2018/03/06 Python
解决python selenium3启动不了firefox的问题
2018/10/13 Python
Python3利用Dlib实现摄像头实时人脸检测和平铺显示示例
2019/02/21 Python
Python下简易的单例模式详解
2019/04/08 Python
Ubuntu下Anaconda和Pycharm配置方法详解
2019/06/14 Python
Series和DataFrame使用简单入门
2019/11/13 Python
numpy ndarray 按条件筛选数组,关联筛选的例子
2019/11/26 Python
利用python3筛选excel中特定的行(行值满足某个条件/行值属于某个集合)
2020/09/04 Python
CSS3动画:5种预载动画效果实例
2017/04/05 HTML / CSS
linux面试题参考答案(11)
2016/11/26 面试题
旅游管理毕业生自荐书
2014/02/02 职场文书
企业党员个人自我评价
2014/09/20 职场文书
法律进社区活动总结
2015/05/07 职场文书
2015年扶贫帮困工作总结
2015/05/20 职场文书
解决Laravel使用验证时跳转到首页的问题
2021/11/17 PHP
Oracle中update和select 关联操作
2022/01/18 Oracle
Android开发手册Chip监听及ChipGroup监听
2022/06/10 Java/Android
Win11如何查看显卡型号 Win11查看显卡型号的方法
2022/08/14 数码科技