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实现自动更换ip的方法
May 05 Python
详解django中自定义标签和过滤器
Jul 03 Python
Python中使用多进程来实现并行处理的方法小结
Aug 09 Python
python爬虫之BeautifulSoup 使用select方法详解
Oct 23 Python
python网络爬虫学习笔记(1)
Apr 09 Python
Python批处理删除和重命名文件夹的实例
Jul 11 Python
python 计算平均平方误差(MSE)的实例
Jun 29 Python
Python collections.defaultdict模块用法详解
Jun 18 Python
python Paramiko使用示例
Sep 21 Python
Python 实现RSA加解密文本文件
Dec 30 Python
TensorFlow的环境配置与安装方法
Feb 20 Python
Python数据结构之队列详解
Mar 21 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
php中array_multisort对多维数组排序的方法
2020/06/21 PHP
php+ajax实现无刷新分页
2015/11/18 PHP
PHP从数组中删除元素的四种方法实例
2017/05/12 PHP
PHP自定义序列化接口Serializable用法分析
2017/12/29 PHP
js jquery做的图片连续滚动代码
2008/01/06 Javascript
一个基于jquery的图片切换效果
2010/07/06 Javascript
javascript自适应宽度的瀑布流实现思路
2013/02/20 Javascript
jQuery判断密码强度实现思路及代码
2013/04/24 Javascript
jquery获取radio值实例
2014/10/16 Javascript
js实现九宫格图片半透明渐显特效的方法
2015/02/16 Javascript
JavaScript入门系列之知识点总结
2016/03/24 Javascript
JS判断图片是否加载完成方法汇总(最新版)
2016/05/13 Javascript
JavaScript每天必学之数组和对象部分
2016/09/17 Javascript
Ztree新增角色和编辑角色回显问题的解决
2016/10/25 Javascript
AngularJS 防止页面闪烁的方法
2017/03/09 Javascript
nodejs和C语言插入mysql数据库乱码问题的解决方法
2017/04/14 NodeJs
js实现图片局部放大效果详解
2019/03/18 Javascript
微信小程序iBeacon测距及稳定程序的实现解析
2019/07/31 Javascript
TypeScript之调用栈的实现
2019/12/31 Javascript
[38:21]2014 DOTA2国际邀请赛中国区预选赛5.21 TongFu VS LGD-CDEC
2014/05/22 DOTA
[16:19]教你分分钟做大人——风暴之灵
2015/03/11 DOTA
python 定时修改数据库的示例代码
2018/04/08 Python
Python 3.3实现计算两个日期间隔秒数/天数的方法示例
2019/01/07 Python
详解python算法之冒泡排序
2019/03/05 Python
详解Python Matplotlib解决绘图X轴值不按数组排序问题
2019/08/05 Python
python实现获取单向链表倒数第k个结点的值示例
2019/10/24 Python
Python序列化与反序列化pickle用法实例
2019/11/11 Python
使用python+poco+夜神模拟器进行自动化测试实例
2020/04/23 Python
浅析python 动态库m.so.1.0错误问题
2020/05/09 Python
一款纯css3实现的tab选项卡的实列教程
2014/12/11 HTML / CSS
吉尔德利巧克力公司:Ghirardelli Chocolate Company
2019/03/27 全球购物
会计电算化个人求职信范文
2014/01/24 职场文书
心理咨询承诺书
2014/05/20 职场文书
2015年终个人政治思想工作总结
2015/11/24 职场文书
趣味运动会口号
2015/12/24 职场文书
python中pycryto实现数据加密
2022/04/29 Python