import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
1、从摄像头捕获视频
从摄像头捕获视频流,并在窗口“frame”中输出,按“q”键停止输出视频流。
cv.VideoCapture()函数,参数可以为设备号或者是视频路径。设备号为0代表一个设备,1为第二台设备
cap.read()函数的返回一个bool值,即为ret的值,检查视频流是否正确读取。frame为视频流的值。
cap.get(popId)函数,获取cap对象的属性,像视频流的长度和宽度等
cap.set(popId,Value)函数,设置cap对象的属性
cv.cvtColor(frame, cv.COLOR_BGR2GRAY)函数,设置视频流的颜色
注意释放cap对象
cap = cv.VideoCapture(0)
while(True):
ret, frame = cap.read()
#print("ret = ",ret, "frame = ", frame)
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
2、从文件中读取视频
cap = cv.VideoCapture('vtest.avi')
while(cap.isOpened()):
ret, frame = cap.read()
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
cv.imshow('frame',gray)
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
3、保存视频
fourcc = cv.VideoWriter_fourcc(*’DIVX’)定义视频解码器(FourCC)
cv.VideoWriter(‘./videos/output.avi’,fourcc, 20.0, (640,480), isColor=True) 第一个参数为保存视频的地址;第二个参数为视频解码器;第三个参数为视频每秒多少帧;第四个参数为视频帧大小;第五个参数为视频帧是否是有颜色的默认为带颜色。
frame = cv.flip(frame,1) 视频翻转。默认情况为上下正常,左右相反。第二个参数为0表示y轴翻转;为1为x轴翻转;为-1都翻转。
cap = cv.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv.VideoWriter_fourcc(*'DIVX')
out = cv.VideoWriter('./videos/output.avi',fourcc, 20.0, (640,480), isColor=True)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv.flip(frame,1)
# write the flipped frame
out.write(frame)
cv.imshow('frame',frame)
if cv.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv.destroyAllWindows()