从相机中读取视频
import numpy as np
import cv2 as cv
#选择摄像头
cap = cv.VideoCapture(0)
#如果摄像头没打开,后面程序不执行,重新调
if not cap.isOpened():
print("Cannot open camera")
exit()
#死循环
while True:
#ret返回是否正确读取了帧,frame为帧传递对象
ret,frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#选取风格
gray = cv.cvtColor(frame,cv.COLOR_BGR2RGBA)
#显示结果
cv.imshow('frame',gray)
if cv.waitKey(1) == ord('q'):
break
#工作完成,释放资源
cap.release()
cv.destroyAllWindows()
从文件读取视频
import numpy as np
import cv2 as cv
#将摄像头索引换成视频名称即可
cap = cv.VideoCapture('output.avi')
#如果摄像头没打开,后面程序不执行,重新调
if not cap.isOpened():
print("Cannot open camera")
exit()
#死循环
while True:
#ret返回是否正确读取了帧,frame为帧传递对象
ret,frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#选取风格
gray = cv.cvtColor(frame,cv.COLOR_BGR2RGBA)
#显示结果
cv.imshow('frame',gray)
if cv.waitKey(1) == ord('q'):
break
#工作完成,释放资源
cap.release()
cv.destroyAllWindows()
保存视频
import numpy as np
import cv2 as cv
#选择摄像头
cap = cv.VideoCapture(0)
#建立输出视频对象,并选择视频格式
fourcc = cv.VideoWriter_fourcc(*'XVID')
#输出
out = cv.VideoWriter('output.avi',fourcc, 20.0,(640,480))
#如果摄像头没打开,后面程序不执行,重新调
if not cap.isOpened():
print("Cannot open camera")
exit()
#死循环
while True:
#ret返回是否正确读取了帧,frame为帧传递对象
ret,frame = cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
#视频角度变换
frame = cv.flip(frame,0)
#输出
out.write(frame)
#显示结果
cv.imshow('frame',frame)
if cv.waitKey(1) == ord('q'):
break
#工作完成,释放资源
cap.release()
out.release()
cv.destroyAllWindows()