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中的魔法方法深入理解
Jul 09 Python
python3实现读取chrome浏览器cookie
Jun 19 Python
virtualenv实现多个版本Python共存
Aug 21 Python
python与caffe改变通道顺序的方法
Aug 04 Python
python里dict变成list实例方法
Jun 26 Python
django中使用POST方法获取POST数据
Aug 20 Python
解决在pycharm运行代码,调用CMD窗口的命令运行显示乱码问题
Aug 23 Python
python [:3] 实现提取数组中的数
Nov 27 Python
TensorFlow tf.nn.conv2d实现卷积的方式
Jan 03 Python
python logging模块的使用
Sep 07 Python
关于Python错误重试方法总结
Jan 03 Python
python中常用的数据结构介绍
Jan 12 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 301转向实现代码
2008/09/18 PHP
php中实现可以返回多个值的函数实例
2015/03/21 PHP
PHP JSON格式的中文显示问题解决方法
2015/04/09 PHP
支持中文、字母、数字的PHP验证码
2015/05/04 PHP
javascript匿名函数应用示例介绍
2014/03/07 Javascript
jQuery遍历json中多个map的方法
2015/02/12 Javascript
使用AngularJS 应用访问 Android 手机的图片库
2015/03/24 Javascript
javascript实现点击商品列表checkbox实时统计金额的方法
2015/05/15 Javascript
AngularJS整合Springmvc、Spring、Mybatis搭建开发环境
2016/02/25 Javascript
js 提交form表单和设置form表单请求路径的实现方法
2016/10/25 Javascript
easyui combobox开启搜索自动完成功能的实例代码
2016/11/08 Javascript
Javascript 闭包详解及实例代码
2016/11/30 Javascript
解决bootstrap中使用modal加载kindeditor时弹出层文本框不能输入的问题
2017/06/05 Javascript
JavaScrip关于创建常量的知识点
2017/12/07 Javascript
ajax前台后台跨域请求处理方式
2018/02/08 Javascript
基于cropper.js封装vue实现在线图片裁剪组件功能
2018/03/01 Javascript
vue better scroll 无法滚动的解决方法
2018/06/07 Javascript
微信小程序项目实践之九宫格实现及item跳转功能
2018/07/19 Javascript
微信小程序实现多个按钮的颜色状态转换
2019/02/15 Javascript
微信小程序 scroll-view 实现锚点跳转功能
2019/12/12 Javascript
[44:50]DOTA2上海特级锦标赛B组小组赛#2 VG VS Fnatic第二局
2016/02/26 DOTA
用python写asp详细讲解
2013/12/16 Python
python样条插值的实现代码
2018/12/17 Python
Django  ORM 练习题及答案
2019/07/19 Python
用python拟合等角螺线的实现示例
2019/12/27 Python
在python中实现求输出1-3+5-7+9-......101的和
2020/04/02 Python
Python如何定义一个函数
2015/09/01 面试题
abstract class和interface有什么区别
2013/08/04 面试题
生日主持词
2014/03/20 职场文书
小学语文课后反思精选
2014/04/25 职场文书
入股协议书范本
2014/11/01 职场文书
小学教师师德师风承诺书
2015/04/28 职场文书
离婚协议书范文2016
2016/03/18 职场文书
护理专业毕业自我鉴定
2019/08/12 职场文书
MySQL Innodb关键特性之插入缓冲(insert buffer)
2021/04/08 MySQL
《游戏王:大师决斗》将推出新卡牌包4月4日上线
2022/03/31 其他游戏