opencv-012-视频读写

知识点

VideoCapture 视频文件读取、摄像头读取、视频流读取
VideoWriter 视频写出、文件保存、

  • CAP_PROP_FRAME_HEIGHT #高度
  • CAP_PROP_FRAME_WIDTH #宽度
  • CAP_PROP_FRAME_COUNT #数量
  • CAP_PROP_FPS #帧率

不支持音频编码与解码保存,不是一个音视频处理的库!主要是分析与解析视频内容。保存文件最大支持单个文件为2G。

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 视频读写
*/
int main() {
// 打开摄像头
// VideoCapture capture(0);
// 打开视频文件
VideoCapture capture;
capture.open("../images/vtest.avi");
if (!capture.isOpened()) {
cout << "could not load video.." << endl;
return -1;
}

Size S = Size((int) capture.get(CAP_PROP_FRAME_WIDTH), (int) capture.get(CAP_PROP_FRAME_HEIGHT));
int fps = capture.get(CAP_PROP_FPS);
cout << "capture fps: " << fps << endl;
VideoWriter writer("D:/test.mp4", cv::VideoWriter::fourcc('D', 'I','V','X'), fps, S, true);

Mat frame;
while(capture.read(frame)){
imshow("input", frame);
writer.write(frame);
char c = waitKey(50);
if(c == 27){
break;
}
}
capture.release();
writer.release();

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import cv2 as cv
import numpy as np


capture = cv.VideoCapture("D:/vcprojects/images/768x576.avi")
# capture = cv.VideoCapture(0) 打开摄像头
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("D:/test.mp4", 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()

结果

代码地址

github