一、视频获取(开启、保存、修改)
1、开启摄像头-cv2.VideoCapture(0)
&ret, frame=cap.read()
-
函数1:
cv2.VideoCapture()
• 参数说明:0,1代表电脑摄像头,或视频文件路径。 -
函数2:
ret,frame = cap.read()
-
说明:cap.read()按帧读取视频,
• Ret:返回布尔值True/False,如果读取帧是正确的则返回True, 如果文件读取到结尾,它的返回值就为False;
• Frame:每一帧的图像,是个三维矩阵。
下面的程序将使用opencv调用摄 像头,并实时播放摄像头中画面, 按下“q”键结束播放.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while (True):
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()
2、视频的读取与保存-cv2.VideoWriter_fourcc()
&cv2.VideoWriter('output.avi',fourcc, 20.0,(640,480))
- 指定写入视频帧编码格式
函数:fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
-
创建VideoWriter对象
• 函数out =cv2.VideoWriter('output.avi',fourcc, 20.0,(640,480))
-
参数说明:
• 参数1:保存视频路径+名字;
• 参数2:FourCC 为4 字节码,确定视频的编码格式;
• 参数3:播放帧率
• 参数4:大小
• 参数5:默认为True,彩色图
import cv2
#调用摄像头函数cv2.VideoCapture,参数0:系统摄像头
cap = cv2.VideoCapture(0)
#创建编码方式
#mp4:'X','V','I','D'avi:'M','J','P','G'或'P','I','M','1' flv:'F','L','V','1'
fourcc = cv2.VideoWriter_fourcc('F','L','V','1')
#创建VideoWriter对象
out = cv2.VideoWriter('output_1.flv',fourcc, 20.0, (640,480))
#创建循环结构进行连续读写
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
3、修改视频格式
import numpy as np
import cv2
cap = cv2.VideoCapture('output_1.flv')
fourcc = cv2.VideoWriter_fourcc('M','J','P','G')
fps = cap.get(cv2.CAP_PROP_FPS)
print(fps)
# 视频图像的宽度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# 视频图像的长度
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(frame_width)
print(frame_height)
#创建VideoWriter对象
out = cv2.VideoWriter('output_1_new.mp4',fourcc, fps,(frame_width,frame_height))
while(True):
ret, frame = cap.read()
if ret==True:
# 水平翻转
frame = cv2.flip(frame,1)
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey