天天看点

OpenCV-视频读写(java版)

@​​TOC​​

​​

​OpenCV 2 中提供了两个类来实现视频的读写。读视频的类是​

​VideoCapture​

​,写视频的类是 ​

​VideoWriter

读视频

VideoCapture 既可以从视频文件读取图像,也可以从摄像头读取图像。该类提供了一系列构造函数和方法打开视频文件或摄像头。下方对VideoCapture的常用方法进行说明

方法 说明

open()

VideoCapture()

open(index)

VideoCapture(index)

index表示要打开的视频捕获设备的ID

通过构造函数的方式打开第index个摄像头

(下方不再说明)

open(int index, int apiPreference)

apiPreference:媒体类型,缺省时默认为  CAP_ANY

(更多查看Videoio类)

open(int index, int apiPreference, MatOfInt params)
open(String filename)

打开一个视频文件。

filename:文件地址

open(String filename, int apiPreference)
open(String filename, int apiPreference, MatOfInt params)

示例:

public static void main(String[] args) {
        String libraryPath= System.getProperty("user.dir")+"\\lib\\opencv_java460.dll";
        System.load(libraryPath);
        VideoCapture vc = new VideoCapture();
        //打开摄像头
        vc.open(0);
        Mat mat = new Mat();
        while(vc.read(mat)){
            for(int i=0;i<mat.rows();i++){
                for (int j=0;j<mat.cols();j++){
                    if (i>(mat.rows()/2)   ){
                        //给相应位置赋予像素值
                        mat.put(i,j,144,238,144);
                    }
                }
            }
            HighGui.imshow("test", mat);
            HighGui.waitKey(1);
        }
        
        vc.release();
        //关闭窗口
        HighGui.destroyAllWindows();
  
    }      

参考文档: