Opencv-视频文件的读写

视频文件的读写

    • 知识点
    • python代码
    • c++代码

知识点

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

  • CAP_PROP_FRAME_HEIGHT
  • CAP_PROP_FRAME_WIDTH
  • CAP_PROP_FRAME_COUNT
  • CAP_PROP_FPS
  • 不支持音频编码与解码保存,不是一个音视频处理的库!主要是分析与解析视频内容。保存文件最大支持单个文件为2G
  • PS:关于编码方式类型设置,可以用下的代码做参考!
    int type = static_cast(capture.get(CAP_PROP_FOURCC));
    VideoWriter out(“D:/test.mp4”, type, 15, Size(width, height), true);

python代码

import cv2 as cv
import numpy as np

capture = cv.VideoCapture("C:/Users/qqxd/Desktop/opencvcode/images/bike.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 is %d, width is %d , count is %d , fps is %d " %(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()

c++代码

#include
#include

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
	// 打开摄像头
	// VideoCapture capture(0); 

	// 打开文件
	VideoCapture capture;
	capture.open("C:/Users/qqxd/Desktop/opencvcode/images/bike.avi");
	if (!capture.isOpened()) {
		printf("could not read this video file...\n");
		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);
	printf("current fps : %d \n", fps);
	//在Opencv4中,CV_FOURCC(‘P’, ‘I’, ‘M’, ‘1’)CV_FOURCC(‘M’,‘J’,‘P’,‘G’),已经改为CAP_OPENCV_MJPEG
	VideoWriter writer("D:/test.mp4", CAP_OPENCV_MJPEG, fps, S, true);

	Mat frame;
	namedWindow("camera-demo", WINDOW_AUTOSIZE);
	while (capture.read(frame)) {
		imshow("camera-demo", frame);
		writer.write(frame);
		char c = waitKey(50);
		if (c == 27) {
			break;
		}
	}
	capture.release();
	writer.release();
	waitKey(0);
	return 0;
}

你可能感兴趣的:(Opencv)