Video Read and Write的代码注释:
import cv2 as cv
import numpy as np
capture = cv.VideoCapture("dataset/train/test_cp.avi")
# capture = cv.VideoCapture(0) 打开摄像头
# 此处我是先打开摄像头录制一段视频
# 视频保存在所在环境文件夹里,录制时按esc结束录制
# 完成后读取所录制的视频
height = capture.get(cv.CAP_PROP_frame_HEIGHT)
width = capture.get(cv.CAP_PROP_frame_WIDTH)
count = capture.get(cv.CAP_PROP_frame_COUNT)
fps = capture.get(cv.CAP_PROP_FPS)
print(height, width, count, fps)
out = cv.VideoWriter("dataset/train/test_cp.avi", cv.VideoWriter_fourcc('D', 'I', 'V', 'X'), 15,
(np.int(width), np.int(height)), True)
while True:
ret, frame = capture.read()
if ret is True:
cv.imshow("video-input", frame)
out.write(frame)
c = cv.waitKey(50)
if c == 27: # ESC
break
else:
break
capture.release()
out.release()
结果如图:
读取出视频,并将视频保存
cv.VideoCapture(path):path填写视频的路径
cv.VideoCapture(0):path填写为0的话,默认调用摄像头
注:不支持音频编码与解码保存,不是一个音视频处理的库!保存文件最大支持单个文件为2G
详细参考此代码,源自博客:
#include#include using namespace std; using namespace cv; int main() { //存放读取的每一帧和被转化后的每一帧 Mat in_f, out_f; //打开自带摄像头 VideoCapture readCapture(0); //判断摄像头是否打开成功 if (!readCapture.isOpened()) { cout << "摄像头打开错误!" << endl; return -1; } //获取读入视频文件的高度和宽度 int width=(int)readCapture.get(CAP_PROP_frame_WIDTH); int height=(int)readCapture.get(CAP_PROP_frame_HEIGHT); //定义存放读取视频的地址 char myVideo[] = "D:/test/myVideo3.avi"; //定义每一秒读取的帧数 double fps = 30; //按照规定的帧数写入读取的视频文件 //当存入视频为灰度色彩时,isColor必须设置为0 //否则,不需要写最后一个参数,否则会出现问题。 VideoWriter writerCapture(myVideo,VideoWriter::fourcc('X', 'V', 'I', 'D'),fps,Size(width,height),0); if (!writerCapture.isOpened()) { cout << "写入视频错误" << endl; return -1; } //显示摄像头读取的视频和转换成灰度空间的视频文件 while (true) { //从摄像机读取帧(抓取并解码) readCapture >> in_f; //将帧转换为灰度 cvtColor(in_f, out_f, COLOR_BGR2GRAY); //将幀写入视频文件(编码并保存) writerCapture << out_f; imshow("read", in_f); imshow("write", out_f); if (waitKey(1000 / fps) >= 0) { break; } } readCapture.release(); return 0; }
有关视频还有同上代码博主的视频基础



