天天看點

OpenCV之視訊操作一、讀視訊三、寫視訊

文章目錄

  • 一、讀視訊
    • 1.打開視訊檔案
    • 2.捕獲攝像頭
    • 3.open()
    • 4.讀取到圖像中
    • 5.視訊打開的例子
  • 三、寫視訊
    • 1.VideoWriter
    • 2.函數
      • (1)是否成功建立
      • (2)寫入
    • 3.幀率fps
    • 4.例子

一、讀視訊

1.打開視訊檔案

2.捕獲攝像頭

這個可能是

,也可能是

1

2

3

4

。一個個試試

3.open()

VideoCapture capture;
capture.open(0);
           

4.讀取到圖像中

直接重載操作符

>>

writer >> frame;

5.視訊打開的例子

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;


int main()
{
    Mat image;
    VideoCapture capture;
    capture.open(0);
    if(capture.isOpened())
    {
        cout << "Capture is opened" << endl;
        for(;;)
        {
            capture >> image;
            if(image.empty())
                break;
            imshow("Sample", image);
            if(waitKey(10) >= 0)
                break;
        }
    }
    else
    {
        cout << "No capture" << endl;
        waitKey(0);
    }
    return 0;
}
           

三、寫視訊

1.VideoWriter

cv::VideoWriter::VideoWriter	(	
	const String & 	filename,
	int 			fourcc,
	double 			fps,
	Size 			frameSize,
	bool 			isColor = true 
)		
           
  • filename:如

    xxx.avi

  • fourcc:如

    VideoWriter::fourcc('M', 'J', 'P', 'G')

  • fps:幀率。意思是一秒有多少幀,決定一秒配置設定幾個寫入的幀。
  • frameSize:

    Size(圖檔的列寬,行高)

  • isColor:不管了

2.函數

(1)是否成功建立

成功初始化傳回true

(2)寫入

或者直接重載操作符

<<

writer << frame;

3.幀率fps

每秒25幀

OpenCV之視訊操作一、讀視訊三、寫視訊

每秒1幀

OpenCV之視訊操作一、讀視訊三、寫視訊

4.例子

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main()
{
	// 視訊幀,圖檔行高400,列寬600
	Mat frame(400, 600, CV_8UC3);

	// 建立 writer,并指定 FOURCC、FPS和Size(圖檔的列寬,行高)
	VideoWriter writer = VideoWriter("myvideo.avi", VideoWriter::fourcc('M', 'J', 'P', 'G'), 25, Size(frame.cols, frame.rows));

	// 檢查是否成功建立
	if (!writer.isOpened())
	{
		cerr << "Can not create video file.\n";
		return -1;
	}

	for (int i = 0; i < 100; i++)
	{
		// 将圖像置為黑色
		frame = Scalar::all(0);
		// 将整數 i 轉為 i 字元串類型
		char text[128];
		sprintf(text, "%d", i);
		// 将數字繪到畫面上
		putText(frame, text, Point(200, 200), FONT_HERSHEY_SCRIPT_SIMPLEX, 3,
				Scalar(0, 0, 255), 3);
		// 将圖像寫入視訊
		writer << frame;
	}
	return 0;
}
           

opencv–讀寫視訊