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 相关文章推荐
Python3基础之基本数据类型概述
Aug 13 Python
python制作一个桌面便签软件
Aug 09 Python
Python win32com 操作Exce的l简单方法(必看)
May 25 Python
Python 12306抢火车票脚本 Python京东抢手机脚本
Feb 06 Python
在python带权重的列表中随机取值的方法
Jan 23 Python
django+echart数据动态显示的例子
Aug 12 Python
Django1.11配合uni-app发起微信支付的实现
Oct 12 Python
PYTHON实现SIGN签名的过程解析
Oct 28 Python
Django app配置多个数据库代码实例
Dec 17 Python
Python使用PyQt5/PySide2编写一个极简的音乐播放器功能
Feb 07 Python
python3爬虫中多线程进行解锁操作实例
Nov 25 Python
python使用PySimpleGUI设置进度条及控件使用
Jun 10 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下10件你也许并不了解的事情
2008/09/11 PHP
PHP MVC模式在网站架构中的实现分析
2010/03/04 PHP
php创建和删除目录函数介绍和递归删除目录函数分享
2014/11/18 PHP
Yii2学习笔记之汉化yii设置表单的描述(属性标签attributeLabels)
2017/02/07 PHP
[原创]PHP实现字节数Byte转换为KB、MB、GB、TB的方法
2017/08/31 PHP
ThinkPHP5框架缓存查询操作分析
2018/05/30 PHP
执行iframe中的javascript方法
2008/10/07 Javascript
javascript 操作Word和Excel的实现代码
2009/10/26 Javascript
JavaScript 学习笔记(五)
2009/12/31 Javascript
使用jQuery同时控制四张图片的伸缩实现代码
2013/04/19 Javascript
jQuery产品间断向下滚动效果核心代码
2014/05/08 Javascript
javascript常用的方法整理
2015/08/20 Javascript
详解Bootstrap插件
2016/04/25 Javascript
jQuery Ajax实现跨域请求
2017/01/21 Javascript
Angular中点击li标签实现更改颜色的核心代码
2017/12/08 Javascript
vue2.0 下拉框默认标题设置方法
2018/08/22 Javascript
vue项目中将element-ui table表格写成组件的实现代码
2019/06/12 Javascript
vue3修改link标签默认icon无效问题详解
2019/10/09 Javascript
Python对切片命名的实现方法
2018/10/16 Python
pycharm访问mysql数据库的方法步骤
2019/06/18 Python
Python格式化字符串f-string概览(小结)
2019/06/18 Python
python 中xpath爬虫实例详解
2019/08/26 Python
python enumerate内置函数用法总结
2020/01/07 Python
python标准库OS模块详解
2020/03/10 Python
序列化Python对象的方法
2020/08/01 Python
python 实现"神经衰弱"翻牌游戏
2020/11/09 Python
解决import tensorflow导致jupyter内核死亡的问题
2021/02/06 Python
英国最大的婴儿监视器网上商店:Baby Monitors Direct
2018/04/24 全球购物
幼儿园教师教育感言
2014/02/28 职场文书
农村婚庆司仪主持词
2014/03/15 职场文书
yy生日主持词
2014/03/20 职场文书
小学生作文评语大全
2014/04/21 职场文书
2014年城管个人工作总结
2014/12/08 职场文书
小石潭记导游词
2015/02/03 职场文书
年度考核表个人总结
2015/03/06 职场文书
Spring Boot mybatis-config 和 log4j 输出sql 日志的方式
2021/07/26 Java/Android