美文网首页
012 视频文件的读写

012 视频文件的读写

作者: 几时见得清梦 | 来源:发表于2019-08-15 22:50 被阅读0次
    • API
      VideoCapture用于视频文件、摄像头的读取和打开。
      VideoWriter用于视频文件保存。
    1. 不支持音频编解码,故保存的视频无声音。

    C++

    #include<opencv2/opencv.hpp>
    #include<iostream>
    
    using namespace cv;
    using namespace std;
    
    int main(int argc, char** argv) {
        // 打开摄像头
        // VideoCapture capture(0); 
    
        // 打开文件
        VideoCapture capture;
        capture.open("D:/vcprojects/images/768x576.avi");
        if (!capture.isOpened()) {
            printf("could not read this video file...\n");
            return -1;
        }
        Size S = Size((int)capture.get(CV_CAP_PROP_FRAME_WIDTH),
            (int)capture.get(CV_CAP_PROP_FRAME_HEIGHT));
        int fps = capture.get(CV_CAP_PROP_FPS);
        printf("current fps : %d \n", fps);
        VideoWriter writer("D:/test.mp4", CV_FOURCC('D', 'I', 'V', 'X'), fps, S, true);
    
        Mat frame;
        namedWindow("camera-demo", CV_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;
    }
    

    Python

    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() # ret为bool类型
        if ret is True:
            cv.imshow("video-input", frame)
            out.write(frame)
            c = cv.waitKey(50) # 间隔50ms键盘进行监听
            if c == 27: # ESC
                break
        else:
            break
    
    capture.release() # 释放相机资源
    out.release()
    

    相关文章

      网友评论

          本文标题:012 视频文件的读写

          本文链接:https://www.haomeiwen.com/subject/zjxxsctx.html