python如何播放视频_OpenCV视频操作

使用工具Python3.5,

使用库numpy;opencv

1.用摄像头捕获视频

cv2.VideoCapture() :0为默认计算机默认摄像头,1可以更换来源;

~~~

import numpy as np

import cv2

cap = cv2.VideoCapture(0)

while(True):

#capture frame-by-frame

ret , frame = cap.read()

#our operation on the frame come here

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

#display the resulting frame

cv2.imshow('frame',gray)

if cv2.waitKey(1) &0xFF ==ord('q'): #按q键退出

break

#when everything done , release the capture

cap.release()

cv2.destroyAllWindows()

~~~

当代码报错时,可以使用cap.isOpened()来检查是否成功初始化了,返回值是True,就没有问题,否则就要使用cap.open()。

可以使用cap.get(propId)来获取视频的一些参数信息。propId可以是0到18之间的任何数,每一个数代表一个属性,自己可以尝试一下。

其中一些值可以使用cap.set(propId,value)来修改,例如cap.get(3)和cap.get(4)来查看每一帧的宽和高,默认是640x480。我们可以使用ret=cap.set(3,320)和ret = cap.set(4,240)来把宽和高改成320x240。

2.从文件中播放视频

把设备索引号改成文件名即可。在播放每一帧时,使用cv2.waitKey()适当持续时间,一般可以设置25ms。

~~~

import numpy as np

import cv2

cap=cv2.VideoCapture('filename.avi')#文件名及格式

while(True):

#capture frame-by-frame

ret , frame = cap.read()

#our operation on the frame come here

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

#display the resulting frame

cv2.imshow('frame',gray)

if cv2.waitKey(1) &0xFF ==ord('q'): #按q键退出

break

#when everything done , release the capture

cap.release()

cv2.destroyAllWindows()

~~~

代码中尝试修改视频流的一些属性;

![](https://box.kancloud.cn/00e7b470be24d10b99bd818751917c51_458x725.jpg)

![](https://box.kancloud.cn/bfe1412f9928c24f3711d654682ee9ba_578x242.jpg)

3.保存视频

创建一个VideoWrite的对象,确定输出文件名,指定FourCC编码,播放频率和帧的大小,最后是isColor标签True为彩色。

FourCC是一个4字节码,用来确定视频的编码格式。

1.In Fedora : DIVX , XVID , MJPG , X264 , WMV1 , WMV2

XVID是最好的,MJPG是高尺寸视频,X264得到小尺寸视频

2.In Windows : DIVX

3.In OSX :不知道用什么好

设置FourCC格式时,原文里采用了cv2.VideoWriter_fourcc()这个函数,若运行程序的时候显示这个函数不存在,可以改用了cv2.cv.CV_FOURCC这个函数。

~~~

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()

~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值