基于基础02 的基础上对视频进行取帧保存
代码如下:
package com.example.javacvstudy;
/**
* 本地摄像头截图
*/
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.opencv_core.Mat;
import org.springframework.boot.test.context.SpringBootTest;
import javax.swing.*;
@SpringBootTest
class CanmerCutImage {
static OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
public static void main(String[] args) throws FrameGrabber.Exception, InterruptedException {
//读取摄像头数据,创建摄像头对象,0表示本机摄像头,1表示外接摄像头
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
grabber.start(); //开始获取摄像头数据
CanvasFrame canvas = new CanvasFrame("摄像头");//新建一个窗口
canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setAlwaysOnTop(true);
int ex = 0;
while(true){
if(!canvas.isDisplayable()){//窗口是否关闭
grabber.stop();//停止抓取
System.exit(2);//退出
break;
}
canvas.showImage(grabber.grab());//获取摄像头图像并放到窗口上显示, 这里的Frame frame=grabber.grab(); frame是一帧视频图像
Mat mat = converter.convertToMat(grabber.grabFrame());
ex++;
opencv_imgcodecs.imwrite("d:\\temp\\img\\" + ex + ".jpg", mat);
Thread.sleep(1000);//50毫秒刷新一次图像
}
}
}
运行结果: