从摄像头捕获视频
要捕捉视频,需创建一个VideoCapture()对象,它的参数可以是设备索引或视频文件的名称。设备索引指定摄像头编号。0代表第一个摄像头、1代表第二个,以此类推。创建对象后,使用read()函数逐帧捕捉视频。最后需要释放对象。
保存视频
要保存视频,需创建一个VideoWriter()对象,指定输出文件名(例如:output.avi)。之后指定FourCC代码——FourCC是用于指定视频编解码器的4字节代码。接下来传递每秒帧数(fps)和帧大小。最后一个是isColor标志,如果它为True,编码器编码成彩色帧,否则编码成灰度帧。创建对象后,使用write()函数保存视频。最后需要释放对象。
FourCC is a 4-byte code used to specify the video codec. The list of available codes can be found in fourcc.org1. It is platform dependent.
官方教程
代码整合
import cv2
## Copyright (c) 2020, Wenquan.Zhao. All rights reserved.
def Operations(frame):
op1Frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
op2Frame = cv2.flip(frame,0)
return op2Frame
def saveVideo(saveVideoPath):
cap = cv2.VideoCapture(0)
if cap.isOpened():
print('[INFO]: Camera is opened!')
else:
cap.open()
print('[INFO]: Camera is opened!')
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(saveVideoPath, fourcc, 20.0, (640,480))
while(True):
ret, frame = cap.read()
if ret==True:
# operations on the frame
op2 = Operations(frame)
# write the frame
out.write(frame)
# display the frame after operation
cv2.imshow('frame', op2)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
if __name__=="__main__":
saveVideoPath = 'output.avi'
saveVideo(saveVideoPath)