opencv依赖了ffmpeg,所以可以轻松对avi视频文件进行操作。
打开视频文件或摄像头视频需要使用Opencv中的VideoCapture类,保存视频或摄像头视频到本地磁盘,需要使用Opencv中的VideoWriter类。
先上代码:
1 bool isInit= false;
2 VideoCapture *inputVideo=NULL;
3 VideoWriter *outputVideo=NULL;
4
5 JNIEXPORT void JNICALL
6 Java_org_opencv_samples_tutorial2_Tutorial2Activity_FindFeatures(JNIEnv *, jobject, jlong addrGray,
7 jlong addrRgba) {
8 Mat &mGr = *(Mat *) addrGray;
9 Mat &mRgb = *(Mat *) addrRgba;
10 vector<KeyPoint> v;
11
12 looperAddNum++;
13 if (looperAddNum > 15) {
14 looperAddNum = 0;
15 if (looperIndexNum < 100)
16 looperIndexNum += 1;
17 }
18
19
20
21 // code start-----------------------------------------------------------------------------
22
23 if (!isInit){
24 LOGI("index start");
25 const string source = "/data/data/org.opencv.samples.tutorial2/cache/Megamind.avi"; // the source file name
26 inputVideo=new VideoCapture(source.c_str());
27 if (!inputVideo->isOpened()){
28 LOGI("open video error");
29 return;
30 }
31 Mat lsFrame;
32 *inputVideo>> lsFrame;
33 if (lsFrame.empty())
34 return;
35 string::size_type pAt = source.find_last_of('.'); // Find extension point
36 const string NAME = source.substr(0, pAt) + "R" + ".avi"; // Form the new name with container
37 LOGI("index looper %d %d", lsFrame.cols, lsFrame.rows);
38 outputVideo=new VideoWriter();
39 outputVideo->open(NAME, VideoWriter::fourcc('M', 'J', 'P', 'G'), 25, Size(lsFrame.cols, lsFrame.rows), true);
40 if (!outputVideo->isOpened())
41 {
42 LOGI("index open video error %s", NAME.c_str());
43 return;
44 }
45 isInit= true;
46 }
47
48
49
50
51 if (isInit){
52 Mat videoFrame;
53 *inputVideo >> videoFrame;
54 if (videoFrame.empty())
55 return;
56 // show video
57 Mat dstW = mRgb(Rect(0,0, videoFrame.cols, videoFrame.rows));
58 cvtColor(videoFrame, dstW, COLOR_RGB2BGRA);
59
60 int channel = 2; // Select the channel to save
61 Mat res;
62 vector<Mat> spl;
63 split(videoFrame, spl); // process - extract only the correct channel
64 for (int i =0; i < 3; ++i)
65 if (i != channel)
66 spl[i] = Mat::zeros(Size(videoFrame.cols, videoFrame.rows), spl[0].type());
67 merge(spl, res);
68 *outputVideo << res;
69 }
70
71
72 // code end-----------------------------------------------------------------------------
73 }
代码说明:
1、使用VideoCapture读内容文件获取视频信息。
2、初始化输出视频VideoWriter。
3、开始读取mat 写入 VideoWriter。
4、同时将其中两个通道数据设置为0(黑色)。
编解码器标识说明:
CV_FOURCC(‘P’, ‘I’, ‘M’, ‘1’) = MPEG-1 codec
CV_FOURCC(‘M’, ‘J’, ‘P’, ‘G’) = motion-jpeg codec
CV_FOURCC(‘M’, ‘P’, ‘4’, ‘2’) = MPEG-4.2 codec
CV_FOURCC(‘D’, ‘I’, ‘V’, ‘3’) = MPEG-4.3 codec
CV_FOURCC(‘D’, ‘I’, ‘V’, ‘X’) = MPEG-4 codec
CV_FOURCC(‘U’, ‘2’, ‘6’, ‘3’) = H263 codec
CV_FOURCC(‘I’, ‘2’, ‘6’, ‘3’) = H263I codec
CV_FOURCC(‘F’, ‘L’, ‘V’, ‘1’) = FLV1 codec